babylon.max.js 3.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. })();
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. })();
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = function (left, right) {
  551. var x = (left.x < right.x) ? left.x : right.x;
  552. var y = (left.y < right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. })();
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.TransformCoordinates = function (vector, transformation) {
  834. var result = Vector3.Zero();
  835. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  836. return result;
  837. };
  838. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  839. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  840. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  841. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  842. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  843. result.x = x / w;
  844. result.y = y / w;
  845. result.z = z / w;
  846. };
  847. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  848. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  849. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  850. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  851. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  852. result.x = rx / rw;
  853. result.y = ry / rw;
  854. result.z = rz / rw;
  855. };
  856. Vector3.TransformNormal = function (vector, transformation) {
  857. var result = Vector3.Zero();
  858. Vector3.TransformNormalToRef(vector, transformation, result);
  859. return result;
  860. };
  861. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  862. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  863. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  864. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  865. };
  866. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  867. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  868. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  869. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  870. };
  871. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  872. var squared = amount * amount;
  873. var cubed = amount * squared;
  874. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  875. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  876. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  877. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  878. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  879. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  880. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  881. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  882. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  883. return new Vector3(x, y, z);
  884. };
  885. Vector3.Clamp = function (value, min, max) {
  886. var x = value.x;
  887. x = (x > max.x) ? max.x : x;
  888. x = (x < min.x) ? min.x : x;
  889. var y = value.y;
  890. y = (y > max.y) ? max.y : y;
  891. y = (y < min.y) ? min.y : y;
  892. var z = value.z;
  893. z = (z > max.z) ? max.z : z;
  894. z = (z < min.z) ? min.z : z;
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  898. var squared = amount * amount;
  899. var cubed = amount * squared;
  900. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  901. var part2 = (-2.0 * cubed) + (3.0 * squared);
  902. var part3 = (cubed - (2.0 * squared)) + amount;
  903. var part4 = cubed - squared;
  904. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  905. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  906. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Lerp = function (start, end, amount) {
  910. var x = start.x + ((end.x - start.x) * amount);
  911. var y = start.y + ((end.y - start.y) * amount);
  912. var z = start.z + ((end.z - start.z) * amount);
  913. return new Vector3(x, y, z);
  914. };
  915. Vector3.Dot = function (left, right) {
  916. return (left.x * right.x + left.y * right.y + left.z * right.z);
  917. };
  918. Vector3.Cross = function (left, right) {
  919. var result = Vector3.Zero();
  920. Vector3.CrossToRef(left, right, result);
  921. return result;
  922. };
  923. Vector3.CrossToRef = function (left, right, result) {
  924. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  925. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  926. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  927. result.copyFrom(Tmp.Vector3[0]);
  928. };
  929. Vector3.Normalize = function (vector) {
  930. var result = Vector3.Zero();
  931. Vector3.NormalizeToRef(vector, result);
  932. return result;
  933. };
  934. Vector3.NormalizeToRef = function (vector, result) {
  935. result.copyFrom(vector);
  936. result.normalize();
  937. };
  938. Vector3.Project = function (vector, world, transform, viewport) {
  939. var cw = viewport.width;
  940. var ch = viewport.height;
  941. var cx = viewport.x;
  942. var cy = viewport.y;
  943. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  944. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  945. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  946. world.multiplyToRef(transform, matrix);
  947. matrix.multiplyToRef(viewportMatrix, matrix);
  948. return Vector3.TransformCoordinates(vector, matrix);
  949. };
  950. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  951. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  952. world.multiplyToRef(transform, matrix);
  953. matrix.invert();
  954. source.x = source.x / viewportWidth * 2 - 1;
  955. source.y = -(source.y / viewportHeight * 2 - 1);
  956. var vector = Vector3.TransformCoordinates(source, matrix);
  957. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  958. if (MathTools.WithinEpsilon(num, 1.0)) {
  959. vector = vector.scale(1.0 / num);
  960. }
  961. return vector;
  962. };
  963. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  964. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  965. world.multiplyToRef(view, matrix);
  966. matrix.multiplyToRef(projection, matrix);
  967. matrix.invert();
  968. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  969. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  970. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  971. if (MathTools.WithinEpsilon(num, 1.0)) {
  972. vector = vector.scale(1.0 / num);
  973. }
  974. return vector;
  975. };
  976. Vector3.Minimize = function (left, right) {
  977. var min = left.clone();
  978. min.MinimizeInPlace(right);
  979. return min;
  980. };
  981. Vector3.Maximize = function (left, right) {
  982. var max = left.clone();
  983. max.MaximizeInPlace(right);
  984. return max;
  985. };
  986. Vector3.Distance = function (value1, value2) {
  987. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  988. };
  989. Vector3.DistanceSquared = function (value1, value2) {
  990. var x = value1.x - value2.x;
  991. var y = value1.y - value2.y;
  992. var z = value1.z - value2.z;
  993. return (x * x) + (y * y) + (z * z);
  994. };
  995. Vector3.Center = function (value1, value2) {
  996. var center = value1.add(value2);
  997. center.scaleInPlace(0.5);
  998. return center;
  999. };
  1000. /**
  1001. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1002. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1003. * to something in order to rotate it from its local system to the given target system.
  1004. */
  1005. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1006. var rotation = Vector3.Zero();
  1007. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1008. return rotation;
  1009. };
  1010. /**
  1011. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1012. */
  1013. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1014. var u = axis1.normalize();
  1015. var w = axis3.normalize();
  1016. // world axis
  1017. var X = Axis.X;
  1018. var Y = Axis.Y;
  1019. // equation unknowns and vars
  1020. var yaw = 0.0;
  1021. var pitch = 0.0;
  1022. var roll = 0.0;
  1023. var x = 0.0;
  1024. var y = 0.0;
  1025. var z = 0.0;
  1026. var t = 0.0;
  1027. var sign = -1.0;
  1028. var nbRevert = 0;
  1029. var cross = Tmp.Vector3[0];
  1030. var dot = 0.0;
  1031. // step 1 : rotation around w
  1032. // Rv3(u) = u1, and u1 belongs to plane xOz
  1033. // Rv3(w) = w1 = w invariant
  1034. var u1 = Tmp.Vector3[1];
  1035. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1036. z = 1.0;
  1037. }
  1038. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1039. x = 1.0;
  1040. }
  1041. else {
  1042. t = w.z / w.x;
  1043. x = -t * Math.sqrt(1 / (1 + t * t));
  1044. z = Math.sqrt(1 / (1 + t * t));
  1045. }
  1046. u1.x = x;
  1047. u1.y = y;
  1048. u1.z = z;
  1049. u1.normalize();
  1050. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1051. cross.normalize();
  1052. if (Vector3.Dot(w, cross) < 0) {
  1053. sign = 1.0;
  1054. }
  1055. dot = Vector3.Dot(u, u1);
  1056. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1057. roll = Math.acos(dot) * sign;
  1058. if (Vector3.Dot(u1, X) < 0) {
  1059. roll = Math.PI + roll;
  1060. u1 = u1.scaleInPlace(-1);
  1061. nbRevert++;
  1062. }
  1063. // step 2 : rotate around u1
  1064. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1065. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1066. var w2 = Tmp.Vector3[2];
  1067. var v2 = Tmp.Vector3[3];
  1068. x = 0.0;
  1069. y = 0.0;
  1070. z = 0.0;
  1071. sign = -1.0;
  1072. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1073. x = 1.0;
  1074. }
  1075. else {
  1076. t = u1.z / u1.x;
  1077. x = -t * Math.sqrt(1 / (1 + t * t));
  1078. z = Math.sqrt(1 / (1 + t * t));
  1079. }
  1080. w2.x = x;
  1081. w2.y = y;
  1082. w2.z = z;
  1083. w2.normalize();
  1084. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1085. v2.normalize();
  1086. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1087. cross.normalize();
  1088. if (Vector3.Dot(u1, cross) < 0) {
  1089. sign = 1.0;
  1090. }
  1091. dot = Vector3.Dot(w, w2);
  1092. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1093. pitch = Math.acos(dot) * sign;
  1094. if (Vector3.Dot(v2, Y) < 0) {
  1095. pitch = Math.PI + pitch;
  1096. nbRevert++;
  1097. }
  1098. // step 3 : rotate around v2
  1099. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1100. sign = -1.0;
  1101. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1102. cross.normalize();
  1103. if (Vector3.Dot(cross, Y) < 0) {
  1104. sign = 1.0;
  1105. }
  1106. dot = Vector3.Dot(u1, X);
  1107. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1108. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1109. if (dot < 0 && nbRevert < 2) {
  1110. yaw = Math.PI + yaw;
  1111. }
  1112. ref.x = pitch;
  1113. ref.y = yaw;
  1114. ref.z = roll;
  1115. };
  1116. return Vector3;
  1117. })();
  1118. BABYLON.Vector3 = Vector3;
  1119. //Vector4 class created for EulerAngle class conversion to Quaternion
  1120. var Vector4 = (function () {
  1121. function Vector4(x, y, z, w) {
  1122. this.x = x;
  1123. this.y = y;
  1124. this.z = z;
  1125. this.w = w;
  1126. }
  1127. Vector4.prototype.toString = function () {
  1128. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1129. };
  1130. Vector4.prototype.getClassName = function () {
  1131. return "Vector4";
  1132. };
  1133. Vector4.prototype.getHashCode = function () {
  1134. var hash = this.x || 0;
  1135. hash = (hash * 397) ^ (this.y || 0);
  1136. hash = (hash * 397) ^ (this.z || 0);
  1137. hash = (hash * 397) ^ (this.w || 0);
  1138. return hash;
  1139. };
  1140. // Operators
  1141. Vector4.prototype.asArray = function () {
  1142. var result = [];
  1143. this.toArray(result, 0);
  1144. return result;
  1145. };
  1146. Vector4.prototype.toArray = function (array, index) {
  1147. if (index === undefined) {
  1148. index = 0;
  1149. }
  1150. array[index] = this.x;
  1151. array[index + 1] = this.y;
  1152. array[index + 2] = this.z;
  1153. array[index + 3] = this.w;
  1154. return this;
  1155. };
  1156. Vector4.prototype.addInPlace = function (otherVector) {
  1157. this.x += otherVector.x;
  1158. this.y += otherVector.y;
  1159. this.z += otherVector.z;
  1160. this.w += otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.add = function (otherVector) {
  1164. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1165. };
  1166. Vector4.prototype.addToRef = function (otherVector, result) {
  1167. result.x = this.x + otherVector.x;
  1168. result.y = this.y + otherVector.y;
  1169. result.z = this.z + otherVector.z;
  1170. result.w = this.w + otherVector.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.subtractInPlace = function (otherVector) {
  1174. this.x -= otherVector.x;
  1175. this.y -= otherVector.y;
  1176. this.z -= otherVector.z;
  1177. this.w -= otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.subtract = function (otherVector) {
  1181. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1182. };
  1183. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1184. result.x = this.x - otherVector.x;
  1185. result.y = this.y - otherVector.y;
  1186. result.z = this.z - otherVector.z;
  1187. result.w = this.w - otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1191. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1192. };
  1193. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1194. result.x = this.x - x;
  1195. result.y = this.y - y;
  1196. result.z = this.z - z;
  1197. result.w = this.w - w;
  1198. return this;
  1199. };
  1200. Vector4.prototype.negate = function () {
  1201. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1202. };
  1203. Vector4.prototype.scaleInPlace = function (scale) {
  1204. this.x *= scale;
  1205. this.y *= scale;
  1206. this.z *= scale;
  1207. this.w *= scale;
  1208. return this;
  1209. };
  1210. Vector4.prototype.scale = function (scale) {
  1211. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1212. };
  1213. Vector4.prototype.scaleToRef = function (scale, result) {
  1214. result.x = this.x * scale;
  1215. result.y = this.y * scale;
  1216. result.z = this.z * scale;
  1217. result.w = this.w * scale;
  1218. };
  1219. Vector4.prototype.equals = function (otherVector) {
  1220. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1221. };
  1222. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1223. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1224. return otherVector
  1225. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1226. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1227. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1228. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1229. };
  1230. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1231. return this.x === x && this.y === y && this.z === z && this.w === w;
  1232. };
  1233. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1234. this.x *= otherVector.x;
  1235. this.y *= otherVector.y;
  1236. this.z *= otherVector.z;
  1237. this.w *= otherVector.w;
  1238. return this;
  1239. };
  1240. Vector4.prototype.multiply = function (otherVector) {
  1241. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1242. };
  1243. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1244. result.x = this.x * otherVector.x;
  1245. result.y = this.y * otherVector.y;
  1246. result.z = this.z * otherVector.z;
  1247. result.w = this.w * otherVector.w;
  1248. return this;
  1249. };
  1250. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1251. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1252. };
  1253. Vector4.prototype.divide = function (otherVector) {
  1254. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1255. };
  1256. Vector4.prototype.divideToRef = function (otherVector, result) {
  1257. result.x = this.x / otherVector.x;
  1258. result.y = this.y / otherVector.y;
  1259. result.z = this.z / otherVector.z;
  1260. result.w = this.w / otherVector.w;
  1261. return this;
  1262. };
  1263. Vector4.prototype.MinimizeInPlace = function (other) {
  1264. if (other.x < this.x)
  1265. this.x = other.x;
  1266. if (other.y < this.y)
  1267. this.y = other.y;
  1268. if (other.z < this.z)
  1269. this.z = other.z;
  1270. if (other.w < this.w)
  1271. this.w = other.w;
  1272. return this;
  1273. };
  1274. Vector4.prototype.MaximizeInPlace = function (other) {
  1275. if (other.x > this.x)
  1276. this.x = other.x;
  1277. if (other.y > this.y)
  1278. this.y = other.y;
  1279. if (other.z > this.z)
  1280. this.z = other.z;
  1281. if (other.w > this.w)
  1282. this.w = other.w;
  1283. return this;
  1284. };
  1285. // Properties
  1286. Vector4.prototype.length = function () {
  1287. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1288. };
  1289. Vector4.prototype.lengthSquared = function () {
  1290. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1291. };
  1292. // Methods
  1293. Vector4.prototype.normalize = function () {
  1294. var len = this.length();
  1295. if (len === 0)
  1296. return this;
  1297. var num = 1.0 / len;
  1298. this.x *= num;
  1299. this.y *= num;
  1300. this.z *= num;
  1301. this.w *= num;
  1302. return this;
  1303. };
  1304. Vector4.prototype.toVector3 = function () {
  1305. return new Vector3(this.x, this.y, this.z);
  1306. };
  1307. Vector4.prototype.clone = function () {
  1308. return new Vector4(this.x, this.y, this.z, this.w);
  1309. };
  1310. Vector4.prototype.copyFrom = function (source) {
  1311. this.x = source.x;
  1312. this.y = source.y;
  1313. this.z = source.z;
  1314. this.w = source.w;
  1315. return this;
  1316. };
  1317. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1318. this.x = x;
  1319. this.y = y;
  1320. this.z = z;
  1321. this.w = w;
  1322. return this;
  1323. };
  1324. // Statics
  1325. Vector4.FromArray = function (array, offset) {
  1326. if (!offset) {
  1327. offset = 0;
  1328. }
  1329. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1330. };
  1331. Vector4.FromArrayToRef = function (array, offset, result) {
  1332. result.x = array[offset];
  1333. result.y = array[offset + 1];
  1334. result.z = array[offset + 2];
  1335. result.w = array[offset + 3];
  1336. };
  1337. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1338. result.x = array[offset];
  1339. result.y = array[offset + 1];
  1340. result.z = array[offset + 2];
  1341. result.w = array[offset + 3];
  1342. };
  1343. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1344. result.x = x;
  1345. result.y = y;
  1346. result.z = z;
  1347. result.w = w;
  1348. };
  1349. Vector4.Zero = function () {
  1350. return new Vector4(0, 0, 0, 0);
  1351. };
  1352. Vector4.Normalize = function (vector) {
  1353. var result = Vector4.Zero();
  1354. Vector4.NormalizeToRef(vector, result);
  1355. return result;
  1356. };
  1357. Vector4.NormalizeToRef = function (vector, result) {
  1358. result.copyFrom(vector);
  1359. result.normalize();
  1360. };
  1361. Vector4.Minimize = function (left, right) {
  1362. var min = left.clone();
  1363. min.MinimizeInPlace(right);
  1364. return min;
  1365. };
  1366. Vector4.Maximize = function (left, right) {
  1367. var max = left.clone();
  1368. max.MaximizeInPlace(right);
  1369. return max;
  1370. };
  1371. Vector4.Distance = function (value1, value2) {
  1372. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1373. };
  1374. Vector4.DistanceSquared = function (value1, value2) {
  1375. var x = value1.x - value2.x;
  1376. var y = value1.y - value2.y;
  1377. var z = value1.z - value2.z;
  1378. var w = value1.w - value2.w;
  1379. return (x * x) + (y * y) + (z * z) + (w * w);
  1380. };
  1381. Vector4.Center = function (value1, value2) {
  1382. var center = value1.add(value2);
  1383. center.scaleInPlace(0.5);
  1384. return center;
  1385. };
  1386. return Vector4;
  1387. })();
  1388. BABYLON.Vector4 = Vector4;
  1389. var Size = (function () {
  1390. function Size(width, height) {
  1391. this.width = width;
  1392. this.height = height;
  1393. }
  1394. Size.prototype.toString = function () {
  1395. return "{W: " + this.width + ", H: " + this.height + "}";
  1396. };
  1397. Size.prototype.getClassName = function () {
  1398. return "Size";
  1399. };
  1400. Size.prototype.getHashCode = function () {
  1401. var hash = this.width || 0;
  1402. hash = (hash * 397) ^ (this.height || 0);
  1403. return hash;
  1404. };
  1405. Size.prototype.copyFrom = function (src) {
  1406. this.width = src.width;
  1407. this.height = src.height;
  1408. };
  1409. Size.prototype.copyFromFloats = function (width, height) {
  1410. this.width = width;
  1411. this.height = height;
  1412. };
  1413. Size.prototype.multiplyByFloats = function (w, h) {
  1414. return new Size(this.width * w, this.height * h);
  1415. };
  1416. Size.prototype.clone = function () {
  1417. return new Size(this.width, this.height);
  1418. };
  1419. Size.prototype.equals = function (other) {
  1420. if (!other) {
  1421. return false;
  1422. }
  1423. return (this.width === other.width) && (this.height === other.height);
  1424. };
  1425. Object.defineProperty(Size.prototype, "surface", {
  1426. get: function () {
  1427. return this.width * this.height;
  1428. },
  1429. enumerable: true,
  1430. configurable: true
  1431. });
  1432. Size.Zero = function () {
  1433. return new Size(0, 0);
  1434. };
  1435. Size.prototype.add = function (otherSize) {
  1436. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1437. return r;
  1438. };
  1439. Size.prototype.substract = function (otherSize) {
  1440. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1441. return r;
  1442. };
  1443. Size.Lerp = function (start, end, amount) {
  1444. var w = start.width + ((end.width - start.width) * amount);
  1445. var h = start.height + ((end.height - start.height) * amount);
  1446. return new Size(w, h);
  1447. };
  1448. return Size;
  1449. })();
  1450. BABYLON.Size = Size;
  1451. var Quaternion = (function () {
  1452. function Quaternion(x, y, z, w) {
  1453. if (x === void 0) { x = 0; }
  1454. if (y === void 0) { y = 0; }
  1455. if (z === void 0) { z = 0; }
  1456. if (w === void 0) { w = 1; }
  1457. this.x = x;
  1458. this.y = y;
  1459. this.z = z;
  1460. this.w = w;
  1461. }
  1462. Quaternion.prototype.toString = function () {
  1463. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1464. };
  1465. Quaternion.prototype.getClassName = function () {
  1466. return "Quaternion";
  1467. };
  1468. Quaternion.prototype.getHashCode = function () {
  1469. var hash = this.x || 0;
  1470. hash = (hash * 397) ^ (this.y || 0);
  1471. hash = (hash * 397) ^ (this.z || 0);
  1472. hash = (hash * 397) ^ (this.w || 0);
  1473. return hash;
  1474. };
  1475. Quaternion.prototype.asArray = function () {
  1476. return [this.x, this.y, this.z, this.w];
  1477. };
  1478. Quaternion.prototype.equals = function (otherQuaternion) {
  1479. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1480. };
  1481. Quaternion.prototype.clone = function () {
  1482. return new Quaternion(this.x, this.y, this.z, this.w);
  1483. };
  1484. Quaternion.prototype.copyFrom = function (other) {
  1485. this.x = other.x;
  1486. this.y = other.y;
  1487. this.z = other.z;
  1488. this.w = other.w;
  1489. return this;
  1490. };
  1491. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1492. this.x = x;
  1493. this.y = y;
  1494. this.z = z;
  1495. this.w = w;
  1496. return this;
  1497. };
  1498. Quaternion.prototype.add = function (other) {
  1499. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1500. };
  1501. Quaternion.prototype.subtract = function (other) {
  1502. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1503. };
  1504. Quaternion.prototype.scale = function (value) {
  1505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1506. };
  1507. Quaternion.prototype.multiply = function (q1) {
  1508. var result = new Quaternion(0, 0, 0, 1.0);
  1509. this.multiplyToRef(q1, result);
  1510. return result;
  1511. };
  1512. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1513. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1514. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1515. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1516. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1517. result.copyFromFloats(x, y, z, w);
  1518. return this;
  1519. };
  1520. Quaternion.prototype.multiplyInPlace = function (q1) {
  1521. this.multiplyToRef(q1, this);
  1522. return this;
  1523. };
  1524. Quaternion.prototype.conjugateToRef = function (ref) {
  1525. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1526. return this;
  1527. };
  1528. Quaternion.prototype.conjugateInPlace = function () {
  1529. this.x *= -1;
  1530. this.y *= -1;
  1531. this.z *= -1;
  1532. return this;
  1533. };
  1534. Quaternion.prototype.conjugate = function () {
  1535. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1536. return result;
  1537. };
  1538. Quaternion.prototype.length = function () {
  1539. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1540. };
  1541. Quaternion.prototype.normalize = function () {
  1542. var length = 1.0 / this.length();
  1543. this.x *= length;
  1544. this.y *= length;
  1545. this.z *= length;
  1546. this.w *= length;
  1547. return this;
  1548. };
  1549. Quaternion.prototype.toEulerAngles = function (order) {
  1550. if (order === void 0) { order = "YZX"; }
  1551. var result = Vector3.Zero();
  1552. this.toEulerAnglesToRef(result, order);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1556. if (order === void 0) { order = "YZX"; }
  1557. var heading, attitude, bank;
  1558. var x = this.x, y = this.y, z = this.z, w = this.w;
  1559. switch (order) {
  1560. case "YZX":
  1561. var test = x * y + z * w;
  1562. if (test > 0.499) {
  1563. heading = 2 * Math.atan2(x, w);
  1564. attitude = Math.PI / 2;
  1565. bank = 0;
  1566. }
  1567. if (test < -0.499) {
  1568. heading = -2 * Math.atan2(x, w);
  1569. attitude = -Math.PI / 2;
  1570. bank = 0;
  1571. }
  1572. if (isNaN(heading)) {
  1573. var sqx = x * x;
  1574. var sqy = y * y;
  1575. var sqz = z * z;
  1576. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1577. attitude = Math.asin(2 * test); // attitude
  1578. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1579. }
  1580. break;
  1581. default:
  1582. throw new Error("Euler order " + order + " not supported yet.");
  1583. }
  1584. result.y = heading;
  1585. result.z = attitude;
  1586. result.x = bank;
  1587. return this;
  1588. };
  1589. ;
  1590. Quaternion.prototype.toRotationMatrix = function (result) {
  1591. var xx = this.x * this.x;
  1592. var yy = this.y * this.y;
  1593. var zz = this.z * this.z;
  1594. var xy = this.x * this.y;
  1595. var zw = this.z * this.w;
  1596. var zx = this.z * this.x;
  1597. var yw = this.y * this.w;
  1598. var yz = this.y * this.z;
  1599. var xw = this.x * this.w;
  1600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1601. result.m[1] = 2.0 * (xy + zw);
  1602. result.m[2] = 2.0 * (zx - yw);
  1603. result.m[3] = 0;
  1604. result.m[4] = 2.0 * (xy - zw);
  1605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1606. result.m[6] = 2.0 * (yz + xw);
  1607. result.m[7] = 0;
  1608. result.m[8] = 2.0 * (zx + yw);
  1609. result.m[9] = 2.0 * (yz - xw);
  1610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1611. result.m[11] = 0;
  1612. result.m[12] = 0;
  1613. result.m[13] = 0;
  1614. result.m[14] = 0;
  1615. result.m[15] = 1.0;
  1616. return this;
  1617. };
  1618. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1619. Quaternion.FromRotationMatrixToRef(matrix, this);
  1620. return this;
  1621. };
  1622. // Statics
  1623. Quaternion.FromRotationMatrix = function (matrix) {
  1624. var result = new Quaternion();
  1625. Quaternion.FromRotationMatrixToRef(matrix, result);
  1626. return result;
  1627. };
  1628. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1629. var data = matrix.m;
  1630. var m11 = data[0], m12 = data[4], m13 = data[8];
  1631. var m21 = data[1], m22 = data[5], m23 = data[9];
  1632. var m31 = data[2], m32 = data[6], m33 = data[10];
  1633. var trace = m11 + m22 + m33;
  1634. var s;
  1635. if (trace > 0) {
  1636. s = 0.5 / Math.sqrt(trace + 1.0);
  1637. result.w = 0.25 / s;
  1638. result.x = (m32 - m23) * s;
  1639. result.y = (m13 - m31) * s;
  1640. result.z = (m21 - m12) * s;
  1641. }
  1642. else if (m11 > m22 && m11 > m33) {
  1643. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1644. result.w = (m32 - m23) / s;
  1645. result.x = 0.25 * s;
  1646. result.y = (m12 + m21) / s;
  1647. result.z = (m13 + m31) / s;
  1648. }
  1649. else if (m22 > m33) {
  1650. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1651. result.w = (m13 - m31) / s;
  1652. result.x = (m12 + m21) / s;
  1653. result.y = 0.25 * s;
  1654. result.z = (m23 + m32) / s;
  1655. }
  1656. else {
  1657. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1658. result.w = (m21 - m12) / s;
  1659. result.x = (m13 + m31) / s;
  1660. result.y = (m23 + m32) / s;
  1661. result.z = 0.25 * s;
  1662. }
  1663. };
  1664. Quaternion.Inverse = function (q) {
  1665. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1666. };
  1667. Quaternion.Identity = function () {
  1668. return new Quaternion(0, 0, 0, 1);
  1669. };
  1670. Quaternion.RotationAxis = function (axis, angle) {
  1671. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1672. };
  1673. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1674. var sin = Math.sin(angle / 2);
  1675. axis.normalize();
  1676. result.w = Math.cos(angle / 2);
  1677. result.x = axis.x * sin;
  1678. result.y = axis.y * sin;
  1679. result.z = axis.z * sin;
  1680. return result;
  1681. };
  1682. Quaternion.FromArray = function (array, offset) {
  1683. if (!offset) {
  1684. offset = 0;
  1685. }
  1686. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1687. };
  1688. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1689. var q = new Quaternion();
  1690. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1691. return q;
  1692. };
  1693. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1694. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1695. var halfRoll = roll * 0.5;
  1696. var halfPitch = pitch * 0.5;
  1697. var halfYaw = yaw * 0.5;
  1698. var sinRoll = Math.sin(halfRoll);
  1699. var cosRoll = Math.cos(halfRoll);
  1700. var sinPitch = Math.sin(halfPitch);
  1701. var cosPitch = Math.cos(halfPitch);
  1702. var sinYaw = Math.sin(halfYaw);
  1703. var cosYaw = Math.cos(halfYaw);
  1704. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1705. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1706. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1707. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1708. };
  1709. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1710. var result = new Quaternion();
  1711. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1712. return result;
  1713. };
  1714. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1715. // Produces a quaternion from Euler angles in the z-x-z orientation
  1716. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1717. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1718. var halfBeta = beta * 0.5;
  1719. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1720. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1721. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1722. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1723. };
  1724. Quaternion.Slerp = function (left, right, amount) {
  1725. var num2;
  1726. var num3;
  1727. var num = amount;
  1728. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1729. var flag = false;
  1730. if (num4 < 0) {
  1731. flag = true;
  1732. num4 = -num4;
  1733. }
  1734. if (num4 > 0.999999) {
  1735. num3 = 1 - num;
  1736. num2 = flag ? -num : num;
  1737. }
  1738. else {
  1739. var num5 = Math.acos(num4);
  1740. var num6 = (1.0 / Math.sin(num5));
  1741. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1742. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1743. }
  1744. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1745. };
  1746. return Quaternion;
  1747. })();
  1748. BABYLON.Quaternion = Quaternion;
  1749. var Matrix = (function () {
  1750. function Matrix() {
  1751. this.m = new Float32Array(16);
  1752. }
  1753. // Properties
  1754. Matrix.prototype.isIdentity = function () {
  1755. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1756. return false;
  1757. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1758. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1759. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1760. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1761. return false;
  1762. return true;
  1763. };
  1764. Matrix.prototype.determinant = function () {
  1765. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1766. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1767. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1768. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1769. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1770. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1771. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1772. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1773. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1774. };
  1775. // Methods
  1776. Matrix.prototype.toArray = function () {
  1777. return this.m;
  1778. };
  1779. Matrix.prototype.asArray = function () {
  1780. return this.toArray();
  1781. };
  1782. Matrix.prototype.invert = function () {
  1783. this.invertToRef(this);
  1784. return this;
  1785. };
  1786. Matrix.prototype.reset = function () {
  1787. for (var index = 0; index < 16; index++) {
  1788. this.m[index] = 0;
  1789. }
  1790. return this;
  1791. };
  1792. Matrix.prototype.add = function (other) {
  1793. var result = new Matrix();
  1794. this.addToRef(other, result);
  1795. return result;
  1796. };
  1797. Matrix.prototype.addToRef = function (other, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = this.m[index] + other.m[index];
  1800. }
  1801. return this;
  1802. };
  1803. Matrix.prototype.addToSelf = function (other) {
  1804. for (var index = 0; index < 16; index++) {
  1805. this.m[index] += other.m[index];
  1806. }
  1807. return this;
  1808. };
  1809. Matrix.prototype.invertToRef = function (other) {
  1810. var l1 = this.m[0];
  1811. var l2 = this.m[1];
  1812. var l3 = this.m[2];
  1813. var l4 = this.m[3];
  1814. var l5 = this.m[4];
  1815. var l6 = this.m[5];
  1816. var l7 = this.m[6];
  1817. var l8 = this.m[7];
  1818. var l9 = this.m[8];
  1819. var l10 = this.m[9];
  1820. var l11 = this.m[10];
  1821. var l12 = this.m[11];
  1822. var l13 = this.m[12];
  1823. var l14 = this.m[13];
  1824. var l15 = this.m[14];
  1825. var l16 = this.m[15];
  1826. var l17 = (l11 * l16) - (l12 * l15);
  1827. var l18 = (l10 * l16) - (l12 * l14);
  1828. var l19 = (l10 * l15) - (l11 * l14);
  1829. var l20 = (l9 * l16) - (l12 * l13);
  1830. var l21 = (l9 * l15) - (l11 * l13);
  1831. var l22 = (l9 * l14) - (l10 * l13);
  1832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1837. var l28 = (l7 * l16) - (l8 * l15);
  1838. var l29 = (l6 * l16) - (l8 * l14);
  1839. var l30 = (l6 * l15) - (l7 * l14);
  1840. var l31 = (l5 * l16) - (l8 * l13);
  1841. var l32 = (l5 * l15) - (l7 * l13);
  1842. var l33 = (l5 * l14) - (l6 * l13);
  1843. var l34 = (l7 * l12) - (l8 * l11);
  1844. var l35 = (l6 * l12) - (l8 * l10);
  1845. var l36 = (l6 * l11) - (l7 * l10);
  1846. var l37 = (l5 * l12) - (l8 * l9);
  1847. var l38 = (l5 * l11) - (l7 * l9);
  1848. var l39 = (l5 * l10) - (l6 * l9);
  1849. other.m[0] = l23 * l27;
  1850. other.m[4] = l24 * l27;
  1851. other.m[8] = l25 * l27;
  1852. other.m[12] = l26 * l27;
  1853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1865. return this;
  1866. };
  1867. Matrix.prototype.setTranslation = function (vector3) {
  1868. this.m[12] = vector3.x;
  1869. this.m[13] = vector3.y;
  1870. this.m[14] = vector3.z;
  1871. return this;
  1872. };
  1873. Matrix.prototype.getTranslation = function () {
  1874. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1875. };
  1876. Matrix.prototype.multiply = function (other) {
  1877. var result = new Matrix();
  1878. this.multiplyToRef(other, result);
  1879. return result;
  1880. };
  1881. Matrix.prototype.copyFrom = function (other) {
  1882. for (var index = 0; index < 16; index++) {
  1883. this.m[index] = other.m[index];
  1884. }
  1885. return this;
  1886. };
  1887. Matrix.prototype.copyToArray = function (array, offset) {
  1888. if (offset === void 0) { offset = 0; }
  1889. for (var index = 0; index < 16; index++) {
  1890. array[offset + index] = this.m[index];
  1891. }
  1892. return this;
  1893. };
  1894. Matrix.prototype.multiplyToRef = function (other, result) {
  1895. this.multiplyToArray(other, result.m, 0);
  1896. return this;
  1897. };
  1898. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1899. var tm0 = this.m[0];
  1900. var tm1 = this.m[1];
  1901. var tm2 = this.m[2];
  1902. var tm3 = this.m[3];
  1903. var tm4 = this.m[4];
  1904. var tm5 = this.m[5];
  1905. var tm6 = this.m[6];
  1906. var tm7 = this.m[7];
  1907. var tm8 = this.m[8];
  1908. var tm9 = this.m[9];
  1909. var tm10 = this.m[10];
  1910. var tm11 = this.m[11];
  1911. var tm12 = this.m[12];
  1912. var tm13 = this.m[13];
  1913. var tm14 = this.m[14];
  1914. var tm15 = this.m[15];
  1915. var om0 = other.m[0];
  1916. var om1 = other.m[1];
  1917. var om2 = other.m[2];
  1918. var om3 = other.m[3];
  1919. var om4 = other.m[4];
  1920. var om5 = other.m[5];
  1921. var om6 = other.m[6];
  1922. var om7 = other.m[7];
  1923. var om8 = other.m[8];
  1924. var om9 = other.m[9];
  1925. var om10 = other.m[10];
  1926. var om11 = other.m[11];
  1927. var om12 = other.m[12];
  1928. var om13 = other.m[13];
  1929. var om14 = other.m[14];
  1930. var om15 = other.m[15];
  1931. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1932. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1933. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1934. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1935. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1936. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1937. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1938. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1939. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1940. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1941. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1942. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1943. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1944. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1945. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1946. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1947. return this;
  1948. };
  1949. Matrix.prototype.equals = function (value) {
  1950. return value &&
  1951. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1952. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1953. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1954. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1955. };
  1956. Matrix.prototype.clone = function () {
  1957. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1958. };
  1959. Matrix.prototype.getClassName = function () {
  1960. return "Matrix";
  1961. };
  1962. Matrix.prototype.getHashCode = function () {
  1963. var hash = this.m[0] || 0;
  1964. for (var i = 1; i < 16; i++) {
  1965. hash = (hash * 397) ^ (this.m[i] || 0);
  1966. }
  1967. return hash;
  1968. };
  1969. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1970. translation.x = this.m[12];
  1971. translation.y = this.m[13];
  1972. translation.z = this.m[14];
  1973. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1974. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1975. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1976. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1977. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1978. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1979. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1980. rotation.x = 0;
  1981. rotation.y = 0;
  1982. rotation.z = 0;
  1983. rotation.w = 1;
  1984. return false;
  1985. }
  1986. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1987. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1988. return true;
  1989. };
  1990. // Statics
  1991. Matrix.FromArray = function (array, offset) {
  1992. var result = new Matrix();
  1993. if (!offset) {
  1994. offset = 0;
  1995. }
  1996. Matrix.FromArrayToRef(array, offset, result);
  1997. return result;
  1998. };
  1999. Matrix.FromArrayToRef = function (array, offset, result) {
  2000. for (var index = 0; index < 16; index++) {
  2001. result.m[index] = array[index + offset];
  2002. }
  2003. };
  2004. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2005. for (var index = 0; index < 16; index++) {
  2006. result.m[index] = array[index + offset] * scale;
  2007. }
  2008. };
  2009. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2010. result.m[0] = initialM11;
  2011. result.m[1] = initialM12;
  2012. result.m[2] = initialM13;
  2013. result.m[3] = initialM14;
  2014. result.m[4] = initialM21;
  2015. result.m[5] = initialM22;
  2016. result.m[6] = initialM23;
  2017. result.m[7] = initialM24;
  2018. result.m[8] = initialM31;
  2019. result.m[9] = initialM32;
  2020. result.m[10] = initialM33;
  2021. result.m[11] = initialM34;
  2022. result.m[12] = initialM41;
  2023. result.m[13] = initialM42;
  2024. result.m[14] = initialM43;
  2025. result.m[15] = initialM44;
  2026. };
  2027. Matrix.prototype.getRow = function (index) {
  2028. if (index < 0 || index > 3) {
  2029. return null;
  2030. }
  2031. var i = index * 4;
  2032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2033. };
  2034. Matrix.prototype.setRow = function (index, row) {
  2035. if (index < 0 || index > 3) {
  2036. return this;
  2037. }
  2038. var i = index * 4;
  2039. this.m[i + 0] = row.x;
  2040. this.m[i + 1] = row.y;
  2041. this.m[i + 2] = row.z;
  2042. this.m[i + 3] = row.w;
  2043. return this;
  2044. };
  2045. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2046. var result = new Matrix();
  2047. result.m[0] = initialM11;
  2048. result.m[1] = initialM12;
  2049. result.m[2] = initialM13;
  2050. result.m[3] = initialM14;
  2051. result.m[4] = initialM21;
  2052. result.m[5] = initialM22;
  2053. result.m[6] = initialM23;
  2054. result.m[7] = initialM24;
  2055. result.m[8] = initialM31;
  2056. result.m[9] = initialM32;
  2057. result.m[10] = initialM33;
  2058. result.m[11] = initialM34;
  2059. result.m[12] = initialM41;
  2060. result.m[13] = initialM42;
  2061. result.m[14] = initialM43;
  2062. result.m[15] = initialM44;
  2063. return result;
  2064. };
  2065. Matrix.Compose = function (scale, rotation, translation) {
  2066. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2067. var rotationMatrix = Matrix.Identity();
  2068. rotation.toRotationMatrix(rotationMatrix);
  2069. result = result.multiply(rotationMatrix);
  2070. result.setTranslation(translation);
  2071. return result;
  2072. };
  2073. Matrix.Identity = function () {
  2074. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2075. };
  2076. Matrix.IdentityToRef = function (result) {
  2077. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2078. };
  2079. Matrix.Zero = function () {
  2080. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2081. };
  2082. Matrix.RotationX = function (angle) {
  2083. var result = new Matrix();
  2084. Matrix.RotationXToRef(angle, result);
  2085. return result;
  2086. };
  2087. Matrix.Invert = function (source) {
  2088. var result = new Matrix();
  2089. source.invertToRef(result);
  2090. return result;
  2091. };
  2092. Matrix.RotationXToRef = function (angle, result) {
  2093. var s = Math.sin(angle);
  2094. var c = Math.cos(angle);
  2095. result.m[0] = 1.0;
  2096. result.m[15] = 1.0;
  2097. result.m[5] = c;
  2098. result.m[10] = c;
  2099. result.m[9] = -s;
  2100. result.m[6] = s;
  2101. result.m[1] = 0;
  2102. result.m[2] = 0;
  2103. result.m[3] = 0;
  2104. result.m[4] = 0;
  2105. result.m[7] = 0;
  2106. result.m[8] = 0;
  2107. result.m[11] = 0;
  2108. result.m[12] = 0;
  2109. result.m[13] = 0;
  2110. result.m[14] = 0;
  2111. };
  2112. Matrix.RotationY = function (angle) {
  2113. var result = new Matrix();
  2114. Matrix.RotationYToRef(angle, result);
  2115. return result;
  2116. };
  2117. Matrix.RotationYToRef = function (angle, result) {
  2118. var s = Math.sin(angle);
  2119. var c = Math.cos(angle);
  2120. result.m[5] = 1.0;
  2121. result.m[15] = 1.0;
  2122. result.m[0] = c;
  2123. result.m[2] = -s;
  2124. result.m[8] = s;
  2125. result.m[10] = c;
  2126. result.m[1] = 0;
  2127. result.m[3] = 0;
  2128. result.m[4] = 0;
  2129. result.m[6] = 0;
  2130. result.m[7] = 0;
  2131. result.m[9] = 0;
  2132. result.m[11] = 0;
  2133. result.m[12] = 0;
  2134. result.m[13] = 0;
  2135. result.m[14] = 0;
  2136. };
  2137. Matrix.RotationZ = function (angle) {
  2138. var result = new Matrix();
  2139. Matrix.RotationZToRef(angle, result);
  2140. return result;
  2141. };
  2142. Matrix.RotationZToRef = function (angle, result) {
  2143. var s = Math.sin(angle);
  2144. var c = Math.cos(angle);
  2145. result.m[10] = 1.0;
  2146. result.m[15] = 1.0;
  2147. result.m[0] = c;
  2148. result.m[1] = s;
  2149. result.m[4] = -s;
  2150. result.m[5] = c;
  2151. result.m[2] = 0;
  2152. result.m[3] = 0;
  2153. result.m[6] = 0;
  2154. result.m[7] = 0;
  2155. result.m[8] = 0;
  2156. result.m[9] = 0;
  2157. result.m[11] = 0;
  2158. result.m[12] = 0;
  2159. result.m[13] = 0;
  2160. result.m[14] = 0;
  2161. };
  2162. Matrix.RotationAxis = function (axis, angle) {
  2163. var result = Matrix.Zero();
  2164. Matrix.RotationAxisToRef(axis, angle, result);
  2165. return result;
  2166. };
  2167. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2168. var s = Math.sin(-angle);
  2169. var c = Math.cos(-angle);
  2170. var c1 = 1 - c;
  2171. axis.normalize();
  2172. result.m[0] = (axis.x * axis.x) * c1 + c;
  2173. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2174. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2175. result.m[3] = 0.0;
  2176. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2177. result.m[5] = (axis.y * axis.y) * c1 + c;
  2178. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2179. result.m[7] = 0.0;
  2180. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2181. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2182. result.m[10] = (axis.z * axis.z) * c1 + c;
  2183. result.m[11] = 0.0;
  2184. result.m[15] = 1.0;
  2185. };
  2186. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2187. var result = new Matrix();
  2188. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2189. return result;
  2190. };
  2191. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2192. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2193. this._tempQuaternion.toRotationMatrix(result);
  2194. };
  2195. Matrix.Scaling = function (x, y, z) {
  2196. var result = Matrix.Zero();
  2197. Matrix.ScalingToRef(x, y, z, result);
  2198. return result;
  2199. };
  2200. Matrix.ScalingToRef = function (x, y, z, result) {
  2201. result.m[0] = x;
  2202. result.m[1] = 0;
  2203. result.m[2] = 0;
  2204. result.m[3] = 0;
  2205. result.m[4] = 0;
  2206. result.m[5] = y;
  2207. result.m[6] = 0;
  2208. result.m[7] = 0;
  2209. result.m[8] = 0;
  2210. result.m[9] = 0;
  2211. result.m[10] = z;
  2212. result.m[11] = 0;
  2213. result.m[12] = 0;
  2214. result.m[13] = 0;
  2215. result.m[14] = 0;
  2216. result.m[15] = 1.0;
  2217. };
  2218. Matrix.Translation = function (x, y, z) {
  2219. var result = Matrix.Identity();
  2220. Matrix.TranslationToRef(x, y, z, result);
  2221. return result;
  2222. };
  2223. Matrix.TranslationToRef = function (x, y, z, result) {
  2224. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2225. };
  2226. Matrix.Lerp = function (startValue, endValue, gradient) {
  2227. var result = Matrix.Zero();
  2228. for (var index = 0; index < 16; index++) {
  2229. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2230. }
  2231. return result;
  2232. };
  2233. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2234. var startScale = new Vector3(0, 0, 0);
  2235. var startRotation = new Quaternion();
  2236. var startTranslation = new Vector3(0, 0, 0);
  2237. startValue.decompose(startScale, startRotation, startTranslation);
  2238. var endScale = new Vector3(0, 0, 0);
  2239. var endRotation = new Quaternion();
  2240. var endTranslation = new Vector3(0, 0, 0);
  2241. endValue.decompose(endScale, endRotation, endTranslation);
  2242. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2243. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2244. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2245. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2246. };
  2247. Matrix.LookAtLH = function (eye, target, up) {
  2248. var result = Matrix.Zero();
  2249. Matrix.LookAtLHToRef(eye, target, up, result);
  2250. return result;
  2251. };
  2252. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2253. // Z axis
  2254. target.subtractToRef(eye, this._zAxis);
  2255. this._zAxis.normalize();
  2256. // X axis
  2257. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2258. if (this._xAxis.lengthSquared() === 0) {
  2259. this._xAxis.x = 1.0;
  2260. }
  2261. else {
  2262. this._xAxis.normalize();
  2263. }
  2264. // Y axis
  2265. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2266. this._yAxis.normalize();
  2267. // Eye angles
  2268. var ex = -Vector3.Dot(this._xAxis, eye);
  2269. var ey = -Vector3.Dot(this._yAxis, eye);
  2270. var ez = -Vector3.Dot(this._zAxis, eye);
  2271. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2272. };
  2273. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2274. var matrix = Matrix.Zero();
  2275. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2276. return matrix;
  2277. };
  2278. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2279. var hw = 2.0 / width;
  2280. var hh = 2.0 / height;
  2281. var id = 1.0 / (zfar - znear);
  2282. var nid = znear / (znear - zfar);
  2283. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2284. };
  2285. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2286. var matrix = Matrix.Zero();
  2287. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2288. return matrix;
  2289. };
  2290. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2291. result.m[0] = 2.0 / (right - left);
  2292. result.m[1] = result.m[2] = result.m[3] = 0;
  2293. result.m[5] = 2.0 / (top - bottom);
  2294. result.m[4] = result.m[6] = result.m[7] = 0;
  2295. result.m[10] = -1.0 / (znear - zfar);
  2296. result.m[8] = result.m[9] = result.m[11] = 0;
  2297. result.m[12] = (left + right) / (left - right);
  2298. result.m[13] = (top + bottom) / (bottom - top);
  2299. result.m[14] = znear / (znear - zfar);
  2300. result.m[15] = 1.0;
  2301. };
  2302. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2303. var matrix = Matrix.Zero();
  2304. matrix.m[0] = (2.0 * znear) / width;
  2305. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2306. matrix.m[5] = (2.0 * znear) / height;
  2307. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2308. matrix.m[10] = -zfar / (znear - zfar);
  2309. matrix.m[8] = matrix.m[9] = 0.0;
  2310. matrix.m[11] = 1.0;
  2311. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2312. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2313. return matrix;
  2314. };
  2315. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2316. var matrix = Matrix.Zero();
  2317. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2318. return matrix;
  2319. };
  2320. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2321. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2322. var tan = 1.0 / (Math.tan(fov * 0.5));
  2323. if (isVerticalFovFixed) {
  2324. result.m[0] = tan / aspect;
  2325. }
  2326. else {
  2327. result.m[0] = tan;
  2328. }
  2329. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2330. if (isVerticalFovFixed) {
  2331. result.m[5] = tan;
  2332. }
  2333. else {
  2334. result.m[5] = tan * aspect;
  2335. }
  2336. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2337. result.m[8] = result.m[9] = 0.0;
  2338. result.m[10] = -zfar / (znear - zfar);
  2339. result.m[11] = 1.0;
  2340. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2341. result.m[14] = (znear * zfar) / (znear - zfar);
  2342. };
  2343. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2344. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2345. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2346. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2347. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2348. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2349. var xScale = 2.0 / (leftTan + rightTan);
  2350. var yScale = 2.0 / (upTan + downTan);
  2351. result.m[0] = xScale;
  2352. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2353. result.m[5] = yScale;
  2354. result.m[6] = result.m[7] = 0.0;
  2355. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2356. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2357. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2358. result.m[10] = -zfar / (znear - zfar);
  2359. result.m[11] = 1.0;
  2360. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2361. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2362. result.m[14] = (znear * zfar) / (znear - zfar);
  2363. };
  2364. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2365. var cw = viewport.width;
  2366. var ch = viewport.height;
  2367. var cx = viewport.x;
  2368. var cy = viewport.y;
  2369. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2370. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2371. };
  2372. Matrix.GetAsMatrix2x2 = function (matrix) {
  2373. return new Float32Array([
  2374. matrix.m[0], matrix.m[1],
  2375. matrix.m[4], matrix.m[5]
  2376. ]);
  2377. };
  2378. Matrix.GetAsMatrix3x3 = function (matrix) {
  2379. return new Float32Array([
  2380. matrix.m[0], matrix.m[1], matrix.m[2],
  2381. matrix.m[4], matrix.m[5], matrix.m[6],
  2382. matrix.m[8], matrix.m[9], matrix.m[10]
  2383. ]);
  2384. };
  2385. Matrix.Transpose = function (matrix) {
  2386. var result = new Matrix();
  2387. result.m[0] = matrix.m[0];
  2388. result.m[1] = matrix.m[4];
  2389. result.m[2] = matrix.m[8];
  2390. result.m[3] = matrix.m[12];
  2391. result.m[4] = matrix.m[1];
  2392. result.m[5] = matrix.m[5];
  2393. result.m[6] = matrix.m[9];
  2394. result.m[7] = matrix.m[13];
  2395. result.m[8] = matrix.m[2];
  2396. result.m[9] = matrix.m[6];
  2397. result.m[10] = matrix.m[10];
  2398. result.m[11] = matrix.m[14];
  2399. result.m[12] = matrix.m[3];
  2400. result.m[13] = matrix.m[7];
  2401. result.m[14] = matrix.m[11];
  2402. result.m[15] = matrix.m[15];
  2403. return result;
  2404. };
  2405. Matrix.Reflection = function (plane) {
  2406. var matrix = new Matrix();
  2407. Matrix.ReflectionToRef(plane, matrix);
  2408. return matrix;
  2409. };
  2410. Matrix.ReflectionToRef = function (plane, result) {
  2411. plane.normalize();
  2412. var x = plane.normal.x;
  2413. var y = plane.normal.y;
  2414. var z = plane.normal.z;
  2415. var temp = -2 * x;
  2416. var temp2 = -2 * y;
  2417. var temp3 = -2 * z;
  2418. result.m[0] = (temp * x) + 1;
  2419. result.m[1] = temp2 * x;
  2420. result.m[2] = temp3 * x;
  2421. result.m[3] = 0.0;
  2422. result.m[4] = temp * y;
  2423. result.m[5] = (temp2 * y) + 1;
  2424. result.m[6] = temp3 * y;
  2425. result.m[7] = 0.0;
  2426. result.m[8] = temp * z;
  2427. result.m[9] = temp2 * z;
  2428. result.m[10] = (temp3 * z) + 1;
  2429. result.m[11] = 0.0;
  2430. result.m[12] = temp * plane.d;
  2431. result.m[13] = temp2 * plane.d;
  2432. result.m[14] = temp3 * plane.d;
  2433. result.m[15] = 1.0;
  2434. };
  2435. Matrix._tempQuaternion = new Quaternion();
  2436. Matrix._xAxis = Vector3.Zero();
  2437. Matrix._yAxis = Vector3.Zero();
  2438. Matrix._zAxis = Vector3.Zero();
  2439. return Matrix;
  2440. })();
  2441. BABYLON.Matrix = Matrix;
  2442. var Plane = (function () {
  2443. function Plane(a, b, c, d) {
  2444. this.normal = new Vector3(a, b, c);
  2445. this.d = d;
  2446. }
  2447. Plane.prototype.asArray = function () {
  2448. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2449. };
  2450. // Methods
  2451. Plane.prototype.clone = function () {
  2452. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2453. };
  2454. Plane.prototype.getClassName = function () {
  2455. return "Plane";
  2456. };
  2457. Plane.prototype.getHashCode = function () {
  2458. var hash = this.normal.getHashCode();
  2459. hash = (hash * 397) ^ (this.d || 0);
  2460. return hash;
  2461. };
  2462. Plane.prototype.normalize = function () {
  2463. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2464. var magnitude = 0;
  2465. if (norm !== 0) {
  2466. magnitude = 1.0 / norm;
  2467. }
  2468. this.normal.x *= magnitude;
  2469. this.normal.y *= magnitude;
  2470. this.normal.z *= magnitude;
  2471. this.d *= magnitude;
  2472. return this;
  2473. };
  2474. Plane.prototype.transform = function (transformation) {
  2475. var transposedMatrix = Matrix.Transpose(transformation);
  2476. var x = this.normal.x;
  2477. var y = this.normal.y;
  2478. var z = this.normal.z;
  2479. var d = this.d;
  2480. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2481. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2482. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2483. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2484. return new Plane(normalX, normalY, normalZ, finalD);
  2485. };
  2486. Plane.prototype.dotCoordinate = function (point) {
  2487. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2488. };
  2489. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2490. var x1 = point2.x - point1.x;
  2491. var y1 = point2.y - point1.y;
  2492. var z1 = point2.z - point1.z;
  2493. var x2 = point3.x - point1.x;
  2494. var y2 = point3.y - point1.y;
  2495. var z2 = point3.z - point1.z;
  2496. var yz = (y1 * z2) - (z1 * y2);
  2497. var xz = (z1 * x2) - (x1 * z2);
  2498. var xy = (x1 * y2) - (y1 * x2);
  2499. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2500. var invPyth;
  2501. if (pyth !== 0) {
  2502. invPyth = 1.0 / pyth;
  2503. }
  2504. else {
  2505. invPyth = 0;
  2506. }
  2507. this.normal.x = yz * invPyth;
  2508. this.normal.y = xz * invPyth;
  2509. this.normal.z = xy * invPyth;
  2510. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2511. return this;
  2512. };
  2513. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2514. var dot = Vector3.Dot(this.normal, direction);
  2515. return (dot <= epsilon);
  2516. };
  2517. Plane.prototype.signedDistanceTo = function (point) {
  2518. return Vector3.Dot(point, this.normal) + this.d;
  2519. };
  2520. // Statics
  2521. Plane.FromArray = function (array) {
  2522. return new Plane(array[0], array[1], array[2], array[3]);
  2523. };
  2524. Plane.FromPoints = function (point1, point2, point3) {
  2525. var result = new Plane(0, 0, 0, 0);
  2526. result.copyFromPoints(point1, point2, point3);
  2527. return result;
  2528. };
  2529. Plane.FromPositionAndNormal = function (origin, normal) {
  2530. var result = new Plane(0, 0, 0, 0);
  2531. normal.normalize();
  2532. result.normal = normal;
  2533. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2534. return result;
  2535. };
  2536. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2537. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2538. return Vector3.Dot(point, normal) + d;
  2539. };
  2540. return Plane;
  2541. })();
  2542. BABYLON.Plane = Plane;
  2543. var Viewport = (function () {
  2544. function Viewport(x, y, width, height) {
  2545. this.x = x;
  2546. this.y = y;
  2547. this.width = width;
  2548. this.height = height;
  2549. }
  2550. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2551. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2552. };
  2553. return Viewport;
  2554. })();
  2555. BABYLON.Viewport = Viewport;
  2556. var Frustum = (function () {
  2557. function Frustum() {
  2558. }
  2559. Frustum.GetPlanes = function (transform) {
  2560. var frustumPlanes = [];
  2561. for (var index = 0; index < 6; index++) {
  2562. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2563. }
  2564. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2565. return frustumPlanes;
  2566. };
  2567. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2568. // Near
  2569. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2570. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2571. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2572. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2573. frustumPlanes[0].normalize();
  2574. // Far
  2575. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2576. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2577. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2578. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2579. frustumPlanes[1].normalize();
  2580. // Left
  2581. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2582. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2583. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2584. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2585. frustumPlanes[2].normalize();
  2586. // Right
  2587. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2588. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2589. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2590. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2591. frustumPlanes[3].normalize();
  2592. // Top
  2593. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2594. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2595. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2596. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2597. frustumPlanes[4].normalize();
  2598. // Bottom
  2599. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2600. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2601. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2602. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2603. frustumPlanes[5].normalize();
  2604. };
  2605. return Frustum;
  2606. })();
  2607. BABYLON.Frustum = Frustum;
  2608. (function (Space) {
  2609. Space[Space["LOCAL"] = 0] = "LOCAL";
  2610. Space[Space["WORLD"] = 1] = "WORLD";
  2611. })(BABYLON.Space || (BABYLON.Space = {}));
  2612. var Space = BABYLON.Space;
  2613. var Axis = (function () {
  2614. function Axis() {
  2615. }
  2616. Axis.X = new Vector3(1, 0, 0);
  2617. Axis.Y = new Vector3(0, 1, 0);
  2618. Axis.Z = new Vector3(0, 0, 1);
  2619. return Axis;
  2620. })();
  2621. BABYLON.Axis = Axis;
  2622. ;
  2623. var BezierCurve = (function () {
  2624. function BezierCurve() {
  2625. }
  2626. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2627. // Extract X (which is equal to time here)
  2628. var f0 = 1 - 3 * x2 + 3 * x1;
  2629. var f1 = 3 * x2 - 6 * x1;
  2630. var f2 = 3 * x1;
  2631. var refinedT = t;
  2632. for (var i = 0; i < 5; i++) {
  2633. var refinedT2 = refinedT * refinedT;
  2634. var refinedT3 = refinedT2 * refinedT;
  2635. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2636. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2637. refinedT -= (x - t) * slope;
  2638. refinedT = Math.min(1, Math.max(0, refinedT));
  2639. }
  2640. // Resolve cubic bezier for the given x
  2641. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2642. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2643. Math.pow(refinedT, 3);
  2644. };
  2645. return BezierCurve;
  2646. })();
  2647. BABYLON.BezierCurve = BezierCurve;
  2648. (function (Orientation) {
  2649. Orientation[Orientation["CW"] = 0] = "CW";
  2650. Orientation[Orientation["CCW"] = 1] = "CCW";
  2651. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2652. var Orientation = BABYLON.Orientation;
  2653. var Angle = (function () {
  2654. function Angle(radians) {
  2655. var _this = this;
  2656. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2657. this.radians = function () { return _this._radians; };
  2658. this._radians = radians;
  2659. if (this._radians < 0)
  2660. this._radians += (2 * Math.PI);
  2661. }
  2662. Angle.BetweenTwoPoints = function (a, b) {
  2663. var delta = b.subtract(a);
  2664. var theta = Math.atan2(delta.y, delta.x);
  2665. return new Angle(theta);
  2666. };
  2667. Angle.FromRadians = function (radians) {
  2668. return new Angle(radians);
  2669. };
  2670. Angle.FromDegrees = function (degrees) {
  2671. return new Angle(degrees * Math.PI / 180);
  2672. };
  2673. return Angle;
  2674. })();
  2675. BABYLON.Angle = Angle;
  2676. var Arc2 = (function () {
  2677. function Arc2(startPoint, midPoint, endPoint) {
  2678. this.startPoint = startPoint;
  2679. this.midPoint = midPoint;
  2680. this.endPoint = endPoint;
  2681. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2682. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2683. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2684. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2685. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2686. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2687. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2688. var a1 = this.startAngle.degrees();
  2689. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2690. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2691. // angles correction
  2692. if (a2 - a1 > +180.0)
  2693. a2 -= 360.0;
  2694. if (a2 - a1 < -180.0)
  2695. a2 += 360.0;
  2696. if (a3 - a2 > +180.0)
  2697. a3 -= 360.0;
  2698. if (a3 - a2 < -180.0)
  2699. a3 += 360.0;
  2700. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2701. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2702. }
  2703. return Arc2;
  2704. })();
  2705. BABYLON.Arc2 = Arc2;
  2706. var Path2 = (function () {
  2707. function Path2(x, y) {
  2708. this._points = new Array();
  2709. this._length = 0;
  2710. this.closed = false;
  2711. this._points.push(new Vector2(x, y));
  2712. }
  2713. Path2.prototype.addLineTo = function (x, y) {
  2714. if (closed) {
  2715. //Tools.Error("cannot add lines to closed paths");
  2716. return this;
  2717. }
  2718. var newPoint = new Vector2(x, y);
  2719. var previousPoint = this._points[this._points.length - 1];
  2720. this._points.push(newPoint);
  2721. this._length += newPoint.subtract(previousPoint).length();
  2722. return this;
  2723. };
  2724. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2725. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2726. if (closed) {
  2727. //Tools.Error("cannot add arcs to closed paths");
  2728. return this;
  2729. }
  2730. var startPoint = this._points[this._points.length - 1];
  2731. var midPoint = new Vector2(midX, midY);
  2732. var endPoint = new Vector2(endX, endY);
  2733. var arc = new Arc2(startPoint, midPoint, endPoint);
  2734. var increment = arc.angle.radians() / numberOfSegments;
  2735. if (arc.orientation === Orientation.CW)
  2736. increment *= -1;
  2737. var currentAngle = arc.startAngle.radians() + increment;
  2738. for (var i = 0; i < numberOfSegments; i++) {
  2739. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2740. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2741. this.addLineTo(x, y);
  2742. currentAngle += increment;
  2743. }
  2744. return this;
  2745. };
  2746. Path2.prototype.close = function () {
  2747. this.closed = true;
  2748. return this;
  2749. };
  2750. Path2.prototype.length = function () {
  2751. var result = this._length;
  2752. if (!this.closed) {
  2753. var lastPoint = this._points[this._points.length - 1];
  2754. var firstPoint = this._points[0];
  2755. result += (firstPoint.subtract(lastPoint).length());
  2756. }
  2757. return result;
  2758. };
  2759. Path2.prototype.getPoints = function () {
  2760. return this._points;
  2761. };
  2762. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2763. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2764. //Tools.Error("normalized length position should be between 0 and 1.");
  2765. return Vector2.Zero();
  2766. }
  2767. var lengthPosition = normalizedLengthPosition * this.length();
  2768. var previousOffset = 0;
  2769. for (var i = 0; i < this._points.length; i++) {
  2770. var j = (i + 1) % this._points.length;
  2771. var a = this._points[i];
  2772. var b = this._points[j];
  2773. var bToA = b.subtract(a);
  2774. var nextOffset = (bToA.length() + previousOffset);
  2775. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2776. var dir = bToA.normalize();
  2777. var localOffset = lengthPosition - previousOffset;
  2778. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2779. }
  2780. previousOffset = nextOffset;
  2781. }
  2782. //Tools.Error("internal error");
  2783. return Vector2.Zero();
  2784. };
  2785. Path2.StartingAt = function (x, y) {
  2786. return new Path2(x, y);
  2787. };
  2788. return Path2;
  2789. })();
  2790. BABYLON.Path2 = Path2;
  2791. var Path3D = (function () {
  2792. /**
  2793. * new Path3D(path, normal, raw)
  2794. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2795. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2796. * path : an array of Vector3, the curve axis of the Path3D
  2797. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2798. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2799. */
  2800. function Path3D(path, firstNormal, raw) {
  2801. this.path = path;
  2802. this._curve = new Array();
  2803. this._distances = new Array();
  2804. this._tangents = new Array();
  2805. this._normals = new Array();
  2806. this._binormals = new Array();
  2807. for (var p = 0; p < path.length; p++) {
  2808. this._curve[p] = path[p].clone(); // hard copy
  2809. }
  2810. this._raw = raw || false;
  2811. this._compute(firstNormal);
  2812. }
  2813. /**
  2814. * Returns the Path3D array of successive Vector3 designing its curve.
  2815. */
  2816. Path3D.prototype.getCurve = function () {
  2817. return this._curve;
  2818. };
  2819. /**
  2820. * Returns an array populated with tangent vectors on each Path3D curve point.
  2821. */
  2822. Path3D.prototype.getTangents = function () {
  2823. return this._tangents;
  2824. };
  2825. /**
  2826. * Returns an array populated with normal vectors on each Path3D curve point.
  2827. */
  2828. Path3D.prototype.getNormals = function () {
  2829. return this._normals;
  2830. };
  2831. /**
  2832. * Returns an array populated with binormal vectors on each Path3D curve point.
  2833. */
  2834. Path3D.prototype.getBinormals = function () {
  2835. return this._binormals;
  2836. };
  2837. /**
  2838. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2839. */
  2840. Path3D.prototype.getDistances = function () {
  2841. return this._distances;
  2842. };
  2843. /**
  2844. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2845. * Returns the same object updated.
  2846. */
  2847. Path3D.prototype.update = function (path, firstNormal) {
  2848. for (var p = 0; p < path.length; p++) {
  2849. this._curve[p].x = path[p].x;
  2850. this._curve[p].y = path[p].y;
  2851. this._curve[p].z = path[p].z;
  2852. }
  2853. this._compute(firstNormal);
  2854. return this;
  2855. };
  2856. // private function compute() : computes tangents, normals and binormals
  2857. Path3D.prototype._compute = function (firstNormal) {
  2858. var l = this._curve.length;
  2859. // first and last tangents
  2860. this._tangents[0] = this._getFirstNonNullVector(0);
  2861. if (!this._raw) {
  2862. this._tangents[0].normalize();
  2863. }
  2864. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2865. if (!this._raw) {
  2866. this._tangents[l - 1].normalize();
  2867. }
  2868. // normals and binormals at first point : arbitrary vector with _normalVector()
  2869. var tg0 = this._tangents[0];
  2870. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2871. this._normals[0] = pp0;
  2872. if (!this._raw) {
  2873. this._normals[0].normalize();
  2874. }
  2875. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2876. if (!this._raw) {
  2877. this._binormals[0].normalize();
  2878. }
  2879. this._distances[0] = 0.0;
  2880. // normals and binormals : next points
  2881. var prev; // previous vector (segment)
  2882. var cur; // current vector (segment)
  2883. var curTang; // current tangent
  2884. // previous normal
  2885. var prevBinor; // previous binormal
  2886. for (var i = 1; i < l; i++) {
  2887. // tangents
  2888. prev = this._getLastNonNullVector(i);
  2889. if (i < l - 1) {
  2890. cur = this._getFirstNonNullVector(i);
  2891. this._tangents[i] = prev.add(cur);
  2892. this._tangents[i].normalize();
  2893. }
  2894. this._distances[i] = this._distances[i - 1] + prev.length();
  2895. // normals and binormals
  2896. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2897. curTang = this._tangents[i];
  2898. prevBinor = this._binormals[i - 1];
  2899. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2900. if (!this._raw) {
  2901. this._normals[i].normalize();
  2902. }
  2903. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2904. if (!this._raw) {
  2905. this._binormals[i].normalize();
  2906. }
  2907. }
  2908. };
  2909. // private function getFirstNonNullVector(index)
  2910. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2911. Path3D.prototype._getFirstNonNullVector = function (index) {
  2912. var i = 1;
  2913. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2914. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2915. i++;
  2916. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2917. }
  2918. return nNVector;
  2919. };
  2920. // private function getLastNonNullVector(index)
  2921. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2922. Path3D.prototype._getLastNonNullVector = function (index) {
  2923. var i = 1;
  2924. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2925. while (nLVector.length() === 0 && index > i + 1) {
  2926. i++;
  2927. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2928. }
  2929. return nLVector;
  2930. };
  2931. // private function normalVector(v0, vt, va) :
  2932. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2933. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2934. Path3D.prototype._normalVector = function (v0, vt, va) {
  2935. var normal0;
  2936. var tgl = vt.length();
  2937. if (tgl === 0.0) {
  2938. tgl = 1.0;
  2939. }
  2940. if (va === undefined || va === null) {
  2941. var point;
  2942. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  2943. point = new Vector3(0.0, -1.0, 0.0);
  2944. }
  2945. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  2946. point = new Vector3(1.0, 0.0, 0.0);
  2947. }
  2948. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  2949. point = new Vector3(0.0, 0.0, 1.0);
  2950. }
  2951. normal0 = Vector3.Cross(vt, point);
  2952. }
  2953. else {
  2954. normal0 = Vector3.Cross(vt, va);
  2955. Vector3.CrossToRef(normal0, vt, normal0);
  2956. }
  2957. normal0.normalize();
  2958. return normal0;
  2959. };
  2960. return Path3D;
  2961. })();
  2962. BABYLON.Path3D = Path3D;
  2963. var Curve3 = (function () {
  2964. /**
  2965. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2966. * A Curve3 is designed from a series of successive Vector3.
  2967. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2968. */
  2969. function Curve3(points) {
  2970. this._length = 0.0;
  2971. this._points = points;
  2972. this._length = this._computeLength(points);
  2973. }
  2974. /**
  2975. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2976. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2977. * @param v1 (Vector3) the control point
  2978. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2979. * @param nbPoints (integer) the wanted number of points in the curve
  2980. */
  2981. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2982. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2983. var bez = new Array();
  2984. var equation = function (t, val0, val1, val2) {
  2985. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  2986. return res;
  2987. };
  2988. for (var i = 0; i <= nbPoints; i++) {
  2989. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2990. }
  2991. return new Curve3(bez);
  2992. };
  2993. /**
  2994. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2995. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2996. * @param v1 (Vector3) the first control point
  2997. * @param v2 (Vector3) the second control point
  2998. * @param v3 (Vector3) the end point of the Cubic Bezier
  2999. * @param nbPoints (integer) the wanted number of points in the curve
  3000. */
  3001. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3002. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3003. var bez = new Array();
  3004. var equation = function (t, val0, val1, val2, val3) {
  3005. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  3006. return res;
  3007. };
  3008. for (var i = 0; i <= nbPoints; i++) {
  3009. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  3010. }
  3011. return new Curve3(bez);
  3012. };
  3013. /**
  3014. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3015. * @param p1 (Vector3) the origin point of the Hermite Spline
  3016. * @param t1 (Vector3) the tangent vector at the origin point
  3017. * @param p2 (Vector3) the end point of the Hermite Spline
  3018. * @param t2 (Vector3) the tangent vector at the end point
  3019. * @param nbPoints (integer) the wanted number of points in the curve
  3020. */
  3021. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3022. var hermite = new Array();
  3023. var step = 1.0 / nbPoints;
  3024. for (var i = 0; i <= nbPoints; i++) {
  3025. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3026. }
  3027. return new Curve3(hermite);
  3028. };
  3029. /**
  3030. * Returns the Curve3 stored array of successive Vector3
  3031. */
  3032. Curve3.prototype.getPoints = function () {
  3033. return this._points;
  3034. };
  3035. /**
  3036. * Returns the computed length (float) of the curve.
  3037. */
  3038. Curve3.prototype.length = function () {
  3039. return this._length;
  3040. };
  3041. /**
  3042. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3043. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3044. * curveA and curveB keep unchanged.
  3045. */
  3046. Curve3.prototype.continue = function (curve) {
  3047. var lastPoint = this._points[this._points.length - 1];
  3048. var continuedPoints = this._points.slice();
  3049. var curvePoints = curve.getPoints();
  3050. for (var i = 1; i < curvePoints.length; i++) {
  3051. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3052. }
  3053. var continuedCurve = new Curve3(continuedPoints);
  3054. return continuedCurve;
  3055. };
  3056. Curve3.prototype._computeLength = function (path) {
  3057. var l = 0;
  3058. for (var i = 1; i < path.length; i++) {
  3059. l += (path[i].subtract(path[i - 1])).length();
  3060. }
  3061. return l;
  3062. };
  3063. return Curve3;
  3064. })();
  3065. BABYLON.Curve3 = Curve3;
  3066. // SphericalHarmonics
  3067. var SphericalHarmonics = (function () {
  3068. function SphericalHarmonics() {
  3069. this.L00 = Vector3.Zero();
  3070. this.L1_1 = Vector3.Zero();
  3071. this.L10 = Vector3.Zero();
  3072. this.L11 = Vector3.Zero();
  3073. this.L2_2 = Vector3.Zero();
  3074. this.L2_1 = Vector3.Zero();
  3075. this.L20 = Vector3.Zero();
  3076. this.L21 = Vector3.Zero();
  3077. this.L22 = Vector3.Zero();
  3078. }
  3079. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3080. var colorVector = new Vector3(color.r, color.g, color.b);
  3081. var c = colorVector.scale(deltaSolidAngle);
  3082. this.L00 = this.L00.add(c.scale(0.282095));
  3083. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3084. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3085. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3086. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3087. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3088. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3089. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3090. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3091. };
  3092. SphericalHarmonics.prototype.scale = function (scale) {
  3093. this.L00 = this.L00.scale(scale);
  3094. this.L1_1 = this.L1_1.scale(scale);
  3095. this.L10 = this.L10.scale(scale);
  3096. this.L11 = this.L11.scale(scale);
  3097. this.L2_2 = this.L2_2.scale(scale);
  3098. this.L2_1 = this.L2_1.scale(scale);
  3099. this.L20 = this.L20.scale(scale);
  3100. this.L21 = this.L21.scale(scale);
  3101. this.L22 = this.L22.scale(scale);
  3102. };
  3103. return SphericalHarmonics;
  3104. })();
  3105. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3106. // SphericalPolynomial
  3107. var SphericalPolynomial = (function () {
  3108. function SphericalPolynomial() {
  3109. this.x = Vector3.Zero();
  3110. this.y = Vector3.Zero();
  3111. this.z = Vector3.Zero();
  3112. this.xx = Vector3.Zero();
  3113. this.yy = Vector3.Zero();
  3114. this.zz = Vector3.Zero();
  3115. this.xy = Vector3.Zero();
  3116. this.yz = Vector3.Zero();
  3117. this.zx = Vector3.Zero();
  3118. }
  3119. SphericalPolynomial.prototype.addAmbient = function (color) {
  3120. var colorVector = new Vector3(color.r, color.g, color.b);
  3121. this.xx = this.xx.add(colorVector);
  3122. this.yy = this.yy.add(colorVector);
  3123. this.zz = this.zz.add(colorVector);
  3124. };
  3125. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3126. var result = new SphericalPolynomial();
  3127. result.x = harmonics.L11.scale(1.02333);
  3128. result.y = harmonics.L1_1.scale(1.02333);
  3129. result.z = harmonics.L10.scale(1.02333);
  3130. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3131. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3132. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3133. result.yz = harmonics.L2_1.scale(0.858086);
  3134. result.zx = harmonics.L21.scale(0.858086);
  3135. result.xy = harmonics.L2_2.scale(0.858086);
  3136. return result;
  3137. };
  3138. return SphericalPolynomial;
  3139. })();
  3140. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3141. // Vertex formats
  3142. var PositionNormalVertex = (function () {
  3143. function PositionNormalVertex(position, normal) {
  3144. if (position === void 0) { position = Vector3.Zero(); }
  3145. if (normal === void 0) { normal = Vector3.Up(); }
  3146. this.position = position;
  3147. this.normal = normal;
  3148. }
  3149. PositionNormalVertex.prototype.clone = function () {
  3150. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3151. };
  3152. return PositionNormalVertex;
  3153. })();
  3154. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3155. var PositionNormalTextureVertex = (function () {
  3156. function PositionNormalTextureVertex(position, normal, uv) {
  3157. if (position === void 0) { position = Vector3.Zero(); }
  3158. if (normal === void 0) { normal = Vector3.Up(); }
  3159. if (uv === void 0) { uv = Vector2.Zero(); }
  3160. this.position = position;
  3161. this.normal = normal;
  3162. this.uv = uv;
  3163. }
  3164. PositionNormalTextureVertex.prototype.clone = function () {
  3165. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3166. };
  3167. return PositionNormalTextureVertex;
  3168. })();
  3169. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3170. // Temporary pre-allocated objects for engine internal use
  3171. // usage in any internal function :
  3172. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3173. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3174. var Tmp = (function () {
  3175. function Tmp() {
  3176. }
  3177. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3178. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3179. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3180. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3181. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3182. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3183. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3184. Matrix.Zero(), Matrix.Zero(),
  3185. Matrix.Zero(), Matrix.Zero(),
  3186. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3187. return Tmp;
  3188. })();
  3189. BABYLON.Tmp = Tmp;
  3190. })(BABYLON || (BABYLON = {}));
  3191. var BABYLON;
  3192. (function (BABYLON) {
  3193. function generateSerializableMember(type, sourceName) {
  3194. return function (target, propertyKey) {
  3195. if (!target.__serializableMembers) {
  3196. target.__serializableMembers = {};
  3197. }
  3198. if (!target.__serializableMembers[propertyKey]) {
  3199. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3200. }
  3201. };
  3202. }
  3203. function serialize(sourceName) {
  3204. return generateSerializableMember(0, sourceName); // value member
  3205. }
  3206. BABYLON.serialize = serialize;
  3207. function serializeAsTexture(sourceName) {
  3208. return generateSerializableMember(1, sourceName); // texture member
  3209. }
  3210. BABYLON.serializeAsTexture = serializeAsTexture;
  3211. function serializeAsColor3(sourceName) {
  3212. return generateSerializableMember(2, sourceName); // color3 member
  3213. }
  3214. BABYLON.serializeAsColor3 = serializeAsColor3;
  3215. function serializeAsFresnelParameters(sourceName) {
  3216. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3217. }
  3218. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3219. function serializeAsVector2(sourceName) {
  3220. return generateSerializableMember(4, sourceName); // vector2 member
  3221. }
  3222. BABYLON.serializeAsVector2 = serializeAsVector2;
  3223. function serializeAsVector3(sourceName) {
  3224. return generateSerializableMember(5, sourceName); // vector3 member
  3225. }
  3226. BABYLON.serializeAsVector3 = serializeAsVector3;
  3227. function serializeAsMeshReference(sourceName) {
  3228. return generateSerializableMember(6, sourceName); // mesh reference member
  3229. }
  3230. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3231. function serializeAsColorCurves(sourceName) {
  3232. return generateSerializableMember(7, sourceName); // color curves
  3233. }
  3234. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3235. var SerializationHelper = (function () {
  3236. function SerializationHelper() {
  3237. }
  3238. SerializationHelper.Serialize = function (entity, serializationObject) {
  3239. if (!serializationObject) {
  3240. serializationObject = {};
  3241. }
  3242. // Tags
  3243. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3244. // Properties
  3245. for (var property in entity.__serializableMembers) {
  3246. var propertyDescriptor = entity.__serializableMembers[property];
  3247. var targetPropertyName = propertyDescriptor.sourceName || property;
  3248. var propertyType = propertyDescriptor.type;
  3249. var sourceProperty = entity[property];
  3250. if (sourceProperty !== undefined && sourceProperty !== null) {
  3251. switch (propertyType) {
  3252. case 0:
  3253. serializationObject[targetPropertyName] = sourceProperty;
  3254. break;
  3255. case 1:
  3256. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3257. break;
  3258. case 2:
  3259. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3260. break;
  3261. case 3:
  3262. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3263. break;
  3264. case 4:
  3265. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3266. break;
  3267. case 5:
  3268. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3269. break;
  3270. case 6:
  3271. serializationObject[targetPropertyName] = sourceProperty.id;
  3272. break;
  3273. case 7:
  3274. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3275. break;
  3276. }
  3277. }
  3278. }
  3279. return serializationObject;
  3280. };
  3281. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3282. var destination = creationFunction();
  3283. // Tags
  3284. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3285. // Properties
  3286. for (var property in destination.__serializableMembers) {
  3287. var propertyDescriptor = destination.__serializableMembers[property];
  3288. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3289. var propertyType = propertyDescriptor.type;
  3290. if (sourceProperty !== undefined && sourceProperty !== null) {
  3291. switch (propertyType) {
  3292. case 0:
  3293. destination[property] = sourceProperty;
  3294. break;
  3295. case 1:
  3296. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3297. break;
  3298. case 2:
  3299. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3300. break;
  3301. case 3:
  3302. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3303. break;
  3304. case 4:
  3305. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3306. break;
  3307. case 5:
  3308. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3309. break;
  3310. case 6:
  3311. destination[property] = scene.getLastMeshByID(sourceProperty);
  3312. break;
  3313. case 7:
  3314. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3315. break;
  3316. }
  3317. }
  3318. }
  3319. return destination;
  3320. };
  3321. SerializationHelper.Clone = function (creationFunction, source) {
  3322. var destination = creationFunction();
  3323. // Tags
  3324. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3325. // Properties
  3326. for (var property in destination.__serializableMembers) {
  3327. var propertyDescriptor = destination.__serializableMembers[property];
  3328. var sourceProperty = source[property];
  3329. var propertyType = propertyDescriptor.type;
  3330. if (sourceProperty !== undefined && sourceProperty !== null) {
  3331. switch (propertyType) {
  3332. case 0: // Value
  3333. case 6:
  3334. destination[property] = sourceProperty;
  3335. break;
  3336. case 1: // Texture
  3337. case 2: // Color3
  3338. case 3: // FresnelParameters
  3339. case 4: // Vector2
  3340. case 5: // Vector3
  3341. case 7:
  3342. destination[property] = sourceProperty.clone();
  3343. break;
  3344. }
  3345. }
  3346. }
  3347. return destination;
  3348. };
  3349. return SerializationHelper;
  3350. })();
  3351. BABYLON.SerializationHelper = SerializationHelper;
  3352. })(BABYLON || (BABYLON = {}));
  3353. var BABYLON;
  3354. (function (BABYLON) {
  3355. /**
  3356. * A class serves as a medium between the observable and its observers
  3357. */
  3358. var EventState = (function () {
  3359. /**
  3360. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3361. */
  3362. function EventState(mask, skipNextObservers) {
  3363. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3364. this.initalize(mask, skipNextObservers);
  3365. }
  3366. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3367. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3368. this.mask = mask;
  3369. this.skipNextObservers = skipNextObservers;
  3370. return this;
  3371. };
  3372. return EventState;
  3373. })();
  3374. BABYLON.EventState = EventState;
  3375. /**
  3376. * Represent an Observer registered to a given Observable object.
  3377. */
  3378. var Observer = (function () {
  3379. function Observer(callback, mask) {
  3380. this.callback = callback;
  3381. this.mask = mask;
  3382. }
  3383. return Observer;
  3384. })();
  3385. BABYLON.Observer = Observer;
  3386. /**
  3387. * The Observable class is a simple implementation of the Observable pattern.
  3388. * 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.
  3389. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3390. * 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).
  3391. * 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.
  3392. */
  3393. var Observable = (function () {
  3394. function Observable() {
  3395. this._observers = new Array();
  3396. this._eventState = new EventState(0);
  3397. }
  3398. /**
  3399. * Create a new Observer with the specified callback
  3400. * @param callback the callback that will be executed for that Observer
  3401. * @param mask the mask used to filter observers
  3402. * @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.
  3403. */
  3404. Observable.prototype.add = function (callback, mask, insertFirst) {
  3405. if (mask === void 0) { mask = -1; }
  3406. if (insertFirst === void 0) { insertFirst = false; }
  3407. if (!callback) {
  3408. return null;
  3409. }
  3410. var observer = new Observer(callback, mask);
  3411. if (insertFirst) {
  3412. this._observers.unshift(observer);
  3413. }
  3414. else {
  3415. this._observers.push(observer);
  3416. }
  3417. return observer;
  3418. };
  3419. /**
  3420. * Remove an Observer from the Observable object
  3421. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3422. */
  3423. Observable.prototype.remove = function (observer) {
  3424. var index = this._observers.indexOf(observer);
  3425. if (index !== -1) {
  3426. this._observers.splice(index, 1);
  3427. return true;
  3428. }
  3429. return false;
  3430. };
  3431. /**
  3432. * Remove a callback from the Observable object
  3433. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3434. */
  3435. Observable.prototype.removeCallback = function (callback) {
  3436. for (var index = 0; index < this._observers.length; index++) {
  3437. if (this._observers[index].callback === callback) {
  3438. this._observers.splice(index, 1);
  3439. return true;
  3440. }
  3441. }
  3442. return false;
  3443. };
  3444. /**
  3445. * Notify all Observers by calling their respective callback with the given data
  3446. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3447. * @param eventData
  3448. * @param mask
  3449. */
  3450. Observable.prototype.notifyObservers = function (eventData, mask) {
  3451. if (mask === void 0) { mask = -1; }
  3452. var state = this._eventState;
  3453. state.mask = mask;
  3454. state.skipNextObservers = false;
  3455. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3456. var obs = _a[_i];
  3457. if (obs.mask & mask) {
  3458. obs.callback(eventData, state);
  3459. }
  3460. if (state.skipNextObservers) {
  3461. return false;
  3462. }
  3463. }
  3464. return true;
  3465. };
  3466. /**
  3467. * return true is the Observable has at least one Observer registered
  3468. */
  3469. Observable.prototype.hasObservers = function () {
  3470. return this._observers.length > 0;
  3471. };
  3472. /**
  3473. * Clear the list of observers
  3474. */
  3475. Observable.prototype.clear = function () {
  3476. this._observers = new Array();
  3477. };
  3478. /**
  3479. * Clone the current observable
  3480. */
  3481. Observable.prototype.clone = function () {
  3482. var result = new Observable();
  3483. result._observers = this._observers.slice(0);
  3484. return result;
  3485. };
  3486. return Observable;
  3487. })();
  3488. BABYLON.Observable = Observable;
  3489. })(BABYLON || (BABYLON = {}));
  3490. var BABYLON;
  3491. (function (BABYLON) {
  3492. var Database = (function () {
  3493. function Database(urlToScene, callbackManifestChecked) {
  3494. // Handling various flavors of prefixed version of IndexedDB
  3495. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3496. this.callbackManifestChecked = callbackManifestChecked;
  3497. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3498. this.db = null;
  3499. this.enableSceneOffline = false;
  3500. this.enableTexturesOffline = false;
  3501. this.manifestVersionFound = 0;
  3502. this.mustUpdateRessources = false;
  3503. this.hasReachedQuota = false;
  3504. if (!Database.IDBStorageEnabled) {
  3505. this.callbackManifestChecked(true);
  3506. }
  3507. else {
  3508. this.checkManifestFile();
  3509. }
  3510. }
  3511. Database.prototype.checkManifestFile = function () {
  3512. var _this = this;
  3513. function noManifestFile() {
  3514. that.enableSceneOffline = false;
  3515. that.enableTexturesOffline = false;
  3516. that.callbackManifestChecked(false);
  3517. }
  3518. var that = this;
  3519. var timeStampUsed = false;
  3520. var manifestURL = this.currentSceneUrl + ".manifest";
  3521. var xhr = new XMLHttpRequest();
  3522. if (navigator.onLine) {
  3523. // Adding a timestamp to by-pass browsers' cache
  3524. timeStampUsed = true;
  3525. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3526. }
  3527. xhr.open("GET", manifestURL, true);
  3528. xhr.addEventListener("load", function () {
  3529. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3530. try {
  3531. var manifestFile = JSON.parse(xhr.response);
  3532. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3533. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3534. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3535. _this.manifestVersionFound = manifestFile.version;
  3536. }
  3537. if (_this.callbackManifestChecked) {
  3538. _this.callbackManifestChecked(true);
  3539. }
  3540. }
  3541. catch (ex) {
  3542. noManifestFile();
  3543. }
  3544. }
  3545. else {
  3546. noManifestFile();
  3547. }
  3548. }, false);
  3549. xhr.addEventListener("error", function (event) {
  3550. if (timeStampUsed) {
  3551. timeStampUsed = false;
  3552. // Let's retry without the timeStamp
  3553. // It could fail when coupled with HTML5 Offline API
  3554. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3555. xhr.open("GET", retryManifestURL, true);
  3556. xhr.send();
  3557. }
  3558. else {
  3559. noManifestFile();
  3560. }
  3561. }, false);
  3562. try {
  3563. xhr.send();
  3564. }
  3565. catch (ex) {
  3566. BABYLON.Tools.Error("Error on XHR send request.");
  3567. that.callbackManifestChecked(false);
  3568. }
  3569. };
  3570. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3571. var _this = this;
  3572. function handleError() {
  3573. that.isSupported = false;
  3574. if (errorCallback)
  3575. errorCallback();
  3576. }
  3577. var that = this;
  3578. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3579. // Your browser doesn't support IndexedDB
  3580. this.isSupported = false;
  3581. if (errorCallback)
  3582. errorCallback();
  3583. }
  3584. else {
  3585. // If the DB hasn't been opened or created yet
  3586. if (!this.db) {
  3587. this.hasReachedQuota = false;
  3588. this.isSupported = true;
  3589. var request = this.idbFactory.open("babylonjs", 1);
  3590. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3591. request.onerror = function (event) {
  3592. handleError();
  3593. };
  3594. // executes when a version change transaction cannot complete due to other active transactions
  3595. request.onblocked = function (event) {
  3596. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3597. handleError();
  3598. };
  3599. // DB has been opened successfully
  3600. request.onsuccess = function (event) {
  3601. _this.db = request.result;
  3602. successCallback();
  3603. };
  3604. // Initialization of the DB. Creating Scenes & Textures stores
  3605. request.onupgradeneeded = function (event) {
  3606. _this.db = (event.target).result;
  3607. try {
  3608. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3609. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3610. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3611. }
  3612. catch (ex) {
  3613. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3614. handleError();
  3615. }
  3616. };
  3617. }
  3618. else {
  3619. if (successCallback)
  3620. successCallback();
  3621. }
  3622. }
  3623. };
  3624. Database.prototype.loadImageFromDB = function (url, image) {
  3625. var _this = this;
  3626. var completeURL = Database.ReturnFullUrlLocation(url);
  3627. var saveAndLoadImage = function () {
  3628. if (!_this.hasReachedQuota && _this.db !== null) {
  3629. // the texture is not yet in the DB, let's try to save it
  3630. _this._saveImageIntoDBAsync(completeURL, image);
  3631. }
  3632. else {
  3633. image.src = url;
  3634. }
  3635. };
  3636. if (!this.mustUpdateRessources) {
  3637. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3638. }
  3639. else {
  3640. saveAndLoadImage();
  3641. }
  3642. };
  3643. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3644. if (this.isSupported && this.db !== null) {
  3645. var texture;
  3646. var transaction = this.db.transaction(["textures"]);
  3647. transaction.onabort = function (event) {
  3648. image.src = url;
  3649. };
  3650. transaction.oncomplete = function (event) {
  3651. var blobTextureURL;
  3652. if (texture) {
  3653. var URL = window.URL || window.webkitURL;
  3654. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3655. image.onerror = function () {
  3656. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3657. image.src = url;
  3658. };
  3659. image.src = blobTextureURL;
  3660. }
  3661. else {
  3662. notInDBCallback();
  3663. }
  3664. };
  3665. var getRequest = transaction.objectStore("textures").get(url);
  3666. getRequest.onsuccess = function (event) {
  3667. texture = (event.target).result;
  3668. };
  3669. getRequest.onerror = function (event) {
  3670. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3671. image.src = url;
  3672. };
  3673. }
  3674. else {
  3675. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3676. image.src = url;
  3677. }
  3678. };
  3679. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3680. var _this = this;
  3681. if (this.isSupported) {
  3682. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3683. var generateBlobUrl = function () {
  3684. var blobTextureURL;
  3685. if (blob) {
  3686. var URL = window.URL || window.webkitURL;
  3687. try {
  3688. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3689. }
  3690. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3691. catch (ex) {
  3692. blobTextureURL = URL.createObjectURL(blob);
  3693. }
  3694. }
  3695. image.src = blobTextureURL;
  3696. };
  3697. if (Database.IsUASupportingBlobStorage) {
  3698. var xhr = new XMLHttpRequest(), blob;
  3699. xhr.open("GET", url, true);
  3700. xhr.responseType = "blob";
  3701. xhr.addEventListener("load", function () {
  3702. if (xhr.status === 200) {
  3703. // Blob as response (XHR2)
  3704. blob = xhr.response;
  3705. var transaction = _this.db.transaction(["textures"], "readwrite");
  3706. // the transaction could abort because of a QuotaExceededError error
  3707. transaction.onabort = function (event) {
  3708. try {
  3709. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3710. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3711. this.hasReachedQuota = true;
  3712. }
  3713. }
  3714. catch (ex) { }
  3715. generateBlobUrl();
  3716. };
  3717. transaction.oncomplete = function (event) {
  3718. generateBlobUrl();
  3719. };
  3720. var newTexture = { textureUrl: url, data: blob };
  3721. try {
  3722. // Put the blob into the dabase
  3723. var addRequest = transaction.objectStore("textures").put(newTexture);
  3724. addRequest.onsuccess = function (event) {
  3725. };
  3726. addRequest.onerror = function (event) {
  3727. generateBlobUrl();
  3728. };
  3729. }
  3730. catch (ex) {
  3731. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3732. if (ex.code === 25) {
  3733. Database.IsUASupportingBlobStorage = false;
  3734. }
  3735. image.src = url;
  3736. }
  3737. }
  3738. else {
  3739. image.src = url;
  3740. }
  3741. }, false);
  3742. xhr.addEventListener("error", function (event) {
  3743. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3744. image.src = url;
  3745. }, false);
  3746. xhr.send();
  3747. }
  3748. else {
  3749. image.src = url;
  3750. }
  3751. }
  3752. else {
  3753. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3754. image.src = url;
  3755. }
  3756. };
  3757. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3758. var _this = this;
  3759. var updateVersion = function (event) {
  3760. // the version is not yet in the DB or we need to update it
  3761. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3762. };
  3763. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3764. };
  3765. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3766. var _this = this;
  3767. if (this.isSupported) {
  3768. var version;
  3769. try {
  3770. var transaction = this.db.transaction(["versions"]);
  3771. transaction.oncomplete = function (event) {
  3772. if (version) {
  3773. // If the version in the JSON file is > than the version in DB
  3774. if (_this.manifestVersionFound > version.data) {
  3775. _this.mustUpdateRessources = true;
  3776. updateInDBCallback();
  3777. }
  3778. else {
  3779. callback(version.data);
  3780. }
  3781. }
  3782. else {
  3783. _this.mustUpdateRessources = true;
  3784. updateInDBCallback();
  3785. }
  3786. };
  3787. transaction.onabort = function (event) {
  3788. callback(-1);
  3789. };
  3790. var getRequest = transaction.objectStore("versions").get(url);
  3791. getRequest.onsuccess = function (event) {
  3792. version = (event.target).result;
  3793. };
  3794. getRequest.onerror = function (event) {
  3795. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3796. callback(-1);
  3797. };
  3798. }
  3799. catch (ex) {
  3800. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3801. callback(-1);
  3802. }
  3803. }
  3804. else {
  3805. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3806. callback(-1);
  3807. }
  3808. };
  3809. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3810. var _this = this;
  3811. if (this.isSupported && !this.hasReachedQuota) {
  3812. try {
  3813. // Open a transaction to the database
  3814. var transaction = this.db.transaction(["versions"], "readwrite");
  3815. // the transaction could abort because of a QuotaExceededError error
  3816. transaction.onabort = function (event) {
  3817. try {
  3818. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3819. _this.hasReachedQuota = true;
  3820. }
  3821. }
  3822. catch (ex) { }
  3823. callback(-1);
  3824. };
  3825. transaction.oncomplete = function (event) {
  3826. callback(_this.manifestVersionFound);
  3827. };
  3828. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3829. // Put the scene into the database
  3830. var addRequest = transaction.objectStore("versions").put(newVersion);
  3831. addRequest.onsuccess = function (event) {
  3832. };
  3833. addRequest.onerror = function (event) {
  3834. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3835. };
  3836. }
  3837. catch (ex) {
  3838. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3839. callback(-1);
  3840. }
  3841. }
  3842. else {
  3843. callback(-1);
  3844. }
  3845. };
  3846. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3847. var _this = this;
  3848. var completeUrl = Database.ReturnFullUrlLocation(url);
  3849. var saveAndLoadFile = function (event) {
  3850. // the scene is not yet in the DB, let's try to save it
  3851. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3852. };
  3853. this._checkVersionFromDB(completeUrl, function (version) {
  3854. if (version !== -1) {
  3855. if (!_this.mustUpdateRessources) {
  3856. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3857. }
  3858. else {
  3859. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3860. }
  3861. }
  3862. else {
  3863. errorCallback();
  3864. }
  3865. });
  3866. };
  3867. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3868. if (this.isSupported) {
  3869. var targetStore;
  3870. if (url.indexOf(".babylon") !== -1) {
  3871. targetStore = "scenes";
  3872. }
  3873. else {
  3874. targetStore = "textures";
  3875. }
  3876. var file;
  3877. var transaction = this.db.transaction([targetStore]);
  3878. transaction.oncomplete = function (event) {
  3879. if (file) {
  3880. callback(file.data);
  3881. }
  3882. else {
  3883. notInDBCallback();
  3884. }
  3885. };
  3886. transaction.onabort = function (event) {
  3887. notInDBCallback();
  3888. };
  3889. var getRequest = transaction.objectStore(targetStore).get(url);
  3890. getRequest.onsuccess = function (event) {
  3891. file = (event.target).result;
  3892. };
  3893. getRequest.onerror = function (event) {
  3894. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3895. notInDBCallback();
  3896. };
  3897. }
  3898. else {
  3899. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3900. callback();
  3901. }
  3902. };
  3903. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3904. var _this = this;
  3905. if (this.isSupported) {
  3906. var targetStore;
  3907. if (url.indexOf(".babylon") !== -1) {
  3908. targetStore = "scenes";
  3909. }
  3910. else {
  3911. targetStore = "textures";
  3912. }
  3913. // Create XHR
  3914. var xhr = new XMLHttpRequest(), fileData;
  3915. xhr.open("GET", url, true);
  3916. if (useArrayBuffer) {
  3917. xhr.responseType = "arraybuffer";
  3918. }
  3919. xhr.onprogress = progressCallback;
  3920. xhr.addEventListener("load", function () {
  3921. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3922. // Blob as response (XHR2)
  3923. //fileData = xhr.responseText;
  3924. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3925. if (!_this.hasReachedQuota) {
  3926. // Open a transaction to the database
  3927. var transaction = _this.db.transaction([targetStore], "readwrite");
  3928. // the transaction could abort because of a QuotaExceededError error
  3929. transaction.onabort = function (event) {
  3930. try {
  3931. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3932. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3933. this.hasReachedQuota = true;
  3934. }
  3935. }
  3936. catch (ex) { }
  3937. callback(fileData);
  3938. };
  3939. transaction.oncomplete = function (event) {
  3940. callback(fileData);
  3941. };
  3942. var newFile;
  3943. if (targetStore === "scenes") {
  3944. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3945. }
  3946. else {
  3947. newFile = { textureUrl: url, data: fileData };
  3948. }
  3949. try {
  3950. // Put the scene into the database
  3951. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3952. addRequest.onsuccess = function (event) {
  3953. };
  3954. addRequest.onerror = function (event) {
  3955. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3956. };
  3957. }
  3958. catch (ex) {
  3959. callback(fileData);
  3960. }
  3961. }
  3962. else {
  3963. callback(fileData);
  3964. }
  3965. }
  3966. else {
  3967. callback();
  3968. }
  3969. }, false);
  3970. xhr.addEventListener("error", function (event) {
  3971. BABYLON.Tools.Error("error on XHR request.");
  3972. callback();
  3973. }, false);
  3974. xhr.send();
  3975. }
  3976. else {
  3977. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3978. callback();
  3979. }
  3980. };
  3981. Database.IsUASupportingBlobStorage = true;
  3982. Database.IDBStorageEnabled = true;
  3983. Database.parseURL = function (url) {
  3984. var a = document.createElement('a');
  3985. a.href = url;
  3986. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3987. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3988. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3989. return absLocation;
  3990. };
  3991. Database.ReturnFullUrlLocation = function (url) {
  3992. if (url.indexOf("http:/") === -1) {
  3993. return (Database.parseURL(window.location.href) + url);
  3994. }
  3995. else {
  3996. return url;
  3997. }
  3998. };
  3999. return Database;
  4000. })();
  4001. BABYLON.Database = Database;
  4002. })(BABYLON || (BABYLON = {}));
  4003. var BABYLON;
  4004. (function (BABYLON) {
  4005. var Internals;
  4006. (function (Internals) {
  4007. /*
  4008. * Based on jsTGALoader - Javascript loader for TGA file
  4009. * By Vincent Thibault
  4010. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4011. */
  4012. var TGATools = (function () {
  4013. function TGATools() {
  4014. }
  4015. TGATools.GetTGAHeader = function (data) {
  4016. var offset = 0;
  4017. var header = {
  4018. id_length: data[offset++],
  4019. colormap_type: data[offset++],
  4020. image_type: data[offset++],
  4021. colormap_index: data[offset++] | data[offset++] << 8,
  4022. colormap_length: data[offset++] | data[offset++] << 8,
  4023. colormap_size: data[offset++],
  4024. origin: [
  4025. data[offset++] | data[offset++] << 8,
  4026. data[offset++] | data[offset++] << 8
  4027. ],
  4028. width: data[offset++] | data[offset++] << 8,
  4029. height: data[offset++] | data[offset++] << 8,
  4030. pixel_size: data[offset++],
  4031. flags: data[offset++]
  4032. };
  4033. return header;
  4034. };
  4035. TGATools.UploadContent = function (gl, data) {
  4036. // Not enough data to contain header ?
  4037. if (data.length < 19) {
  4038. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4039. return;
  4040. }
  4041. // Read Header
  4042. var offset = 18;
  4043. var header = TGATools.GetTGAHeader(data);
  4044. // Assume it's a valid Targa file.
  4045. if (header.id_length + offset > data.length) {
  4046. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4047. return;
  4048. }
  4049. // Skip not needed data
  4050. offset += header.id_length;
  4051. var use_rle = false;
  4052. var use_pal = false;
  4053. var use_rgb = false;
  4054. var use_grey = false;
  4055. // Get some informations.
  4056. switch (header.image_type) {
  4057. case TGATools._TYPE_RLE_INDEXED:
  4058. use_rle = true;
  4059. case TGATools._TYPE_INDEXED:
  4060. use_pal = true;
  4061. break;
  4062. case TGATools._TYPE_RLE_RGB:
  4063. use_rle = true;
  4064. case TGATools._TYPE_RGB:
  4065. use_rgb = true;
  4066. break;
  4067. case TGATools._TYPE_RLE_GREY:
  4068. use_rle = true;
  4069. case TGATools._TYPE_GREY:
  4070. use_grey = true;
  4071. break;
  4072. }
  4073. var pixel_data;
  4074. var numAlphaBits = header.flags & 0xf;
  4075. var pixel_size = header.pixel_size >> 3;
  4076. var pixel_total = header.width * header.height * pixel_size;
  4077. // Read palettes
  4078. var palettes;
  4079. if (use_pal) {
  4080. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4081. }
  4082. // Read LRE
  4083. if (use_rle) {
  4084. pixel_data = new Uint8Array(pixel_total);
  4085. var c, count, i;
  4086. var localOffset = 0;
  4087. var pixels = new Uint8Array(pixel_size);
  4088. while (offset < pixel_total && localOffset < pixel_total) {
  4089. c = data[offset++];
  4090. count = (c & 0x7f) + 1;
  4091. // RLE pixels
  4092. if (c & 0x80) {
  4093. // Bind pixel tmp array
  4094. for (i = 0; i < pixel_size; ++i) {
  4095. pixels[i] = data[offset++];
  4096. }
  4097. // Copy pixel array
  4098. for (i = 0; i < count; ++i) {
  4099. pixel_data.set(pixels, localOffset + i * pixel_size);
  4100. }
  4101. localOffset += pixel_size * count;
  4102. }
  4103. else {
  4104. count *= pixel_size;
  4105. for (i = 0; i < count; ++i) {
  4106. pixel_data[localOffset + i] = data[offset++];
  4107. }
  4108. localOffset += count;
  4109. }
  4110. }
  4111. }
  4112. else {
  4113. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4114. }
  4115. // Load to texture
  4116. var x_start, y_start, x_step, y_step, y_end, x_end;
  4117. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4118. default:
  4119. case TGATools._ORIGIN_UL:
  4120. x_start = 0;
  4121. x_step = 1;
  4122. x_end = header.width;
  4123. y_start = 0;
  4124. y_step = 1;
  4125. y_end = header.height;
  4126. break;
  4127. case TGATools._ORIGIN_BL:
  4128. x_start = 0;
  4129. x_step = 1;
  4130. x_end = header.width;
  4131. y_start = header.height - 1;
  4132. y_step = -1;
  4133. y_end = -1;
  4134. break;
  4135. case TGATools._ORIGIN_UR:
  4136. x_start = header.width - 1;
  4137. x_step = -1;
  4138. x_end = -1;
  4139. y_start = 0;
  4140. y_step = 1;
  4141. y_end = header.height;
  4142. break;
  4143. case TGATools._ORIGIN_BR:
  4144. x_start = header.width - 1;
  4145. x_step = -1;
  4146. x_end = -1;
  4147. y_start = header.height - 1;
  4148. y_step = -1;
  4149. y_end = -1;
  4150. break;
  4151. }
  4152. // Load the specify method
  4153. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4154. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4155. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4156. };
  4157. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4158. var image = pixel_data, colormap = palettes;
  4159. var width = header.width, height = header.height;
  4160. var color, i = 0, x, y;
  4161. var imageData = new Uint8Array(width * height * 4);
  4162. for (y = y_start; y !== y_end; y += y_step) {
  4163. for (x = x_start; x !== x_end; x += x_step, i++) {
  4164. color = image[i];
  4165. imageData[(x + width * y) * 4 + 3] = 255;
  4166. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4167. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4168. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4169. }
  4170. }
  4171. return imageData;
  4172. };
  4173. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4174. var image = pixel_data;
  4175. var width = header.width, height = header.height;
  4176. var color, i = 0, x, y;
  4177. var imageData = new Uint8Array(width * height * 4);
  4178. for (y = y_start; y !== y_end; y += y_step) {
  4179. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4180. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4181. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4182. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4183. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4184. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4185. }
  4186. }
  4187. return imageData;
  4188. };
  4189. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4190. var image = pixel_data;
  4191. var width = header.width, height = header.height;
  4192. var i = 0, x, y;
  4193. var imageData = new Uint8Array(width * height * 4);
  4194. for (y = y_start; y !== y_end; y += y_step) {
  4195. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4196. imageData[(x + width * y) * 4 + 3] = 255;
  4197. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4198. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4199. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4200. }
  4201. }
  4202. return imageData;
  4203. };
  4204. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4205. var image = pixel_data;
  4206. var width = header.width, height = header.height;
  4207. var i = 0, x, y;
  4208. var imageData = new Uint8Array(width * height * 4);
  4209. for (y = y_start; y !== y_end; y += y_step) {
  4210. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4211. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4212. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4213. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4214. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4215. }
  4216. }
  4217. return imageData;
  4218. };
  4219. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4220. var image = pixel_data;
  4221. var width = header.width, height = header.height;
  4222. var color, i = 0, x, y;
  4223. var imageData = new Uint8Array(width * height * 4);
  4224. for (y = y_start; y !== y_end; y += y_step) {
  4225. for (x = x_start; x !== x_end; x += x_step, i++) {
  4226. color = image[i];
  4227. imageData[(x + width * y) * 4 + 0] = color;
  4228. imageData[(x + width * y) * 4 + 1] = color;
  4229. imageData[(x + width * y) * 4 + 2] = color;
  4230. imageData[(x + width * y) * 4 + 3] = 255;
  4231. }
  4232. }
  4233. return imageData;
  4234. };
  4235. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4236. var image = pixel_data;
  4237. var width = header.width, height = header.height;
  4238. var i = 0, x, y;
  4239. var imageData = new Uint8Array(width * height * 4);
  4240. for (y = y_start; y !== y_end; y += y_step) {
  4241. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4242. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4243. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4244. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4245. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4246. }
  4247. }
  4248. return imageData;
  4249. };
  4250. TGATools._TYPE_NO_DATA = 0;
  4251. TGATools._TYPE_INDEXED = 1;
  4252. TGATools._TYPE_RGB = 2;
  4253. TGATools._TYPE_GREY = 3;
  4254. TGATools._TYPE_RLE_INDEXED = 9;
  4255. TGATools._TYPE_RLE_RGB = 10;
  4256. TGATools._TYPE_RLE_GREY = 11;
  4257. TGATools._ORIGIN_MASK = 0x30;
  4258. TGATools._ORIGIN_SHIFT = 0x04;
  4259. TGATools._ORIGIN_BL = 0x00;
  4260. TGATools._ORIGIN_BR = 0x01;
  4261. TGATools._ORIGIN_UL = 0x02;
  4262. TGATools._ORIGIN_UR = 0x03;
  4263. return TGATools;
  4264. })();
  4265. Internals.TGATools = TGATools;
  4266. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4267. })(BABYLON || (BABYLON = {}));
  4268. var BABYLON;
  4269. (function (BABYLON) {
  4270. var SmartArray = (function () {
  4271. function SmartArray(capacity) {
  4272. this.length = 0;
  4273. this._duplicateId = 0;
  4274. this.data = new Array(capacity);
  4275. this._id = SmartArray._GlobalId++;
  4276. }
  4277. SmartArray.prototype.push = function (value) {
  4278. this.data[this.length++] = value;
  4279. if (this.length > this.data.length) {
  4280. this.data.length *= 2;
  4281. }
  4282. if (!value.__smartArrayFlags) {
  4283. value.__smartArrayFlags = {};
  4284. }
  4285. value.__smartArrayFlags[this._id] = this._duplicateId;
  4286. };
  4287. SmartArray.prototype.pushNoDuplicate = function (value) {
  4288. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4289. return false;
  4290. }
  4291. this.push(value);
  4292. return true;
  4293. };
  4294. SmartArray.prototype.sort = function (compareFn) {
  4295. this.data.sort(compareFn);
  4296. };
  4297. SmartArray.prototype.reset = function () {
  4298. this.length = 0;
  4299. this._duplicateId++;
  4300. };
  4301. SmartArray.prototype.concat = function (array) {
  4302. if (array.length === 0) {
  4303. return;
  4304. }
  4305. if (this.length + array.length > this.data.length) {
  4306. this.data.length = (this.length + array.length) * 2;
  4307. }
  4308. for (var index = 0; index < array.length; index++) {
  4309. this.data[this.length++] = (array.data || array)[index];
  4310. }
  4311. };
  4312. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4313. if (array.length === 0) {
  4314. return;
  4315. }
  4316. if (this.length + array.length > this.data.length) {
  4317. this.data.length = (this.length + array.length) * 2;
  4318. }
  4319. for (var index = 0; index < array.length; index++) {
  4320. var item = (array.data || array)[index];
  4321. this.pushNoDuplicate(item);
  4322. }
  4323. };
  4324. SmartArray.prototype.indexOf = function (value) {
  4325. var position = this.data.indexOf(value);
  4326. if (position >= this.length) {
  4327. return -1;
  4328. }
  4329. return position;
  4330. };
  4331. // Statics
  4332. SmartArray._GlobalId = 0;
  4333. return SmartArray;
  4334. })();
  4335. BABYLON.SmartArray = SmartArray;
  4336. })(BABYLON || (BABYLON = {}));
  4337. var BABYLON;
  4338. (function (BABYLON) {
  4339. /**
  4340. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4341. * The underlying implementation relies on an associative array to ensure the best performances.
  4342. * The value can be anything including 'null' but except 'undefined'
  4343. */
  4344. var StringDictionary = (function () {
  4345. function StringDictionary() {
  4346. this._count = 0;
  4347. this._data = {};
  4348. }
  4349. /**
  4350. * Get a value based from its key
  4351. * @param key the given key to get the matching value from
  4352. * @return the value if found, otherwise undefined is returned
  4353. */
  4354. StringDictionary.prototype.get = function (key) {
  4355. var val = this._data[key];
  4356. if (val !== undefined) {
  4357. return val;
  4358. }
  4359. return undefined;
  4360. };
  4361. /**
  4362. * Get a value from its key or add it if it doesn't exist.
  4363. * This method will ensure you that a given key/data will be present in the dictionary.
  4364. * @param key the given key to get the matching value from
  4365. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4366. * The factory will only be invoked if there's no data for the given key.
  4367. * @return the value corresponding to the key.
  4368. */
  4369. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4370. var val = this.get(key);
  4371. if (val !== undefined) {
  4372. return val;
  4373. }
  4374. val = factory(key);
  4375. if (val) {
  4376. this.add(key, val);
  4377. }
  4378. return val;
  4379. };
  4380. /**
  4381. * Get a value from its key if present in the dictionary otherwise add it
  4382. * @param key the key to get the value from
  4383. * @param val if there's no such key/value pair in the dictionary add it with this value
  4384. * @return the value corresponding to the key
  4385. */
  4386. StringDictionary.prototype.getOrAdd = function (key, val) {
  4387. var curVal = this.get(key);
  4388. if (curVal !== undefined) {
  4389. return curVal;
  4390. }
  4391. this.add(key, val);
  4392. return val;
  4393. };
  4394. /**
  4395. * Check if there's a given key in the dictionary
  4396. * @param key the key to check for
  4397. * @return true if the key is present, false otherwise
  4398. */
  4399. StringDictionary.prototype.contains = function (key) {
  4400. return this._data[key] !== undefined;
  4401. };
  4402. /**
  4403. * Add a new key and its corresponding value
  4404. * @param key the key to add
  4405. * @param value the value corresponding to the key
  4406. * @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
  4407. */
  4408. StringDictionary.prototype.add = function (key, value) {
  4409. if (this._data[key] !== undefined) {
  4410. return false;
  4411. }
  4412. this._data[key] = value;
  4413. ++this._count;
  4414. return true;
  4415. };
  4416. StringDictionary.prototype.set = function (key, value) {
  4417. if (this._data[key] === undefined) {
  4418. return false;
  4419. }
  4420. this._data[key] = value;
  4421. return true;
  4422. };
  4423. /**
  4424. * Remove a key/value from the dictionary.
  4425. * @param key the key to remove
  4426. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4427. */
  4428. StringDictionary.prototype.remove = function (key) {
  4429. if (this.contains(key)) {
  4430. delete this._data[key];
  4431. --this._count;
  4432. return true;
  4433. }
  4434. return false;
  4435. };
  4436. /**
  4437. * Clear the whole content of the dictionary
  4438. */
  4439. StringDictionary.prototype.clear = function () {
  4440. this._data = {};
  4441. this._count = 0;
  4442. };
  4443. Object.defineProperty(StringDictionary.prototype, "count", {
  4444. get: function () {
  4445. return this._count;
  4446. },
  4447. enumerable: true,
  4448. configurable: true
  4449. });
  4450. /**
  4451. * Execute a callback on each key/val of the dictionary.
  4452. * Note that you can remove any element in this dictionary in the callback implementation
  4453. * @param callback the callback to execute on a given key/value pair
  4454. */
  4455. StringDictionary.prototype.forEach = function (callback) {
  4456. for (var cur in this._data) {
  4457. var val = this._data[cur];
  4458. callback(cur, val);
  4459. }
  4460. };
  4461. /**
  4462. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4463. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4464. * Note that you can remove any element in this dictionary in the callback implementation
  4465. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4466. */
  4467. StringDictionary.prototype.first = function (callback) {
  4468. for (var cur in this._data) {
  4469. var val = this._data[cur];
  4470. var res = callback(cur, val);
  4471. if (res) {
  4472. return res;
  4473. }
  4474. }
  4475. return null;
  4476. };
  4477. return StringDictionary;
  4478. })();
  4479. BABYLON.StringDictionary = StringDictionary;
  4480. })(BABYLON || (BABYLON = {}));
  4481. var BABYLON;
  4482. (function (BABYLON) {
  4483. // Screenshots
  4484. var screenshotCanvas;
  4485. var cloneValue = function (source, destinationObject) {
  4486. if (!source)
  4487. return null;
  4488. if (source instanceof BABYLON.Mesh) {
  4489. return null;
  4490. }
  4491. if (source instanceof BABYLON.SubMesh) {
  4492. return source.clone(destinationObject);
  4493. }
  4494. else if (source.clone) {
  4495. return source.clone();
  4496. }
  4497. return null;
  4498. };
  4499. var Tools = (function () {
  4500. function Tools() {
  4501. }
  4502. Tools.Instantiate = function (className) {
  4503. var arr = className.split(".");
  4504. var fn = (window || this);
  4505. for (var i = 0, len = arr.length; i < len; i++) {
  4506. fn = fn[arr[i]];
  4507. }
  4508. if (typeof fn !== "function") {
  4509. return null;
  4510. }
  4511. return fn;
  4512. };
  4513. Tools.SetImmediate = function (action) {
  4514. if (window.setImmediate) {
  4515. window.setImmediate(action);
  4516. }
  4517. else {
  4518. setTimeout(action, 1);
  4519. }
  4520. };
  4521. Tools.IsExponentOfTwo = function (value) {
  4522. var count = 1;
  4523. do {
  4524. count *= 2;
  4525. } while (count < value);
  4526. return count === value;
  4527. };
  4528. Tools.GetExponentOfTwo = function (value, max) {
  4529. var count = 1;
  4530. do {
  4531. count *= 2;
  4532. } while (count < value);
  4533. if (count > max)
  4534. count = max;
  4535. return count;
  4536. };
  4537. Tools.GetFilename = function (path) {
  4538. var index = path.lastIndexOf("/");
  4539. if (index < 0)
  4540. return path;
  4541. return path.substring(index + 1);
  4542. };
  4543. Tools.GetDOMTextContent = function (element) {
  4544. var result = "";
  4545. var child = element.firstChild;
  4546. while (child) {
  4547. if (child.nodeType === 3) {
  4548. result += child.textContent;
  4549. }
  4550. child = child.nextSibling;
  4551. }
  4552. return result;
  4553. };
  4554. Tools.ToDegrees = function (angle) {
  4555. return angle * 180 / Math.PI;
  4556. };
  4557. Tools.ToRadians = function (angle) {
  4558. return angle * Math.PI / 180;
  4559. };
  4560. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4561. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4562. var output = "";
  4563. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4564. var i = 0;
  4565. var bytes = new Uint8Array(buffer);
  4566. while (i < bytes.length) {
  4567. chr1 = bytes[i++];
  4568. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4569. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4570. enc1 = chr1 >> 2;
  4571. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4572. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4573. enc4 = chr3 & 63;
  4574. if (isNaN(chr2)) {
  4575. enc3 = enc4 = 64;
  4576. }
  4577. else if (isNaN(chr3)) {
  4578. enc4 = 64;
  4579. }
  4580. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4581. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4582. }
  4583. return "data:image/png;base64," + output;
  4584. };
  4585. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4586. if (bias === void 0) { bias = null; }
  4587. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4588. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4589. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4590. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 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.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4608. if (bias === void 0) { bias = null; }
  4609. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4610. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4611. if (!stride) {
  4612. stride = 3;
  4613. }
  4614. for (var index = start; index < start + count; index++) {
  4615. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4616. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4617. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4618. }
  4619. if (bias) {
  4620. minimum.x -= minimum.x * bias.x + bias.y;
  4621. minimum.y -= minimum.y * bias.x + bias.y;
  4622. minimum.z -= minimum.z * bias.x + bias.y;
  4623. maximum.x += maximum.x * bias.x + bias.y;
  4624. maximum.y += maximum.y * bias.x + bias.y;
  4625. maximum.z += maximum.z * bias.x + bias.y;
  4626. }
  4627. return {
  4628. minimum: minimum,
  4629. maximum: maximum
  4630. };
  4631. };
  4632. Tools.Vector2ArrayFeeder = function (array) {
  4633. return function (index) {
  4634. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4635. var length = isFloatArray ? array.length / 2 : array.length;
  4636. if (index >= length) {
  4637. return null;
  4638. }
  4639. if (isFloatArray) {
  4640. var fa = array;
  4641. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4642. }
  4643. var a = array;
  4644. return a[index];
  4645. };
  4646. };
  4647. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4648. if (bias === void 0) { bias = null; }
  4649. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4650. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4651. var i = 0;
  4652. var cur = feeder(i++);
  4653. while (cur) {
  4654. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4655. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4656. cur = feeder(i++);
  4657. }
  4658. if (bias) {
  4659. minimum.x -= minimum.x * bias.x + bias.y;
  4660. minimum.y -= minimum.y * bias.x + bias.y;
  4661. maximum.x += maximum.x * bias.x + bias.y;
  4662. maximum.y += maximum.y * bias.x + bias.y;
  4663. }
  4664. return {
  4665. minimum: minimum,
  4666. maximum: maximum
  4667. };
  4668. };
  4669. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4670. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4671. return undefined;
  4672. return Array.isArray(obj) ? obj : [obj];
  4673. };
  4674. // Misc.
  4675. Tools.GetPointerPrefix = function () {
  4676. var eventPrefix = "pointer";
  4677. // Check if pointer events are supported
  4678. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4679. eventPrefix = "mouse";
  4680. }
  4681. return eventPrefix;
  4682. };
  4683. /**
  4684. * @param func - the function to be called
  4685. * @param requester - the object that will request the next frame. Falls back to window.
  4686. */
  4687. Tools.QueueNewFrame = function (func, requester) {
  4688. if (requester === void 0) { requester = window; }
  4689. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4690. /*if(requester.isPresenting) {
  4691. return;
  4692. } else*/ if (requester.requestAnimationFrame)
  4693. requester.requestAnimationFrame(func);
  4694. else if (requester.msRequestAnimationFrame)
  4695. requester.msRequestAnimationFrame(func);
  4696. else if (requester.webkitRequestAnimationFrame)
  4697. requester.webkitRequestAnimationFrame(func);
  4698. else if (requester.mozRequestAnimationFrame)
  4699. requester.mozRequestAnimationFrame(func);
  4700. else if (requester.oRequestAnimationFrame)
  4701. requester.oRequestAnimationFrame(func);
  4702. else {
  4703. window.setTimeout(func, 16);
  4704. }
  4705. };
  4706. Tools.RequestFullscreen = function (element) {
  4707. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4708. if (!requestFunction)
  4709. return;
  4710. requestFunction.call(element);
  4711. };
  4712. Tools.ExitFullscreen = function () {
  4713. if (document.exitFullscreen) {
  4714. document.exitFullscreen();
  4715. }
  4716. else if (document.mozCancelFullScreen) {
  4717. document.mozCancelFullScreen();
  4718. }
  4719. else if (document.webkitCancelFullScreen) {
  4720. document.webkitCancelFullScreen();
  4721. }
  4722. else if (document.msCancelFullScreen) {
  4723. document.msCancelFullScreen();
  4724. }
  4725. };
  4726. Tools.SetCorsBehavior = function (url, img) {
  4727. if (Tools.CorsBehavior) {
  4728. switch (typeof (Tools.CorsBehavior)) {
  4729. case "function":
  4730. var result = Tools.CorsBehavior(url);
  4731. if (result) {
  4732. return result;
  4733. }
  4734. break;
  4735. case "string":
  4736. default:
  4737. img.crossOrigin = Tools.CorsBehavior;
  4738. break;
  4739. }
  4740. }
  4741. };
  4742. // External files
  4743. Tools.CleanUrl = function (url) {
  4744. url = url.replace(/#/mg, "%23");
  4745. return url;
  4746. };
  4747. Tools.LoadImage = function (url, onload, onerror, database) {
  4748. if (url instanceof ArrayBuffer) {
  4749. url = Tools.EncodeArrayBufferTobase64(url);
  4750. }
  4751. url = Tools.CleanUrl(url);
  4752. var img = new Image();
  4753. if (url.substr(0, 5) !== "data:") {
  4754. Tools.SetCorsBehavior(url, img);
  4755. }
  4756. img.onload = function () {
  4757. onload(img);
  4758. };
  4759. img.onerror = function (err) {
  4760. Tools.Error("Error while trying to load texture: " + url);
  4761. if (Tools.UseFallbackTexture) {
  4762. 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";
  4763. onload(img);
  4764. }
  4765. else {
  4766. onerror();
  4767. }
  4768. };
  4769. var noIndexedDB = function () {
  4770. img.src = url;
  4771. };
  4772. var loadFromIndexedDB = function () {
  4773. database.loadImageFromDB(url, img);
  4774. };
  4775. //ANY database to do!
  4776. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4777. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4778. }
  4779. else {
  4780. if (url.indexOf("file:") === -1) {
  4781. noIndexedDB();
  4782. }
  4783. else {
  4784. try {
  4785. var textureName = url.substring(5).toLowerCase();
  4786. var blobURL;
  4787. try {
  4788. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4789. }
  4790. catch (ex) {
  4791. // Chrome doesn't support oneTimeOnly parameter
  4792. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4793. }
  4794. img.src = blobURL;
  4795. }
  4796. catch (e) {
  4797. img.src = null;
  4798. }
  4799. }
  4800. }
  4801. return img;
  4802. };
  4803. //ANY
  4804. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4805. url = Tools.CleanUrl(url);
  4806. var noIndexedDB = function () {
  4807. var request = new XMLHttpRequest();
  4808. var loadUrl = Tools.BaseUrl + url;
  4809. request.open('GET', loadUrl, true);
  4810. if (useArrayBuffer) {
  4811. request.responseType = "arraybuffer";
  4812. }
  4813. request.onprogress = progressCallBack;
  4814. request.onreadystatechange = function () {
  4815. if (request.readyState === 4) {
  4816. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4817. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4818. callback(!useArrayBuffer ? request.responseText : request.response);
  4819. }
  4820. else {
  4821. if (onError) {
  4822. onError();
  4823. }
  4824. else {
  4825. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4826. }
  4827. }
  4828. }
  4829. };
  4830. request.send(null);
  4831. };
  4832. var loadFromIndexedDB = function () {
  4833. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4834. };
  4835. if (url.indexOf("file:") !== -1) {
  4836. var fileName = url.substring(5).toLowerCase();
  4837. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4838. }
  4839. else {
  4840. // Caching all files
  4841. if (database && database.enableSceneOffline) {
  4842. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4843. }
  4844. else {
  4845. noIndexedDB();
  4846. }
  4847. }
  4848. };
  4849. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4850. var reader = new FileReader();
  4851. reader.onload = function (e) {
  4852. //target doesn't have result from ts 1.3
  4853. callback(e.target['result']);
  4854. };
  4855. reader.onprogress = progressCallback;
  4856. reader.readAsDataURL(fileToLoad);
  4857. };
  4858. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4859. var reader = new FileReader();
  4860. reader.onerror = function (e) {
  4861. Tools.Log("Error while reading file: " + fileToLoad.name);
  4862. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4863. };
  4864. reader.onload = function (e) {
  4865. //target doesn't have result from ts 1.3
  4866. callback(e.target['result']);
  4867. };
  4868. reader.onprogress = progressCallBack;
  4869. if (!useArrayBuffer) {
  4870. // Asynchronous read
  4871. reader.readAsText(fileToLoad);
  4872. }
  4873. else {
  4874. reader.readAsArrayBuffer(fileToLoad);
  4875. }
  4876. };
  4877. //returns a downloadable url to a file content.
  4878. Tools.FileAsURL = function (content) {
  4879. var fileBlob = new Blob([content]);
  4880. var url = window.URL || window.webkitURL;
  4881. var link = url.createObjectURL(fileBlob);
  4882. return link;
  4883. };
  4884. // Misc.
  4885. Tools.Format = function (value, decimals) {
  4886. if (decimals === void 0) { decimals = 2; }
  4887. return value.toFixed(decimals);
  4888. };
  4889. Tools.CheckExtends = function (v, min, max) {
  4890. if (v.x < min.x)
  4891. min.x = v.x;
  4892. if (v.y < min.y)
  4893. min.y = v.y;
  4894. if (v.z < min.z)
  4895. min.z = v.z;
  4896. if (v.x > max.x)
  4897. max.x = v.x;
  4898. if (v.y > max.y)
  4899. max.y = v.y;
  4900. if (v.z > max.z)
  4901. max.z = v.z;
  4902. };
  4903. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4904. for (var prop in source) {
  4905. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4906. continue;
  4907. }
  4908. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4909. continue;
  4910. }
  4911. var sourceValue = source[prop];
  4912. var typeOfSourceValue = typeof sourceValue;
  4913. if (typeOfSourceValue === "function") {
  4914. continue;
  4915. }
  4916. if (typeOfSourceValue === "object") {
  4917. if (sourceValue instanceof Array) {
  4918. destination[prop] = [];
  4919. if (sourceValue.length > 0) {
  4920. if (typeof sourceValue[0] == "object") {
  4921. for (var index = 0; index < sourceValue.length; index++) {
  4922. var clonedValue = cloneValue(sourceValue[index], destination);
  4923. if (destination[prop].indexOf(clonedValue) === -1) {
  4924. destination[prop].push(clonedValue);
  4925. }
  4926. }
  4927. }
  4928. else {
  4929. destination[prop] = sourceValue.slice(0);
  4930. }
  4931. }
  4932. }
  4933. else {
  4934. destination[prop] = cloneValue(sourceValue, destination);
  4935. }
  4936. }
  4937. else {
  4938. destination[prop] = sourceValue;
  4939. }
  4940. }
  4941. };
  4942. Tools.IsEmpty = function (obj) {
  4943. for (var i in obj) {
  4944. return false;
  4945. }
  4946. return true;
  4947. };
  4948. Tools.RegisterTopRootEvents = function (events) {
  4949. for (var index = 0; index < events.length; index++) {
  4950. var event = events[index];
  4951. window.addEventListener(event.name, event.handler, false);
  4952. try {
  4953. if (window.parent) {
  4954. window.parent.addEventListener(event.name, event.handler, false);
  4955. }
  4956. }
  4957. catch (e) {
  4958. }
  4959. }
  4960. };
  4961. Tools.UnregisterTopRootEvents = function (events) {
  4962. for (var index = 0; index < events.length; index++) {
  4963. var event = events[index];
  4964. window.removeEventListener(event.name, event.handler);
  4965. try {
  4966. if (window.parent) {
  4967. window.parent.removeEventListener(event.name, event.handler);
  4968. }
  4969. }
  4970. catch (e) {
  4971. }
  4972. }
  4973. };
  4974. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  4975. if (mimeType === void 0) { mimeType = "image/png"; }
  4976. // Read the contents of the framebuffer
  4977. var numberOfChannelsByLine = width * 4;
  4978. var halfHeight = height / 2;
  4979. //Reading datas from WebGL
  4980. var data = engine.readPixels(0, 0, width, height);
  4981. //To flip image on Y axis.
  4982. for (var i = 0; i < halfHeight; i++) {
  4983. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4984. var currentCell = j + i * numberOfChannelsByLine;
  4985. var targetLine = height - i - 1;
  4986. var targetCell = j + targetLine * numberOfChannelsByLine;
  4987. var temp = data[currentCell];
  4988. data[currentCell] = data[targetCell];
  4989. data[targetCell] = temp;
  4990. }
  4991. }
  4992. // Create a 2D canvas to store the result
  4993. if (!screenshotCanvas) {
  4994. screenshotCanvas = document.createElement('canvas');
  4995. }
  4996. screenshotCanvas.width = width;
  4997. screenshotCanvas.height = height;
  4998. var context = screenshotCanvas.getContext('2d');
  4999. // Copy the pixels to a 2D canvas
  5000. var imageData = context.createImageData(width, height);
  5001. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  5002. var castData = imageData.data;
  5003. castData.set(data);
  5004. context.putImageData(imageData, 0, 0);
  5005. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5006. if (successCallback) {
  5007. successCallback(base64Image);
  5008. }
  5009. else {
  5010. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5011. if (("download" in document.createElement("a"))) {
  5012. var a = window.document.createElement("a");
  5013. a.href = base64Image;
  5014. var date = new Date();
  5015. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5016. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5017. window.document.body.appendChild(a);
  5018. a.addEventListener("click", function () {
  5019. a.parentElement.removeChild(a);
  5020. });
  5021. a.click();
  5022. }
  5023. else {
  5024. var newWindow = window.open("");
  5025. var img = newWindow.document.createElement("img");
  5026. img.src = base64Image;
  5027. newWindow.document.body.appendChild(img);
  5028. }
  5029. }
  5030. };
  5031. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5032. if (mimeType === void 0) { mimeType = "image/png"; }
  5033. var width;
  5034. var height;
  5035. //If a precision value is specified
  5036. if (size.precision) {
  5037. width = Math.round(engine.getRenderWidth() * size.precision);
  5038. height = Math.round(width / engine.getAspectRatio(camera));
  5039. size = { width: width, height: height };
  5040. }
  5041. else if (size.width && size.height) {
  5042. width = size.width;
  5043. height = size.height;
  5044. }
  5045. else if (size.width && !size.height) {
  5046. width = size.width;
  5047. height = Math.round(width / engine.getAspectRatio(camera));
  5048. size = { width: width, height: height };
  5049. }
  5050. else if (size.height && !size.width) {
  5051. height = size.height;
  5052. width = Math.round(height * engine.getAspectRatio(camera));
  5053. size = { width: width, height: height };
  5054. }
  5055. else if (!isNaN(size)) {
  5056. height = size;
  5057. width = size;
  5058. }
  5059. else {
  5060. Tools.Error("Invalid 'size' parameter !");
  5061. return;
  5062. }
  5063. var scene = camera.getScene();
  5064. var previousCamera = null;
  5065. if (scene.activeCamera !== camera) {
  5066. previousCamera = scene.activeCamera;
  5067. scene.activeCamera = camera;
  5068. }
  5069. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5070. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5071. texture.renderList = scene.meshes;
  5072. texture.onAfterRenderObservable.add(function () {
  5073. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5074. });
  5075. scene.incrementRenderId();
  5076. scene.resetCachedMaterial();
  5077. texture.render(true);
  5078. texture.dispose();
  5079. if (previousCamera) {
  5080. scene.activeCamera = previousCamera;
  5081. }
  5082. camera.getProjectionMatrix(true); // Force cache refresh;
  5083. };
  5084. // XHR response validator for local file scenario
  5085. Tools.ValidateXHRData = function (xhr, dataType) {
  5086. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5087. if (dataType === void 0) { dataType = 7; }
  5088. try {
  5089. if (dataType & 1) {
  5090. if (xhr.responseText && xhr.responseText.length > 0) {
  5091. return true;
  5092. }
  5093. else if (dataType === 1) {
  5094. return false;
  5095. }
  5096. }
  5097. if (dataType & 2) {
  5098. // Check header width and height since there is no "TGA" magic number
  5099. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5100. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5101. return true;
  5102. }
  5103. else if (dataType === 2) {
  5104. return false;
  5105. }
  5106. }
  5107. if (dataType & 4) {
  5108. // Check for the "DDS" magic number
  5109. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5110. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5111. return true;
  5112. }
  5113. else {
  5114. return false;
  5115. }
  5116. }
  5117. }
  5118. catch (e) {
  5119. }
  5120. return false;
  5121. };
  5122. Object.defineProperty(Tools, "NoneLogLevel", {
  5123. get: function () {
  5124. return Tools._NoneLogLevel;
  5125. },
  5126. enumerable: true,
  5127. configurable: true
  5128. });
  5129. Object.defineProperty(Tools, "MessageLogLevel", {
  5130. get: function () {
  5131. return Tools._MessageLogLevel;
  5132. },
  5133. enumerable: true,
  5134. configurable: true
  5135. });
  5136. Object.defineProperty(Tools, "WarningLogLevel", {
  5137. get: function () {
  5138. return Tools._WarningLogLevel;
  5139. },
  5140. enumerable: true,
  5141. configurable: true
  5142. });
  5143. Object.defineProperty(Tools, "ErrorLogLevel", {
  5144. get: function () {
  5145. return Tools._ErrorLogLevel;
  5146. },
  5147. enumerable: true,
  5148. configurable: true
  5149. });
  5150. Object.defineProperty(Tools, "AllLogLevel", {
  5151. get: function () {
  5152. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5153. },
  5154. enumerable: true,
  5155. configurable: true
  5156. });
  5157. Tools._AddLogEntry = function (entry) {
  5158. Tools._LogCache = entry + Tools._LogCache;
  5159. if (Tools.OnNewCacheEntry) {
  5160. Tools.OnNewCacheEntry(entry);
  5161. }
  5162. };
  5163. Tools._FormatMessage = function (message) {
  5164. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5165. var date = new Date();
  5166. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5167. };
  5168. Tools._LogDisabled = function (message) {
  5169. // nothing to do
  5170. };
  5171. Tools._LogEnabled = function (message) {
  5172. var formattedMessage = Tools._FormatMessage(message);
  5173. console.log("BJS - " + formattedMessage);
  5174. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5175. Tools._AddLogEntry(entry);
  5176. };
  5177. Tools._WarnDisabled = function (message) {
  5178. // nothing to do
  5179. };
  5180. Tools._WarnEnabled = function (message) {
  5181. var formattedMessage = Tools._FormatMessage(message);
  5182. console.warn("BJS - " + formattedMessage);
  5183. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5184. Tools._AddLogEntry(entry);
  5185. };
  5186. Tools._ErrorDisabled = function (message) {
  5187. // nothing to do
  5188. };
  5189. Tools._ErrorEnabled = function (message) {
  5190. Tools.errorsCount++;
  5191. var formattedMessage = Tools._FormatMessage(message);
  5192. console.error("BJS - " + formattedMessage);
  5193. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5194. Tools._AddLogEntry(entry);
  5195. };
  5196. Object.defineProperty(Tools, "LogCache", {
  5197. get: function () {
  5198. return Tools._LogCache;
  5199. },
  5200. enumerable: true,
  5201. configurable: true
  5202. });
  5203. Tools.ClearLogCache = function () {
  5204. Tools._LogCache = "";
  5205. Tools.errorsCount = 0;
  5206. };
  5207. Object.defineProperty(Tools, "LogLevels", {
  5208. set: function (level) {
  5209. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5210. Tools.Log = Tools._LogEnabled;
  5211. }
  5212. else {
  5213. Tools.Log = Tools._LogDisabled;
  5214. }
  5215. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5216. Tools.Warn = Tools._WarnEnabled;
  5217. }
  5218. else {
  5219. Tools.Warn = Tools._WarnDisabled;
  5220. }
  5221. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5222. Tools.Error = Tools._ErrorEnabled;
  5223. }
  5224. else {
  5225. Tools.Error = Tools._ErrorDisabled;
  5226. }
  5227. },
  5228. enumerable: true,
  5229. configurable: true
  5230. });
  5231. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5232. get: function () {
  5233. return Tools._PerformanceNoneLogLevel;
  5234. },
  5235. enumerable: true,
  5236. configurable: true
  5237. });
  5238. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5239. get: function () {
  5240. return Tools._PerformanceUserMarkLogLevel;
  5241. },
  5242. enumerable: true,
  5243. configurable: true
  5244. });
  5245. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5246. get: function () {
  5247. return Tools._PerformanceConsoleLogLevel;
  5248. },
  5249. enumerable: true,
  5250. configurable: true
  5251. });
  5252. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5253. set: function (level) {
  5254. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5255. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5256. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5257. return;
  5258. }
  5259. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5260. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5261. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5262. return;
  5263. }
  5264. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5265. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5266. },
  5267. enumerable: true,
  5268. configurable: true
  5269. });
  5270. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5271. };
  5272. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5273. };
  5274. Tools._StartUserMark = function (counterName, condition) {
  5275. if (condition === void 0) { condition = true; }
  5276. if (!condition || !Tools._performance.mark) {
  5277. return;
  5278. }
  5279. Tools._performance.mark(counterName + "-Begin");
  5280. };
  5281. Tools._EndUserMark = function (counterName, condition) {
  5282. if (condition === void 0) { condition = true; }
  5283. if (!condition || !Tools._performance.mark) {
  5284. return;
  5285. }
  5286. Tools._performance.mark(counterName + "-End");
  5287. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5288. };
  5289. Tools._StartPerformanceConsole = function (counterName, condition) {
  5290. if (condition === void 0) { condition = true; }
  5291. if (!condition) {
  5292. return;
  5293. }
  5294. Tools._StartUserMark(counterName, condition);
  5295. if (console.time) {
  5296. console.time(counterName);
  5297. }
  5298. };
  5299. Tools._EndPerformanceConsole = function (counterName, condition) {
  5300. if (condition === void 0) { condition = true; }
  5301. if (!condition) {
  5302. return;
  5303. }
  5304. Tools._EndUserMark(counterName, condition);
  5305. if (console.time) {
  5306. console.timeEnd(counterName);
  5307. }
  5308. };
  5309. Object.defineProperty(Tools, "Now", {
  5310. get: function () {
  5311. if (window.performance && window.performance.now) {
  5312. return window.performance.now();
  5313. }
  5314. return new Date().getTime();
  5315. },
  5316. enumerable: true,
  5317. configurable: true
  5318. });
  5319. /**
  5320. * This method will return the name of the class used to create the instance of the given object.
  5321. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5322. * @param object the object to get the class name from
  5323. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5324. */
  5325. Tools.getClassName = function (object, isType) {
  5326. if (isType === void 0) { isType = false; }
  5327. var name = null;
  5328. if (!isType && object.getClassName) {
  5329. name = object.getClassName();
  5330. }
  5331. else {
  5332. if (object instanceof Object) {
  5333. var classObj = isType ? object : Object.getPrototypeOf(object);
  5334. name = classObj.constructor["__bjsclassName__"];
  5335. }
  5336. if (!name) {
  5337. name = typeof object;
  5338. }
  5339. }
  5340. return name;
  5341. };
  5342. Tools.first = function (array, predicate) {
  5343. for (var _i = 0; _i < array.length; _i++) {
  5344. var el = array[_i];
  5345. if (predicate(el)) {
  5346. return el;
  5347. }
  5348. }
  5349. };
  5350. /**
  5351. * 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.
  5352. * @param array
  5353. */
  5354. Tools.arrayOrStringFeeder = function (array) {
  5355. return function (index) {
  5356. if (index >= array.length) {
  5357. return null;
  5358. }
  5359. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5360. if (val && val.getHashCode) {
  5361. val = val.getHashCode();
  5362. }
  5363. if (typeof val === "string") {
  5364. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5365. }
  5366. return val;
  5367. };
  5368. };
  5369. /**
  5370. * Compute the hashCode of a stream of number
  5371. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5372. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5373. * @return the hash code computed
  5374. */
  5375. Tools.hashCodeFromStream = function (feeder) {
  5376. // Based from here: http://stackoverflow.com/a/7616484/802124
  5377. var hash = 0;
  5378. var index = 0;
  5379. var chr = feeder(index++);
  5380. while (chr != null) {
  5381. hash = ((hash << 5) - hash) + chr;
  5382. hash |= 0; // Convert to 32bit integer
  5383. chr = feeder(index++);
  5384. }
  5385. return hash;
  5386. };
  5387. Tools.BaseUrl = "";
  5388. Tools.CorsBehavior = "anonymous";
  5389. Tools.UseFallbackTexture = true;
  5390. // Logs
  5391. Tools._NoneLogLevel = 0;
  5392. Tools._MessageLogLevel = 1;
  5393. Tools._WarningLogLevel = 2;
  5394. Tools._ErrorLogLevel = 4;
  5395. Tools._LogCache = "";
  5396. Tools.errorsCount = 0;
  5397. Tools.Log = Tools._LogEnabled;
  5398. Tools.Warn = Tools._WarnEnabled;
  5399. Tools.Error = Tools._ErrorEnabled;
  5400. // Performances
  5401. Tools._PerformanceNoneLogLevel = 0;
  5402. Tools._PerformanceUserMarkLogLevel = 1;
  5403. Tools._PerformanceConsoleLogLevel = 2;
  5404. Tools._performance = window.performance;
  5405. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5406. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5407. return Tools;
  5408. })();
  5409. BABYLON.Tools = Tools;
  5410. /**
  5411. * This class is used to track a performance counter which is number based.
  5412. * The user has access to many properties which give statistics of different nature
  5413. *
  5414. * The implementer can track two kinds of Performance Counter: time and count
  5415. * 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.
  5416. * 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.
  5417. */
  5418. var PerfCounter = (function () {
  5419. function PerfCounter() {
  5420. this._startMonitoringTime = 0;
  5421. this._min = 0;
  5422. this._max = 0;
  5423. this._average = 0;
  5424. this._lastSecAverage = 0;
  5425. this._current = 0;
  5426. this._totalValueCount = 0;
  5427. this._totalAccumulated = 0;
  5428. this._lastSecAccumulated = 0;
  5429. this._lastSecTime = 0;
  5430. this._lastSecValueCount = 0;
  5431. }
  5432. Object.defineProperty(PerfCounter.prototype, "min", {
  5433. /**
  5434. * Returns the smallest value ever
  5435. */
  5436. get: function () {
  5437. return this._min;
  5438. },
  5439. enumerable: true,
  5440. configurable: true
  5441. });
  5442. Object.defineProperty(PerfCounter.prototype, "max", {
  5443. /**
  5444. * Returns the biggest value ever
  5445. */
  5446. get: function () {
  5447. return this._max;
  5448. },
  5449. enumerable: true,
  5450. configurable: true
  5451. });
  5452. Object.defineProperty(PerfCounter.prototype, "average", {
  5453. /**
  5454. * Returns the average value since the performance counter is running
  5455. */
  5456. get: function () {
  5457. return this._average;
  5458. },
  5459. enumerable: true,
  5460. configurable: true
  5461. });
  5462. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5463. /**
  5464. * Returns the average value of the last second the counter was monitored
  5465. */
  5466. get: function () {
  5467. return this._lastSecAverage;
  5468. },
  5469. enumerable: true,
  5470. configurable: true
  5471. });
  5472. Object.defineProperty(PerfCounter.prototype, "current", {
  5473. /**
  5474. * Returns the current value
  5475. */
  5476. get: function () {
  5477. return this._current;
  5478. },
  5479. enumerable: true,
  5480. configurable: true
  5481. });
  5482. Object.defineProperty(PerfCounter.prototype, "total", {
  5483. get: function () {
  5484. return this._totalAccumulated;
  5485. },
  5486. enumerable: true,
  5487. configurable: true
  5488. });
  5489. /**
  5490. * Call this method to start monitoring a new frame.
  5491. * 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.
  5492. */
  5493. PerfCounter.prototype.fetchNewFrame = function () {
  5494. this._totalValueCount++;
  5495. this._current = 0;
  5496. this._lastSecValueCount++;
  5497. };
  5498. /**
  5499. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5500. * @param newCount the count value to add to the monitored count
  5501. * @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.
  5502. */
  5503. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5504. this._current += newCount;
  5505. if (fetchResult) {
  5506. this._fetchResult();
  5507. }
  5508. };
  5509. /**
  5510. * Start monitoring this performance counter
  5511. */
  5512. PerfCounter.prototype.beginMonitoring = function () {
  5513. this._startMonitoringTime = Tools.Now;
  5514. };
  5515. /**
  5516. * Compute the time lapsed since the previous beginMonitoring() call.
  5517. * @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
  5518. */
  5519. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5520. if (newFrame === void 0) { newFrame = true; }
  5521. if (newFrame) {
  5522. this.fetchNewFrame();
  5523. }
  5524. var currentTime = Tools.Now;
  5525. this._current = currentTime - this._startMonitoringTime;
  5526. if (newFrame) {
  5527. this._fetchResult();
  5528. }
  5529. };
  5530. PerfCounter.prototype._fetchResult = function () {
  5531. this._totalAccumulated += this._current;
  5532. this._lastSecAccumulated += this._current;
  5533. // Min/Max update
  5534. this._min = Math.min(this._min, this._current);
  5535. this._max = Math.max(this._max, this._current);
  5536. this._average = this._totalAccumulated / this._totalValueCount;
  5537. // Reset last sec?
  5538. var now = Tools.Now;
  5539. if ((now - this._lastSecTime) > 1000) {
  5540. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5541. this._lastSecTime = now;
  5542. this._lastSecAccumulated = 0;
  5543. this._lastSecValueCount = 0;
  5544. }
  5545. };
  5546. return PerfCounter;
  5547. })();
  5548. BABYLON.PerfCounter = PerfCounter;
  5549. /**
  5550. * Use this className as a decorator on a given class definition to add it a name.
  5551. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5552. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5553. * @param name
  5554. */
  5555. function className(name) {
  5556. return function (target) {
  5557. target["__bjsclassName__"] = name;
  5558. };
  5559. }
  5560. BABYLON.className = className;
  5561. /**
  5562. * An implementation of a loop for asynchronous functions.
  5563. */
  5564. var AsyncLoop = (function () {
  5565. /**
  5566. * Constroctor.
  5567. * @param iterations the number of iterations.
  5568. * @param _fn the function to run each iteration
  5569. * @param _successCallback the callback that will be called upon succesful execution
  5570. * @param offset starting offset.
  5571. */
  5572. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5573. if (offset === void 0) { offset = 0; }
  5574. this.iterations = iterations;
  5575. this._fn = _fn;
  5576. this._successCallback = _successCallback;
  5577. this.index = offset - 1;
  5578. this._done = false;
  5579. }
  5580. /**
  5581. * Execute the next iteration. Must be called after the last iteration was finished.
  5582. */
  5583. AsyncLoop.prototype.executeNext = function () {
  5584. if (!this._done) {
  5585. if (this.index + 1 < this.iterations) {
  5586. ++this.index;
  5587. this._fn(this);
  5588. }
  5589. else {
  5590. this.breakLoop();
  5591. }
  5592. }
  5593. };
  5594. /**
  5595. * Break the loop and run the success callback.
  5596. */
  5597. AsyncLoop.prototype.breakLoop = function () {
  5598. this._done = true;
  5599. this._successCallback();
  5600. };
  5601. /**
  5602. * Helper function
  5603. */
  5604. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5605. if (offset === void 0) { offset = 0; }
  5606. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5607. loop.executeNext();
  5608. return loop;
  5609. };
  5610. /**
  5611. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5612. * @param iterations total number of iterations
  5613. * @param syncedIterations number of synchronous iterations in each async iteration.
  5614. * @param fn the function to call each iteration.
  5615. * @param callback a success call back that will be called when iterating stops.
  5616. * @param breakFunction a break condition (optional)
  5617. * @param timeout timeout settings for the setTimeout function. default - 0.
  5618. * @constructor
  5619. */
  5620. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5621. if (timeout === void 0) { timeout = 0; }
  5622. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5623. if (breakFunction && breakFunction())
  5624. loop.breakLoop();
  5625. else {
  5626. setTimeout(function () {
  5627. for (var i = 0; i < syncedIterations; ++i) {
  5628. var iteration = (loop.index * syncedIterations) + i;
  5629. if (iteration >= iterations)
  5630. break;
  5631. fn(iteration);
  5632. if (breakFunction && breakFunction()) {
  5633. loop.breakLoop();
  5634. break;
  5635. }
  5636. }
  5637. loop.executeNext();
  5638. }, timeout);
  5639. }
  5640. }, callback);
  5641. };
  5642. return AsyncLoop;
  5643. })();
  5644. BABYLON.AsyncLoop = AsyncLoop;
  5645. })(BABYLON || (BABYLON = {}));
  5646. var BABYLON;
  5647. (function (BABYLON) {
  5648. var Internals;
  5649. (function (Internals) {
  5650. var _AlphaState = (function () {
  5651. function _AlphaState() {
  5652. this._isAlphaBlendDirty = false;
  5653. this._isBlendFunctionParametersDirty = false;
  5654. this._alphaBlend = false;
  5655. this._blendFunctionParameters = new Array(4);
  5656. }
  5657. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5658. get: function () {
  5659. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5660. },
  5661. enumerable: true,
  5662. configurable: true
  5663. });
  5664. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5665. get: function () {
  5666. return this._alphaBlend;
  5667. },
  5668. set: function (value) {
  5669. if (this._alphaBlend === value) {
  5670. return;
  5671. }
  5672. this._alphaBlend = value;
  5673. this._isAlphaBlendDirty = true;
  5674. },
  5675. enumerable: true,
  5676. configurable: true
  5677. });
  5678. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5679. if (this._blendFunctionParameters[0] === value0 &&
  5680. this._blendFunctionParameters[1] === value1 &&
  5681. this._blendFunctionParameters[2] === value2 &&
  5682. this._blendFunctionParameters[3] === value3) {
  5683. return;
  5684. }
  5685. this._blendFunctionParameters[0] = value0;
  5686. this._blendFunctionParameters[1] = value1;
  5687. this._blendFunctionParameters[2] = value2;
  5688. this._blendFunctionParameters[3] = value3;
  5689. this._isBlendFunctionParametersDirty = true;
  5690. };
  5691. _AlphaState.prototype.reset = function () {
  5692. this._alphaBlend = false;
  5693. this._blendFunctionParameters[0] = null;
  5694. this._blendFunctionParameters[1] = null;
  5695. this._blendFunctionParameters[2] = null;
  5696. this._blendFunctionParameters[3] = null;
  5697. this._isAlphaBlendDirty = true;
  5698. this._isBlendFunctionParametersDirty = false;
  5699. };
  5700. _AlphaState.prototype.apply = function (gl) {
  5701. if (!this.isDirty) {
  5702. return;
  5703. }
  5704. // Alpha blend
  5705. if (this._isAlphaBlendDirty) {
  5706. if (this._alphaBlend) {
  5707. gl.enable(gl.BLEND);
  5708. }
  5709. else {
  5710. gl.disable(gl.BLEND);
  5711. }
  5712. this._isAlphaBlendDirty = false;
  5713. }
  5714. // Alpha function
  5715. if (this._isBlendFunctionParametersDirty) {
  5716. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5717. this._isBlendFunctionParametersDirty = false;
  5718. }
  5719. };
  5720. return _AlphaState;
  5721. })();
  5722. Internals._AlphaState = _AlphaState;
  5723. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5724. })(BABYLON || (BABYLON = {}));
  5725. var BABYLON;
  5726. (function (BABYLON) {
  5727. var Internals;
  5728. (function (Internals) {
  5729. var _DepthCullingState = (function () {
  5730. function _DepthCullingState() {
  5731. this._isDepthTestDirty = false;
  5732. this._isDepthMaskDirty = false;
  5733. this._isDepthFuncDirty = false;
  5734. this._isCullFaceDirty = false;
  5735. this._isCullDirty = false;
  5736. this._isZOffsetDirty = false;
  5737. }
  5738. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5739. get: function () {
  5740. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5741. },
  5742. enumerable: true,
  5743. configurable: true
  5744. });
  5745. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5746. get: function () {
  5747. return this._zOffset;
  5748. },
  5749. set: function (value) {
  5750. if (this._zOffset === value) {
  5751. return;
  5752. }
  5753. this._zOffset = value;
  5754. this._isZOffsetDirty = true;
  5755. },
  5756. enumerable: true,
  5757. configurable: true
  5758. });
  5759. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5760. get: function () {
  5761. return this._cullFace;
  5762. },
  5763. set: function (value) {
  5764. if (this._cullFace === value) {
  5765. return;
  5766. }
  5767. this._cullFace = value;
  5768. this._isCullFaceDirty = true;
  5769. },
  5770. enumerable: true,
  5771. configurable: true
  5772. });
  5773. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5774. get: function () {
  5775. return this._cull;
  5776. },
  5777. set: function (value) {
  5778. if (this._cull === value) {
  5779. return;
  5780. }
  5781. this._cull = value;
  5782. this._isCullDirty = true;
  5783. },
  5784. enumerable: true,
  5785. configurable: true
  5786. });
  5787. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5788. get: function () {
  5789. return this._depthFunc;
  5790. },
  5791. set: function (value) {
  5792. if (this._depthFunc === value) {
  5793. return;
  5794. }
  5795. this._depthFunc = value;
  5796. this._isDepthFuncDirty = true;
  5797. },
  5798. enumerable: true,
  5799. configurable: true
  5800. });
  5801. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5802. get: function () {
  5803. return this._depthMask;
  5804. },
  5805. set: function (value) {
  5806. if (this._depthMask === value) {
  5807. return;
  5808. }
  5809. this._depthMask = value;
  5810. this._isDepthMaskDirty = true;
  5811. },
  5812. enumerable: true,
  5813. configurable: true
  5814. });
  5815. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5816. get: function () {
  5817. return this._depthTest;
  5818. },
  5819. set: function (value) {
  5820. if (this._depthTest === value) {
  5821. return;
  5822. }
  5823. this._depthTest = value;
  5824. this._isDepthTestDirty = true;
  5825. },
  5826. enumerable: true,
  5827. configurable: true
  5828. });
  5829. _DepthCullingState.prototype.reset = function () {
  5830. this._depthMask = true;
  5831. this._depthTest = true;
  5832. this._depthFunc = null;
  5833. this._cullFace = null;
  5834. this._cull = null;
  5835. this._zOffset = 0;
  5836. this._isDepthTestDirty = true;
  5837. this._isDepthMaskDirty = true;
  5838. this._isDepthFuncDirty = false;
  5839. this._isCullFaceDirty = false;
  5840. this._isCullDirty = false;
  5841. this._isZOffsetDirty = false;
  5842. };
  5843. _DepthCullingState.prototype.apply = function (gl) {
  5844. if (!this.isDirty) {
  5845. return;
  5846. }
  5847. // Cull
  5848. if (this._isCullDirty) {
  5849. if (this.cull) {
  5850. gl.enable(gl.CULL_FACE);
  5851. }
  5852. else {
  5853. gl.disable(gl.CULL_FACE);
  5854. }
  5855. this._isCullDirty = false;
  5856. }
  5857. // Cull face
  5858. if (this._isCullFaceDirty) {
  5859. gl.cullFace(this.cullFace);
  5860. this._isCullFaceDirty = false;
  5861. }
  5862. // Depth mask
  5863. if (this._isDepthMaskDirty) {
  5864. gl.depthMask(this.depthMask);
  5865. this._isDepthMaskDirty = false;
  5866. }
  5867. // Depth test
  5868. if (this._isDepthTestDirty) {
  5869. if (this.depthTest) {
  5870. gl.enable(gl.DEPTH_TEST);
  5871. }
  5872. else {
  5873. gl.disable(gl.DEPTH_TEST);
  5874. }
  5875. this._isDepthTestDirty = false;
  5876. }
  5877. // Depth func
  5878. if (this._isDepthFuncDirty) {
  5879. gl.depthFunc(this.depthFunc);
  5880. this._isDepthFuncDirty = false;
  5881. }
  5882. // zOffset
  5883. if (this._isZOffsetDirty) {
  5884. if (this.zOffset) {
  5885. gl.enable(gl.POLYGON_OFFSET_FILL);
  5886. gl.polygonOffset(this.zOffset, 0);
  5887. }
  5888. else {
  5889. gl.disable(gl.POLYGON_OFFSET_FILL);
  5890. }
  5891. this._isZOffsetDirty = false;
  5892. }
  5893. };
  5894. return _DepthCullingState;
  5895. })();
  5896. Internals._DepthCullingState = _DepthCullingState;
  5897. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5898. })(BABYLON || (BABYLON = {}));
  5899. var BABYLON;
  5900. (function (BABYLON) {
  5901. var Internals;
  5902. (function (Internals) {
  5903. var _StencilState = (function () {
  5904. function _StencilState() {
  5905. this._isStencilTestDirty = false;
  5906. this._isStencilMaskDirty = false;
  5907. this._isStencilFuncDirty = false;
  5908. this._isStencilOpDirty = false;
  5909. this.reset();
  5910. }
  5911. Object.defineProperty(_StencilState.prototype, "isDirty", {
  5912. get: function () {
  5913. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  5914. },
  5915. enumerable: true,
  5916. configurable: true
  5917. });
  5918. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  5919. get: function () {
  5920. return this._stencilFunc;
  5921. },
  5922. set: function (value) {
  5923. if (this._stencilFunc === value) {
  5924. return;
  5925. }
  5926. this._stencilFunc = value;
  5927. this._isStencilFuncDirty = true;
  5928. },
  5929. enumerable: true,
  5930. configurable: true
  5931. });
  5932. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  5933. get: function () {
  5934. return this._stencilFuncRef;
  5935. },
  5936. set: function (value) {
  5937. if (this._stencilFuncRef === value) {
  5938. return;
  5939. }
  5940. this._stencilFuncRef = value;
  5941. this._isStencilFuncDirty = true;
  5942. },
  5943. enumerable: true,
  5944. configurable: true
  5945. });
  5946. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  5947. get: function () {
  5948. return this._stencilFuncMask;
  5949. },
  5950. set: function (value) {
  5951. if (this._stencilFuncMask === value) {
  5952. return;
  5953. }
  5954. this._stencilFuncMask = value;
  5955. this._isStencilFuncDirty = true;
  5956. },
  5957. enumerable: true,
  5958. configurable: true
  5959. });
  5960. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  5961. get: function () {
  5962. return this._stencilOpStencilFail;
  5963. },
  5964. set: function (value) {
  5965. if (this._stencilOpStencilFail === value) {
  5966. return;
  5967. }
  5968. this._stencilOpStencilFail = value;
  5969. this._isStencilOpDirty = true;
  5970. },
  5971. enumerable: true,
  5972. configurable: true
  5973. });
  5974. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  5975. get: function () {
  5976. return this._stencilOpDepthFail;
  5977. },
  5978. set: function (value) {
  5979. if (this._stencilOpDepthFail === value) {
  5980. return;
  5981. }
  5982. this._stencilOpDepthFail = value;
  5983. this._isStencilOpDirty = true;
  5984. },
  5985. enumerable: true,
  5986. configurable: true
  5987. });
  5988. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  5989. get: function () {
  5990. return this._stencilOpStencilDepthPass;
  5991. },
  5992. set: function (value) {
  5993. if (this._stencilOpStencilDepthPass === value) {
  5994. return;
  5995. }
  5996. this._stencilOpStencilDepthPass = value;
  5997. this._isStencilOpDirty = true;
  5998. },
  5999. enumerable: true,
  6000. configurable: true
  6001. });
  6002. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6003. get: function () {
  6004. return this._stencilMask;
  6005. },
  6006. set: function (value) {
  6007. if (this._stencilMask === value) {
  6008. return;
  6009. }
  6010. this._stencilMask = value;
  6011. this._isStencilMaskDirty = true;
  6012. },
  6013. enumerable: true,
  6014. configurable: true
  6015. });
  6016. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6017. get: function () {
  6018. return this._stencilTest;
  6019. },
  6020. set: function (value) {
  6021. if (this._stencilTest === value) {
  6022. return;
  6023. }
  6024. this._stencilTest = value;
  6025. this._isStencilTestDirty = true;
  6026. },
  6027. enumerable: true,
  6028. configurable: true
  6029. });
  6030. _StencilState.prototype.reset = function () {
  6031. this._stencilTest = false;
  6032. this._stencilMask = 0xFF;
  6033. this._stencilFunc = WebGLRenderingContext.ALWAYS;
  6034. this._stencilFuncRef = 1;
  6035. this._stencilFuncMask = 0xFF;
  6036. this._stencilOpStencilFail = WebGLRenderingContext.KEEP;
  6037. this._stencilOpDepthFail = WebGLRenderingContext.KEEP;
  6038. this._stencilOpStencilDepthPass = WebGLRenderingContext.REPLACE;
  6039. this._isStencilTestDirty = true;
  6040. this._isStencilMaskDirty = true;
  6041. this._isStencilFuncDirty = true;
  6042. this._isStencilOpDirty = true;
  6043. };
  6044. _StencilState.prototype.apply = function (gl) {
  6045. if (!this.isDirty) {
  6046. return;
  6047. }
  6048. // Stencil test
  6049. if (this._isStencilTestDirty) {
  6050. if (this.stencilTest) {
  6051. gl.enable(gl.STENCIL_TEST);
  6052. }
  6053. else {
  6054. gl.disable(gl.STENCIL_TEST);
  6055. }
  6056. this._isStencilTestDirty = false;
  6057. }
  6058. // Stencil mask
  6059. if (this._isStencilMaskDirty) {
  6060. gl.stencilMask(this.stencilMask);
  6061. this._isStencilMaskDirty = false;
  6062. }
  6063. // Stencil func
  6064. if (this._isStencilFuncDirty) {
  6065. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6066. this._isStencilFuncDirty = false;
  6067. }
  6068. // Stencil op
  6069. if (this._isStencilOpDirty) {
  6070. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6071. this._isStencilOpDirty = false;
  6072. }
  6073. };
  6074. return _StencilState;
  6075. })();
  6076. Internals._StencilState = _StencilState;
  6077. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6078. })(BABYLON || (BABYLON = {}));
  6079. var BABYLON;
  6080. (function (BABYLON) {
  6081. var compileShader = function (gl, source, type, defines) {
  6082. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6083. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6084. gl.compileShader(shader);
  6085. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6086. throw new Error(gl.getShaderInfoLog(shader));
  6087. }
  6088. return shader;
  6089. };
  6090. var HALF_FLOAT_OES = 0x8D61;
  6091. var getWebGLTextureType = function (gl, type) {
  6092. if (type === Engine.TEXTURETYPE_FLOAT) {
  6093. return gl.FLOAT;
  6094. }
  6095. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6096. // Add Half Float Constant.
  6097. return HALF_FLOAT_OES;
  6098. }
  6099. return gl.UNSIGNED_BYTE;
  6100. };
  6101. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6102. var magFilter = gl.NEAREST;
  6103. var minFilter = gl.NEAREST;
  6104. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6105. magFilter = gl.LINEAR;
  6106. if (generateMipMaps) {
  6107. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6108. }
  6109. else {
  6110. minFilter = gl.LINEAR;
  6111. }
  6112. }
  6113. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6114. magFilter = gl.LINEAR;
  6115. if (generateMipMaps) {
  6116. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6117. }
  6118. else {
  6119. minFilter = gl.LINEAR;
  6120. }
  6121. }
  6122. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6123. magFilter = gl.NEAREST;
  6124. if (generateMipMaps) {
  6125. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6126. }
  6127. else {
  6128. minFilter = gl.NEAREST;
  6129. }
  6130. }
  6131. return {
  6132. min: minFilter,
  6133. mag: magFilter
  6134. };
  6135. };
  6136. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6137. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6138. var engine = scene.getEngine();
  6139. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6140. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6141. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6142. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6143. texture._baseWidth = width;
  6144. texture._baseHeight = height;
  6145. texture._width = potWidth;
  6146. texture._height = potHeight;
  6147. texture.isReady = true;
  6148. processFunction(potWidth, potHeight);
  6149. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6150. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6151. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6152. if (!noMipmap && !isCompressed) {
  6153. gl.generateMipmap(gl.TEXTURE_2D);
  6154. }
  6155. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6156. engine.resetTextureCache();
  6157. scene._removePendingData(texture);
  6158. texture.onLoadedCallbacks.forEach(function (callback) {
  6159. callback();
  6160. });
  6161. texture.onLoadedCallbacks = [];
  6162. };
  6163. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  6164. var img;
  6165. var onload = function () {
  6166. loadedImages[index] = img;
  6167. loadedImages._internalCount++;
  6168. scene._removePendingData(img);
  6169. if (loadedImages._internalCount === 6) {
  6170. onfinish(loadedImages);
  6171. }
  6172. };
  6173. var onerror = function () {
  6174. scene._removePendingData(img);
  6175. };
  6176. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6177. scene._addPendingData(img);
  6178. };
  6179. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  6180. var loadedImages = [];
  6181. loadedImages._internalCount = 0;
  6182. for (var index = 0; index < 6; index++) {
  6183. partialLoad(files[index], index, loadedImages, scene, onfinish);
  6184. }
  6185. };
  6186. var InstancingAttributeInfo = (function () {
  6187. function InstancingAttributeInfo() {
  6188. }
  6189. return InstancingAttributeInfo;
  6190. })();
  6191. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6192. var EngineCapabilities = (function () {
  6193. function EngineCapabilities() {
  6194. }
  6195. return EngineCapabilities;
  6196. })();
  6197. BABYLON.EngineCapabilities = EngineCapabilities;
  6198. /**
  6199. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6200. */
  6201. var Engine = (function () {
  6202. /**
  6203. * @constructor
  6204. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6205. * @param {boolean} [antialias] - enable antialias
  6206. * @param options - further options to be sent to the getContext function
  6207. */
  6208. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6209. var _this = this;
  6210. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6211. // Public members
  6212. this.isFullscreen = false;
  6213. this.isPointerLock = false;
  6214. this.cullBackFaces = true;
  6215. this.renderEvenInBackground = true;
  6216. // To enable/disable IDB support and avoid XHR on .manifest
  6217. this.enableOfflineSupport = true;
  6218. this.scenes = new Array();
  6219. this._windowIsBackground = false;
  6220. this._webGLVersion = "1.0";
  6221. this._drawCalls = new BABYLON.PerfCounter();
  6222. this._renderingQueueLaunched = false;
  6223. this._activeRenderLoops = [];
  6224. // FPS
  6225. this.fpsRange = 60;
  6226. this.previousFramesDuration = [];
  6227. this.fps = 60;
  6228. this.deltaTime = 0;
  6229. // States
  6230. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6231. this._stencilState = new BABYLON.Internals._StencilState();
  6232. this._alphaState = new BABYLON.Internals._AlphaState();
  6233. this._alphaMode = Engine.ALPHA_DISABLE;
  6234. // Cache
  6235. this._loadedTexturesCache = new Array();
  6236. this._maxTextureChannels = 16;
  6237. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6238. this._compiledEffects = {};
  6239. this._vertexAttribArraysEnabled = [];
  6240. this._uintIndicesCurrentlySet = false;
  6241. this._currentBoundBuffer = new Array();
  6242. this._currentBufferPointers = [];
  6243. this._currentInstanceLocations = new Array();
  6244. this._currentInstanceBuffers = new Array();
  6245. this._onVRFullScreenTriggered = function () {
  6246. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6247. //get the old size before we change
  6248. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6249. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6250. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6251. //But actually, no browser follow the specs...
  6252. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6253. //get the width and height, change the render size
  6254. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6255. var width, height;
  6256. _this.setHardwareScalingLevel(1);
  6257. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6258. }
  6259. else {
  6260. //When the specs are implemented, need to uncomment this.
  6261. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6262. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6263. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6264. _this._vrDisplayEnabled = undefined;
  6265. }
  6266. };
  6267. this._renderingCanvas = canvas;
  6268. this._externalData = new BABYLON.StringDictionary();
  6269. options = options || {};
  6270. if (antialias != null) {
  6271. options.antialias = antialias;
  6272. }
  6273. if (options.preserveDrawingBuffer === undefined) {
  6274. options.preserveDrawingBuffer = false;
  6275. }
  6276. // Checks if some of the format renders first to allow the use of webgl inspector.
  6277. var renderToFullFloat = this._canRenderToFloatTexture();
  6278. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6279. // GL
  6280. //try {
  6281. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6282. // if (this._gl) {
  6283. // this._webGLVersion = "2.0";
  6284. // }
  6285. //} catch (e) {
  6286. // // Do nothing
  6287. //}
  6288. if (!this._gl) {
  6289. try {
  6290. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6291. }
  6292. catch (e) {
  6293. throw new Error("WebGL not supported");
  6294. }
  6295. }
  6296. if (!this._gl) {
  6297. throw new Error("WebGL not supported");
  6298. }
  6299. this._onBlur = function () {
  6300. _this._windowIsBackground = true;
  6301. };
  6302. this._onFocus = function () {
  6303. _this._windowIsBackground = false;
  6304. };
  6305. window.addEventListener("blur", this._onBlur);
  6306. window.addEventListener("focus", this._onFocus);
  6307. // Viewport
  6308. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6309. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6310. this.resize();
  6311. // Caps
  6312. this._isStencilEnable = options.stencil;
  6313. this._caps = new EngineCapabilities();
  6314. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6315. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6316. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6317. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6318. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6319. // Infos
  6320. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6321. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6322. if (rendererInfo != null) {
  6323. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6324. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6325. }
  6326. if (!this._glVendor) {
  6327. this._glVendor = "Unknown vendor";
  6328. }
  6329. if (!this._glRenderer) {
  6330. this._glRenderer = "Unknown renderer";
  6331. }
  6332. // Extensions
  6333. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6334. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6335. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6336. 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');
  6337. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6338. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6339. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6340. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6341. this._caps.highPrecisionShaderSupported = true;
  6342. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6343. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6344. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6345. this._caps.textureFloatRender = renderToFullFloat;
  6346. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6347. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6348. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6349. if (this._gl.getShaderPrecisionFormat) {
  6350. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6351. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6352. }
  6353. // Depth buffer
  6354. this.setDepthBuffer(true);
  6355. this.setDepthFunctionToLessOrEqual();
  6356. this.setDepthWrite(true);
  6357. // Fullscreen
  6358. this._onFullscreenChange = function () {
  6359. if (document.fullscreen !== undefined) {
  6360. _this.isFullscreen = document.fullscreen;
  6361. }
  6362. else if (document.mozFullScreen !== undefined) {
  6363. _this.isFullscreen = document.mozFullScreen;
  6364. }
  6365. else if (document.webkitIsFullScreen !== undefined) {
  6366. _this.isFullscreen = document.webkitIsFullScreen;
  6367. }
  6368. else if (document.msIsFullScreen !== undefined) {
  6369. _this.isFullscreen = document.msIsFullScreen;
  6370. }
  6371. // Pointer lock
  6372. if (_this.isFullscreen && _this._pointerLockRequested) {
  6373. canvas.requestPointerLock = canvas.requestPointerLock ||
  6374. canvas.msRequestPointerLock ||
  6375. canvas.mozRequestPointerLock ||
  6376. canvas.webkitRequestPointerLock;
  6377. if (canvas.requestPointerLock) {
  6378. canvas.requestPointerLock();
  6379. }
  6380. }
  6381. };
  6382. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6383. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6384. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6385. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6386. // Pointer lock
  6387. this._onPointerLockChange = function () {
  6388. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6389. document.webkitPointerLockElement === canvas ||
  6390. document.msPointerLockElement === canvas ||
  6391. document.pointerLockElement === canvas);
  6392. };
  6393. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6394. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6395. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6396. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6397. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6398. Engine.audioEngine = new BABYLON.AudioEngine();
  6399. }
  6400. //default loading screen
  6401. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6402. //Load WebVR Devices
  6403. if (options.autoEnableWebVR) {
  6404. this.initWebVR();
  6405. }
  6406. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6407. }
  6408. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6409. get: function () {
  6410. return Engine._ALPHA_DISABLE;
  6411. },
  6412. enumerable: true,
  6413. configurable: true
  6414. });
  6415. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6416. get: function () {
  6417. return Engine._ALPHA_ONEONE;
  6418. },
  6419. enumerable: true,
  6420. configurable: true
  6421. });
  6422. Object.defineProperty(Engine, "ALPHA_ADD", {
  6423. get: function () {
  6424. return Engine._ALPHA_ADD;
  6425. },
  6426. enumerable: true,
  6427. configurable: true
  6428. });
  6429. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6430. get: function () {
  6431. return Engine._ALPHA_COMBINE;
  6432. },
  6433. enumerable: true,
  6434. configurable: true
  6435. });
  6436. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6437. get: function () {
  6438. return Engine._ALPHA_SUBTRACT;
  6439. },
  6440. enumerable: true,
  6441. configurable: true
  6442. });
  6443. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6444. get: function () {
  6445. return Engine._ALPHA_MULTIPLY;
  6446. },
  6447. enumerable: true,
  6448. configurable: true
  6449. });
  6450. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6451. get: function () {
  6452. return Engine._ALPHA_MAXIMIZED;
  6453. },
  6454. enumerable: true,
  6455. configurable: true
  6456. });
  6457. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6458. get: function () {
  6459. return Engine._DELAYLOADSTATE_NONE;
  6460. },
  6461. enumerable: true,
  6462. configurable: true
  6463. });
  6464. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6465. get: function () {
  6466. return Engine._DELAYLOADSTATE_LOADED;
  6467. },
  6468. enumerable: true,
  6469. configurable: true
  6470. });
  6471. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6472. get: function () {
  6473. return Engine._DELAYLOADSTATE_LOADING;
  6474. },
  6475. enumerable: true,
  6476. configurable: true
  6477. });
  6478. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6479. get: function () {
  6480. return Engine._DELAYLOADSTATE_NOTLOADED;
  6481. },
  6482. enumerable: true,
  6483. configurable: true
  6484. });
  6485. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6486. get: function () {
  6487. return Engine._TEXTUREFORMAT_ALPHA;
  6488. },
  6489. enumerable: true,
  6490. configurable: true
  6491. });
  6492. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6493. get: function () {
  6494. return Engine._TEXTUREFORMAT_LUMINANCE;
  6495. },
  6496. enumerable: true,
  6497. configurable: true
  6498. });
  6499. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6500. get: function () {
  6501. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6502. },
  6503. enumerable: true,
  6504. configurable: true
  6505. });
  6506. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6507. get: function () {
  6508. return Engine._TEXTUREFORMAT_RGB;
  6509. },
  6510. enumerable: true,
  6511. configurable: true
  6512. });
  6513. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6514. get: function () {
  6515. return Engine._TEXTUREFORMAT_RGBA;
  6516. },
  6517. enumerable: true,
  6518. configurable: true
  6519. });
  6520. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6521. get: function () {
  6522. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6523. },
  6524. enumerable: true,
  6525. configurable: true
  6526. });
  6527. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6528. get: function () {
  6529. return Engine._TEXTURETYPE_FLOAT;
  6530. },
  6531. enumerable: true,
  6532. configurable: true
  6533. });
  6534. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6535. get: function () {
  6536. return Engine._TEXTURETYPE_HALF_FLOAT;
  6537. },
  6538. enumerable: true,
  6539. configurable: true
  6540. });
  6541. Object.defineProperty(Engine, "Version", {
  6542. get: function () {
  6543. return "2.5-alpha";
  6544. },
  6545. enumerable: true,
  6546. configurable: true
  6547. });
  6548. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6549. get: function () {
  6550. return this._webGLVersion;
  6551. },
  6552. enumerable: true,
  6553. configurable: true
  6554. });
  6555. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6556. /**
  6557. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6558. */
  6559. get: function () {
  6560. return this._isStencilEnable;
  6561. },
  6562. enumerable: true,
  6563. configurable: true
  6564. });
  6565. Engine.prototype._prepareWorkingCanvas = function () {
  6566. if (this._workingCanvas) {
  6567. return;
  6568. }
  6569. this._workingCanvas = document.createElement("canvas");
  6570. this._workingContext = this._workingCanvas.getContext("2d");
  6571. };
  6572. Engine.prototype.resetTextureCache = function () {
  6573. for (var index = 0; index < this._maxTextureChannels; index++) {
  6574. this._activeTexturesCache[index] = null;
  6575. }
  6576. };
  6577. Engine.prototype.getGlInfo = function () {
  6578. return {
  6579. vendor: this._glVendor,
  6580. renderer: this._glRenderer,
  6581. version: this._glVersion
  6582. };
  6583. };
  6584. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6585. if (useScreen === void 0) { useScreen = false; }
  6586. var viewport = camera.viewport;
  6587. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6588. };
  6589. Engine.prototype.getRenderWidth = function (useScreen) {
  6590. if (useScreen === void 0) { useScreen = false; }
  6591. if (!useScreen && this._currentRenderTarget) {
  6592. return this._currentRenderTarget._width;
  6593. }
  6594. return this._renderingCanvas.width;
  6595. };
  6596. Engine.prototype.getRenderHeight = function (useScreen) {
  6597. if (useScreen === void 0) { useScreen = false; }
  6598. if (!useScreen && this._currentRenderTarget) {
  6599. return this._currentRenderTarget._height;
  6600. }
  6601. return this._renderingCanvas.height;
  6602. };
  6603. Engine.prototype.getRenderingCanvas = function () {
  6604. return this._renderingCanvas;
  6605. };
  6606. Engine.prototype.getRenderingCanvasClientRect = function () {
  6607. return this._renderingCanvas.getBoundingClientRect();
  6608. };
  6609. Engine.prototype.setHardwareScalingLevel = function (level) {
  6610. this._hardwareScalingLevel = level;
  6611. this.resize();
  6612. };
  6613. Engine.prototype.getHardwareScalingLevel = function () {
  6614. return this._hardwareScalingLevel;
  6615. };
  6616. Engine.prototype.getLoadedTexturesCache = function () {
  6617. return this._loadedTexturesCache;
  6618. };
  6619. Engine.prototype.getCaps = function () {
  6620. return this._caps;
  6621. };
  6622. Object.defineProperty(Engine.prototype, "drawCalls", {
  6623. get: function () {
  6624. return this._drawCalls.current;
  6625. },
  6626. enumerable: true,
  6627. configurable: true
  6628. });
  6629. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6630. get: function () {
  6631. return this._drawCalls;
  6632. },
  6633. enumerable: true,
  6634. configurable: true
  6635. });
  6636. Engine.prototype.getDepthFunction = function () {
  6637. return this._depthCullingState.depthFunc;
  6638. };
  6639. Engine.prototype.setDepthFunction = function (depthFunc) {
  6640. this._depthCullingState.depthFunc = depthFunc;
  6641. };
  6642. Engine.prototype.setDepthFunctionToGreater = function () {
  6643. this._depthCullingState.depthFunc = this._gl.GREATER;
  6644. };
  6645. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6646. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6647. };
  6648. Engine.prototype.setDepthFunctionToLess = function () {
  6649. this._depthCullingState.depthFunc = this._gl.LESS;
  6650. };
  6651. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6652. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6653. };
  6654. Engine.prototype.getStencilBuffer = function () {
  6655. return this._stencilState.stencilTest;
  6656. };
  6657. Engine.prototype.setStencilBuffer = function (enable) {
  6658. this._stencilState.stencilTest = enable;
  6659. };
  6660. Engine.prototype.getStencilMask = function () {
  6661. return this._stencilState.stencilMask;
  6662. };
  6663. Engine.prototype.setStencilMask = function (mask) {
  6664. this._stencilState.stencilMask = mask;
  6665. };
  6666. Engine.prototype.getStencilFunction = function () {
  6667. return this._stencilState.stencilFunc;
  6668. };
  6669. Engine.prototype.getStencilFunctionReference = function () {
  6670. return this._stencilState.stencilFuncRef;
  6671. };
  6672. Engine.prototype.getStencilFunctionMask = function () {
  6673. return this._stencilState.stencilFuncMask;
  6674. };
  6675. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6676. this._stencilState.stencilFunc = stencilFunc;
  6677. };
  6678. Engine.prototype.setStencilFunctionReference = function (reference) {
  6679. this._stencilState.stencilFuncRef = reference;
  6680. };
  6681. Engine.prototype.setStencilFunctionMask = function (mask) {
  6682. this._stencilState.stencilFuncMask = mask;
  6683. };
  6684. Engine.prototype.getStencilOperationFail = function () {
  6685. return this._stencilState.stencilOpStencilFail;
  6686. };
  6687. Engine.prototype.getStencilOperationDepthFail = function () {
  6688. return this._stencilState.stencilOpDepthFail;
  6689. };
  6690. Engine.prototype.getStencilOperationPass = function () {
  6691. return this._stencilState.stencilOpStencilDepthPass;
  6692. };
  6693. Engine.prototype.setStencilOperationFail = function (operation) {
  6694. this._stencilState.stencilOpStencilFail = operation;
  6695. };
  6696. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  6697. this._stencilState.stencilOpDepthFail = operation;
  6698. };
  6699. Engine.prototype.setStencilOperationPass = function (operation) {
  6700. this._stencilState.stencilOpStencilDepthPass = operation;
  6701. };
  6702. /**
  6703. * stop executing a render loop function and remove it from the execution array
  6704. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6705. */
  6706. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6707. if (!renderFunction) {
  6708. this._activeRenderLoops = [];
  6709. return;
  6710. }
  6711. var index = this._activeRenderLoops.indexOf(renderFunction);
  6712. if (index >= 0) {
  6713. this._activeRenderLoops.splice(index, 1);
  6714. }
  6715. };
  6716. Engine.prototype._renderLoop = function () {
  6717. var shouldRender = true;
  6718. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6719. shouldRender = false;
  6720. }
  6721. if (shouldRender) {
  6722. // Start new frame
  6723. this.beginFrame();
  6724. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6725. var renderFunction = this._activeRenderLoops[index];
  6726. renderFunction();
  6727. }
  6728. // Present
  6729. this.endFrame();
  6730. }
  6731. if (this._activeRenderLoops.length > 0) {
  6732. // Register new frame
  6733. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  6734. }
  6735. else {
  6736. this._renderingQueueLaunched = false;
  6737. }
  6738. };
  6739. /**
  6740. * Register and execute a render loop. The engine can have more than one render function.
  6741. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6742. * @example
  6743. * engine.runRenderLoop(function () {
  6744. * scene.render()
  6745. * })
  6746. */
  6747. Engine.prototype.runRenderLoop = function (renderFunction) {
  6748. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6749. return;
  6750. }
  6751. this._activeRenderLoops.push(renderFunction);
  6752. if (!this._renderingQueueLaunched) {
  6753. this._renderingQueueLaunched = true;
  6754. this._bindedRenderFunction = this._renderLoop.bind(this);
  6755. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6756. }
  6757. };
  6758. /**
  6759. * Toggle full screen mode.
  6760. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6761. * @param {any} options - an options object to be sent to the requestFullscreen function
  6762. */
  6763. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  6764. if (this.isFullscreen) {
  6765. BABYLON.Tools.ExitFullscreen();
  6766. }
  6767. else {
  6768. this._pointerLockRequested = requestPointerLock;
  6769. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  6770. }
  6771. };
  6772. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  6773. if (stencil === void 0) { stencil = false; }
  6774. this.applyStates();
  6775. var mode = 0;
  6776. if (backBuffer) {
  6777. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6778. mode |= this._gl.COLOR_BUFFER_BIT;
  6779. }
  6780. if (depth) {
  6781. this._gl.clearDepth(1.0);
  6782. mode |= this._gl.DEPTH_BUFFER_BIT;
  6783. }
  6784. if (stencil) {
  6785. this._gl.clearStencil(0);
  6786. mode |= this._gl.STENCIL_BUFFER_BIT;
  6787. }
  6788. this._gl.clear(mode);
  6789. };
  6790. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6791. var gl = this._gl;
  6792. // Save state
  6793. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6794. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6795. // Change state
  6796. gl.enable(gl.SCISSOR_TEST);
  6797. gl.scissor(x, y, width, height);
  6798. // Clear
  6799. this.clear(clearColor, true, true, true);
  6800. // Restore state
  6801. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6802. if (curScissor === true) {
  6803. gl.enable(gl.SCISSOR_TEST);
  6804. }
  6805. else {
  6806. gl.disable(gl.SCISSOR_TEST);
  6807. }
  6808. };
  6809. /**
  6810. * Set the WebGL's viewport
  6811. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6812. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6813. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6814. */
  6815. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6816. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6817. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6818. var x = viewport.x || 0;
  6819. var y = viewport.y || 0;
  6820. this._cachedViewport = viewport;
  6821. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6822. };
  6823. /**
  6824. * Directly set the WebGL Viewport
  6825. * The x, y, width & height are directly passed to the WebGL call
  6826. * @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.
  6827. */
  6828. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6829. var currentViewport = this._cachedViewport;
  6830. this._cachedViewport = null;
  6831. this._gl.viewport(x, y, width, height);
  6832. return currentViewport;
  6833. };
  6834. Engine.prototype.beginFrame = function () {
  6835. this._measureFps();
  6836. };
  6837. Engine.prototype.endFrame = function () {
  6838. //this.flushFramebuffer();
  6839. //submit frame to the vr device, if enabled
  6840. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  6841. this._vrDisplayEnabled.submitFrame();
  6842. }
  6843. };
  6844. /**
  6845. * resize the view according to the canvas' size.
  6846. * @example
  6847. * window.addEventListener("resize", function () {
  6848. * engine.resize();
  6849. * });
  6850. */
  6851. Engine.prototype.resize = function () {
  6852. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6853. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6854. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6855. for (var index = 0; index < this.scenes.length; index++) {
  6856. var scene = this.scenes[index];
  6857. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  6858. scene.debugLayer._syncPositions();
  6859. }
  6860. }
  6861. };
  6862. /**
  6863. * force a specific size of the canvas
  6864. * @param {number} width - the new canvas' width
  6865. * @param {number} height - the new canvas' height
  6866. */
  6867. Engine.prototype.setSize = function (width, height) {
  6868. this._renderingCanvas.width = width;
  6869. this._renderingCanvas.height = height;
  6870. for (var index = 0; index < this.scenes.length; index++) {
  6871. var scene = this.scenes[index];
  6872. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6873. var cam = scene.cameras[camIndex];
  6874. cam._currentRenderId = 0;
  6875. }
  6876. }
  6877. };
  6878. //WebVR functions
  6879. Engine.prototype.initWebVR = function () {
  6880. if (!this.vrDisplaysPromise) {
  6881. this._getVRDisplays();
  6882. }
  6883. };
  6884. Engine.prototype.enableVR = function (vrDevice) {
  6885. this._vrDisplayEnabled = vrDevice;
  6886. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  6887. };
  6888. Engine.prototype.disableVR = function () {
  6889. if (this._vrDisplayEnabled) {
  6890. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  6891. }
  6892. };
  6893. Engine.prototype._getVRDisplays = function () {
  6894. var _this = this;
  6895. var getWebVRDevices = function (devices) {
  6896. var size = devices.length;
  6897. var i = 0;
  6898. _this._vrDisplays = devices.filter(function (device) {
  6899. return devices[i] instanceof VRDisplay;
  6900. });
  6901. return _this._vrDisplays;
  6902. };
  6903. //using a key due to typescript
  6904. if (navigator.getVRDisplays) {
  6905. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  6906. }
  6907. };
  6908. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6909. this._currentRenderTarget = texture;
  6910. this.bindUnboundFramebuffer(texture._framebuffer);
  6911. var gl = this._gl;
  6912. if (texture.isCube) {
  6913. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6914. }
  6915. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6916. this.wipeCaches();
  6917. };
  6918. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  6919. if (this._currentFramebuffer !== framebuffer) {
  6920. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  6921. this._currentFramebuffer = framebuffer;
  6922. }
  6923. };
  6924. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6925. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6926. this._currentRenderTarget = null;
  6927. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6928. var gl = this._gl;
  6929. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6930. gl.generateMipmap(gl.TEXTURE_2D);
  6931. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  6932. }
  6933. this.bindUnboundFramebuffer(null);
  6934. };
  6935. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6936. if (texture.generateMipMaps) {
  6937. var gl = this._gl;
  6938. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  6939. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6940. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  6941. }
  6942. };
  6943. Engine.prototype.flushFramebuffer = function () {
  6944. this._gl.flush();
  6945. };
  6946. Engine.prototype.restoreDefaultFramebuffer = function () {
  6947. this._currentRenderTarget = null;
  6948. this.bindUnboundFramebuffer(null);
  6949. this.setViewport(this._cachedViewport);
  6950. this.wipeCaches();
  6951. };
  6952. // VBOs
  6953. Engine.prototype._resetVertexBufferBinding = function () {
  6954. this.bindArrayBuffer(null);
  6955. this._cachedVertexBuffers = null;
  6956. };
  6957. Engine.prototype.createVertexBuffer = function (vertices) {
  6958. var vbo = this._gl.createBuffer();
  6959. this.bindArrayBuffer(vbo);
  6960. if (vertices instanceof Float32Array) {
  6961. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6962. }
  6963. else {
  6964. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6965. }
  6966. this._resetVertexBufferBinding();
  6967. vbo.references = 1;
  6968. return vbo;
  6969. };
  6970. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  6971. var vbo = this._gl.createBuffer();
  6972. this.bindArrayBuffer(vbo);
  6973. if (vertices instanceof Float32Array) {
  6974. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  6975. }
  6976. else {
  6977. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  6978. }
  6979. this._resetVertexBufferBinding();
  6980. vbo.references = 1;
  6981. return vbo;
  6982. };
  6983. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  6984. this.bindArrayBuffer(vertexBuffer);
  6985. if (offset === undefined) {
  6986. offset = 0;
  6987. }
  6988. if (count === undefined) {
  6989. if (vertices instanceof Float32Array) {
  6990. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6991. }
  6992. else {
  6993. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6994. }
  6995. }
  6996. else {
  6997. if (vertices instanceof Float32Array) {
  6998. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  6999. }
  7000. else {
  7001. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7002. }
  7003. }
  7004. this._resetVertexBufferBinding();
  7005. };
  7006. Engine.prototype._resetIndexBufferBinding = function () {
  7007. this.bindIndexBuffer(null);
  7008. this._cachedIndexBuffer = null;
  7009. };
  7010. Engine.prototype.createIndexBuffer = function (indices) {
  7011. var vbo = this._gl.createBuffer();
  7012. this.bindIndexBuffer(vbo);
  7013. // Check for 32 bits indices
  7014. var arrayBuffer;
  7015. var need32Bits = false;
  7016. if (this._caps.uintIndices) {
  7017. for (var index = 0; index < indices.length; index++) {
  7018. if (indices[index] > 65535) {
  7019. need32Bits = true;
  7020. break;
  7021. }
  7022. }
  7023. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7024. }
  7025. else {
  7026. arrayBuffer = new Uint16Array(indices);
  7027. }
  7028. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7029. this._resetIndexBufferBinding();
  7030. vbo.references = 1;
  7031. vbo.is32Bits = need32Bits;
  7032. return vbo;
  7033. };
  7034. Engine.prototype.bindArrayBuffer = function (buffer) {
  7035. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7036. };
  7037. Engine.prototype.bindIndexBuffer = function (buffer) {
  7038. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7039. };
  7040. Engine.prototype.bindBuffer = function (buffer, target) {
  7041. if (this._currentBoundBuffer[target] !== buffer) {
  7042. this._gl.bindBuffer(target, buffer);
  7043. this._currentBoundBuffer[target] = buffer;
  7044. }
  7045. };
  7046. Engine.prototype.updateArrayBuffer = function (data) {
  7047. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7048. };
  7049. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7050. var pointer = this._currentBufferPointers[indx];
  7051. var changed = false;
  7052. if (!pointer) {
  7053. changed = true;
  7054. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7055. }
  7056. else {
  7057. if (pointer.buffer !== buffer) {
  7058. pointer.buffer = buffer;
  7059. changed = true;
  7060. }
  7061. if (pointer.size !== size) {
  7062. pointer.size = size;
  7063. changed = true;
  7064. }
  7065. if (pointer.type !== type) {
  7066. pointer.type = type;
  7067. changed = true;
  7068. }
  7069. if (pointer.normalized !== normalized) {
  7070. pointer.normalized = normalized;
  7071. changed = true;
  7072. }
  7073. if (pointer.stride !== stride) {
  7074. pointer.stride = stride;
  7075. changed = true;
  7076. }
  7077. if (pointer.offset !== offset) {
  7078. pointer.offset = offset;
  7079. changed = true;
  7080. }
  7081. }
  7082. if (changed) {
  7083. this.bindArrayBuffer(buffer);
  7084. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7085. }
  7086. };
  7087. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7088. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7089. this._cachedVertexBuffers = vertexBuffer;
  7090. this._cachedEffectForVertexBuffers = effect;
  7091. var attributesCount = effect.getAttributesCount();
  7092. var offset = 0;
  7093. for (var index = 0; index < attributesCount; index++) {
  7094. if (index < vertexDeclaration.length) {
  7095. var order = effect.getAttributeLocation(index);
  7096. if (order >= 0) {
  7097. if (!this._vertexAttribArraysEnabled[order]) {
  7098. this._gl.enableVertexAttribArray(order);
  7099. this._vertexAttribArraysEnabled[order] = true;
  7100. }
  7101. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7102. }
  7103. offset += vertexDeclaration[index] * 4;
  7104. }
  7105. else {
  7106. //disable effect attributes that have no data
  7107. var order = effect.getAttributeLocation(index);
  7108. if (this._vertexAttribArraysEnabled[order]) {
  7109. this._gl.disableVertexAttribArray(order);
  7110. this._vertexAttribArraysEnabled[order] = false;
  7111. }
  7112. }
  7113. }
  7114. }
  7115. if (this._cachedIndexBuffer !== indexBuffer) {
  7116. this._cachedIndexBuffer = indexBuffer;
  7117. this.bindIndexBuffer(indexBuffer);
  7118. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7119. }
  7120. };
  7121. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7122. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7123. this._cachedVertexBuffers = vertexBuffers;
  7124. this._cachedEffectForVertexBuffers = effect;
  7125. var attributes = effect.getAttributesNames();
  7126. for (var index = 0; index < attributes.length; index++) {
  7127. var order = effect.getAttributeLocation(index);
  7128. if (order >= 0) {
  7129. var vertexBuffer = vertexBuffers[attributes[index]];
  7130. if (!vertexBuffer) {
  7131. if (this._vertexAttribArraysEnabled[order]) {
  7132. this._gl.disableVertexAttribArray(order);
  7133. this._vertexAttribArraysEnabled[order] = false;
  7134. }
  7135. continue;
  7136. }
  7137. if (!this._vertexAttribArraysEnabled[order]) {
  7138. this._gl.enableVertexAttribArray(order);
  7139. this._vertexAttribArraysEnabled[order] = true;
  7140. }
  7141. var buffer = vertexBuffer.getBuffer();
  7142. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7143. if (vertexBuffer.getIsInstanced()) {
  7144. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7145. this._currentInstanceLocations.push(order);
  7146. this._currentInstanceBuffers.push(buffer);
  7147. }
  7148. }
  7149. }
  7150. }
  7151. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7152. this._cachedIndexBuffer = indexBuffer;
  7153. this.bindIndexBuffer(indexBuffer);
  7154. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7155. }
  7156. };
  7157. Engine.prototype.unbindInstanceAttributes = function () {
  7158. var boundBuffer;
  7159. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7160. var instancesBuffer = this._currentInstanceBuffers[i];
  7161. if (boundBuffer != instancesBuffer) {
  7162. boundBuffer = instancesBuffer;
  7163. this.bindArrayBuffer(instancesBuffer);
  7164. }
  7165. var offsetLocation = this._currentInstanceLocations[i];
  7166. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7167. }
  7168. this._currentInstanceBuffers.length = 0;
  7169. this._currentInstanceLocations.length = 0;
  7170. };
  7171. Engine.prototype._releaseBuffer = function (buffer) {
  7172. buffer.references--;
  7173. if (buffer.references === 0) {
  7174. this._gl.deleteBuffer(buffer);
  7175. return true;
  7176. }
  7177. return false;
  7178. };
  7179. Engine.prototype.createInstancesBuffer = function (capacity) {
  7180. var buffer = this._gl.createBuffer();
  7181. buffer.capacity = capacity;
  7182. this.bindArrayBuffer(buffer);
  7183. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7184. return buffer;
  7185. };
  7186. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7187. this._gl.deleteBuffer(buffer);
  7188. };
  7189. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7190. this.bindArrayBuffer(instancesBuffer);
  7191. if (data) {
  7192. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7193. }
  7194. if (offsetLocations[0].index !== undefined) {
  7195. var stride = 0;
  7196. for (var i = 0; i < offsetLocations.length; i++) {
  7197. var ai = offsetLocations[i];
  7198. stride += ai.attributeSize * 4;
  7199. }
  7200. for (var i = 0; i < offsetLocations.length; i++) {
  7201. var ai = offsetLocations[i];
  7202. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7203. this._gl.enableVertexAttribArray(ai.index);
  7204. this._vertexAttribArraysEnabled[ai.index] = true;
  7205. }
  7206. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7207. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7208. this._currentInstanceLocations.push(ai.index);
  7209. this._currentInstanceBuffers.push(instancesBuffer);
  7210. }
  7211. }
  7212. else {
  7213. for (var index = 0; index < 4; index++) {
  7214. var offsetLocation = offsetLocations[index];
  7215. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7216. this._gl.enableVertexAttribArray(offsetLocation);
  7217. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7218. }
  7219. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7220. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7221. this._currentInstanceLocations.push(offsetLocation);
  7222. this._currentInstanceBuffers.push(instancesBuffer);
  7223. }
  7224. }
  7225. };
  7226. Engine.prototype.applyStates = function () {
  7227. this._depthCullingState.apply(this._gl);
  7228. this._stencilState.apply(this._gl);
  7229. this._alphaState.apply(this._gl);
  7230. };
  7231. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7232. // Apply states
  7233. this.applyStates();
  7234. this._drawCalls.addCount(1, false);
  7235. // Render
  7236. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7237. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7238. if (instancesCount) {
  7239. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7240. return;
  7241. }
  7242. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7243. };
  7244. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7245. // Apply states
  7246. this.applyStates();
  7247. this._drawCalls.addCount(1, false);
  7248. if (instancesCount) {
  7249. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7250. return;
  7251. }
  7252. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7253. };
  7254. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7255. // Apply states
  7256. this.applyStates();
  7257. this._drawCalls.addCount(1, false);
  7258. if (instancesCount) {
  7259. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7260. return;
  7261. }
  7262. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7263. };
  7264. // Shaders
  7265. Engine.prototype._releaseEffect = function (effect) {
  7266. if (this._compiledEffects[effect._key]) {
  7267. delete this._compiledEffects[effect._key];
  7268. if (effect.getProgram()) {
  7269. this._gl.deleteProgram(effect.getProgram());
  7270. }
  7271. }
  7272. };
  7273. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7274. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7275. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7276. var name = vertex + "+" + fragment + "@" + defines;
  7277. if (this._compiledEffects[name]) {
  7278. return this._compiledEffects[name];
  7279. }
  7280. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7281. effect._key = name;
  7282. this._compiledEffects[name] = effect;
  7283. return effect;
  7284. };
  7285. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7286. if (uniformsNames === void 0) { uniformsNames = []; }
  7287. if (samplers === void 0) { samplers = []; }
  7288. if (defines === void 0) { defines = ""; }
  7289. return this.createEffect({
  7290. vertex: "particles",
  7291. fragmentElement: fragmentName
  7292. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7293. };
  7294. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7295. context = context || this._gl;
  7296. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7297. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7298. var shaderProgram = context.createProgram();
  7299. context.attachShader(shaderProgram, vertexShader);
  7300. context.attachShader(shaderProgram, fragmentShader);
  7301. context.linkProgram(shaderProgram);
  7302. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7303. if (!linked) {
  7304. var error = context.getProgramInfoLog(shaderProgram);
  7305. if (error) {
  7306. throw new Error(error);
  7307. }
  7308. }
  7309. context.deleteShader(vertexShader);
  7310. context.deleteShader(fragmentShader);
  7311. return shaderProgram;
  7312. };
  7313. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7314. var results = [];
  7315. for (var index = 0; index < uniformsNames.length; index++) {
  7316. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7317. }
  7318. return results;
  7319. };
  7320. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7321. var results = [];
  7322. for (var index = 0; index < attributesNames.length; index++) {
  7323. try {
  7324. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7325. }
  7326. catch (e) {
  7327. results.push(-1);
  7328. }
  7329. }
  7330. return results;
  7331. };
  7332. Engine.prototype.enableEffect = function (effect) {
  7333. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7334. if (effect && effect.onBind) {
  7335. effect.onBind(effect);
  7336. }
  7337. return;
  7338. }
  7339. // Use program
  7340. this.setProgram(effect.getProgram());
  7341. this._currentEffect = effect;
  7342. if (effect.onBind) {
  7343. effect.onBind(effect);
  7344. }
  7345. };
  7346. Engine.prototype.setIntArray = function (uniform, array) {
  7347. if (!uniform)
  7348. return;
  7349. this._gl.uniform1iv(uniform, array);
  7350. };
  7351. Engine.prototype.setIntArray2 = function (uniform, array) {
  7352. if (!uniform || array.length % 2 !== 0)
  7353. return;
  7354. this._gl.uniform2iv(uniform, array);
  7355. };
  7356. Engine.prototype.setIntArray3 = function (uniform, array) {
  7357. if (!uniform || array.length % 3 !== 0)
  7358. return;
  7359. this._gl.uniform3iv(uniform, array);
  7360. };
  7361. Engine.prototype.setIntArray4 = function (uniform, array) {
  7362. if (!uniform || array.length % 4 !== 0)
  7363. return;
  7364. this._gl.uniform4iv(uniform, array);
  7365. };
  7366. Engine.prototype.setFloatArray = function (uniform, array) {
  7367. if (!uniform)
  7368. return;
  7369. this._gl.uniform1fv(uniform, array);
  7370. };
  7371. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7372. if (!uniform || array.length % 2 !== 0)
  7373. return;
  7374. this._gl.uniform2fv(uniform, array);
  7375. };
  7376. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7377. if (!uniform || array.length % 3 !== 0)
  7378. return;
  7379. this._gl.uniform3fv(uniform, array);
  7380. };
  7381. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7382. if (!uniform || array.length % 4 !== 0)
  7383. return;
  7384. this._gl.uniform4fv(uniform, array);
  7385. };
  7386. Engine.prototype.setArray = function (uniform, array) {
  7387. if (!uniform)
  7388. return;
  7389. this._gl.uniform1fv(uniform, array);
  7390. };
  7391. Engine.prototype.setArray2 = function (uniform, array) {
  7392. if (!uniform || array.length % 2 !== 0)
  7393. return;
  7394. this._gl.uniform2fv(uniform, array);
  7395. };
  7396. Engine.prototype.setArray3 = function (uniform, array) {
  7397. if (!uniform || array.length % 3 !== 0)
  7398. return;
  7399. this._gl.uniform3fv(uniform, array);
  7400. };
  7401. Engine.prototype.setArray4 = function (uniform, array) {
  7402. if (!uniform || array.length % 4 !== 0)
  7403. return;
  7404. this._gl.uniform4fv(uniform, array);
  7405. };
  7406. Engine.prototype.setMatrices = function (uniform, matrices) {
  7407. if (!uniform)
  7408. return;
  7409. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7410. };
  7411. Engine.prototype.setMatrix = function (uniform, matrix) {
  7412. if (!uniform)
  7413. return;
  7414. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7415. };
  7416. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7417. if (!uniform)
  7418. return;
  7419. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7420. };
  7421. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7422. if (!uniform)
  7423. return;
  7424. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7425. };
  7426. Engine.prototype.setFloat = function (uniform, value) {
  7427. if (!uniform)
  7428. return;
  7429. this._gl.uniform1f(uniform, value);
  7430. };
  7431. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7432. if (!uniform)
  7433. return;
  7434. this._gl.uniform2f(uniform, x, y);
  7435. };
  7436. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7437. if (!uniform)
  7438. return;
  7439. this._gl.uniform3f(uniform, x, y, z);
  7440. };
  7441. Engine.prototype.setBool = function (uniform, bool) {
  7442. if (!uniform)
  7443. return;
  7444. this._gl.uniform1i(uniform, bool);
  7445. };
  7446. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7447. if (!uniform)
  7448. return;
  7449. this._gl.uniform4f(uniform, x, y, z, w);
  7450. };
  7451. Engine.prototype.setColor3 = function (uniform, color3) {
  7452. if (!uniform)
  7453. return;
  7454. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7455. };
  7456. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7457. if (!uniform)
  7458. return;
  7459. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7460. };
  7461. // States
  7462. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7463. if (zOffset === void 0) { zOffset = 0; }
  7464. if (reverseSide === void 0) { reverseSide = false; }
  7465. // Culling
  7466. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7467. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7468. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7469. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7470. if (culling) {
  7471. this._depthCullingState.cullFace = cullFace;
  7472. this._depthCullingState.cull = true;
  7473. }
  7474. else {
  7475. this._depthCullingState.cull = false;
  7476. }
  7477. }
  7478. // Z offset
  7479. this._depthCullingState.zOffset = zOffset;
  7480. };
  7481. Engine.prototype.setDepthBuffer = function (enable) {
  7482. this._depthCullingState.depthTest = enable;
  7483. };
  7484. Engine.prototype.getDepthWrite = function () {
  7485. return this._depthCullingState.depthMask;
  7486. };
  7487. Engine.prototype.setDepthWrite = function (enable) {
  7488. this._depthCullingState.depthMask = enable;
  7489. };
  7490. Engine.prototype.setColorWrite = function (enable) {
  7491. this._gl.colorMask(enable, enable, enable, enable);
  7492. };
  7493. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7494. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7495. if (this._alphaMode === mode) {
  7496. return;
  7497. }
  7498. switch (mode) {
  7499. case Engine.ALPHA_DISABLE:
  7500. this._alphaState.alphaBlend = false;
  7501. break;
  7502. case Engine.ALPHA_COMBINE:
  7503. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7504. this._alphaState.alphaBlend = true;
  7505. break;
  7506. case Engine.ALPHA_ONEONE:
  7507. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7508. this._alphaState.alphaBlend = true;
  7509. break;
  7510. case Engine.ALPHA_ADD:
  7511. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7512. this._alphaState.alphaBlend = true;
  7513. break;
  7514. case Engine.ALPHA_SUBTRACT:
  7515. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7516. this._alphaState.alphaBlend = true;
  7517. break;
  7518. case Engine.ALPHA_MULTIPLY:
  7519. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7520. this._alphaState.alphaBlend = true;
  7521. break;
  7522. case Engine.ALPHA_MAXIMIZED:
  7523. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7524. this._alphaState.alphaBlend = true;
  7525. break;
  7526. }
  7527. if (!noDepthWriteChange) {
  7528. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7529. }
  7530. this._alphaMode = mode;
  7531. };
  7532. Engine.prototype.getAlphaMode = function () {
  7533. return this._alphaMode;
  7534. };
  7535. Engine.prototype.setAlphaTesting = function (enable) {
  7536. this._alphaTest = enable;
  7537. };
  7538. Engine.prototype.getAlphaTesting = function () {
  7539. return this._alphaTest;
  7540. };
  7541. // Textures
  7542. Engine.prototype.wipeCaches = function () {
  7543. this.resetTextureCache();
  7544. this._currentEffect = null;
  7545. this._stencilState.reset();
  7546. this._depthCullingState.reset();
  7547. this.setDepthFunctionToLessOrEqual();
  7548. this._alphaState.reset();
  7549. this._cachedVertexBuffers = null;
  7550. this._cachedIndexBuffer = null;
  7551. this._cachedEffectForVertexBuffers = null;
  7552. };
  7553. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7554. var gl = this._gl;
  7555. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7556. var magFilter = gl.NEAREST;
  7557. var minFilter = gl.NEAREST;
  7558. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7559. magFilter = gl.LINEAR;
  7560. minFilter = gl.LINEAR;
  7561. }
  7562. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7563. magFilter = gl.LINEAR;
  7564. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7565. }
  7566. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7567. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7568. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7569. texture.samplingMode = samplingMode;
  7570. };
  7571. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7572. var _this = this;
  7573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7574. if (onLoad === void 0) { onLoad = null; }
  7575. if (onError === void 0) { onError = null; }
  7576. if (buffer === void 0) { buffer = null; }
  7577. var texture = this._gl.createTexture();
  7578. var extension;
  7579. var fromData = false;
  7580. if (url.substr(0, 5) === "data:") {
  7581. fromData = true;
  7582. }
  7583. if (!fromData)
  7584. extension = url.substr(url.length - 4, 4).toLowerCase();
  7585. else {
  7586. var oldUrl = url;
  7587. fromData = oldUrl.split(':');
  7588. url = oldUrl;
  7589. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7590. }
  7591. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7592. var isTGA = (extension === ".tga");
  7593. scene._addPendingData(texture);
  7594. texture.url = url;
  7595. texture.noMipmap = noMipmap;
  7596. texture.references = 1;
  7597. texture.samplingMode = samplingMode;
  7598. texture.onLoadedCallbacks = [onLoad];
  7599. this._loadedTexturesCache.push(texture);
  7600. var onerror = function () {
  7601. scene._removePendingData(texture);
  7602. if (onError) {
  7603. onError();
  7604. }
  7605. };
  7606. var callback;
  7607. if (isTGA) {
  7608. callback = function (arrayBuffer) {
  7609. var data = new Uint8Array(arrayBuffer);
  7610. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7611. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7612. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7613. }, samplingMode);
  7614. };
  7615. if (!(fromData instanceof Array))
  7616. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7617. callback(arrayBuffer);
  7618. }, null, scene.database, true, onerror);
  7619. else
  7620. callback(buffer);
  7621. }
  7622. else if (isDDS) {
  7623. callback = function (data) {
  7624. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7625. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7626. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7627. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7628. }, samplingMode);
  7629. };
  7630. if (!(fromData instanceof Array))
  7631. BABYLON.Tools.LoadFile(url, function (data) {
  7632. callback(data);
  7633. }, null, scene.database, true, onerror);
  7634. else
  7635. callback(buffer);
  7636. }
  7637. else {
  7638. var onload = function (img) {
  7639. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7640. var isPot = (img.width === potWidth && img.height === potHeight);
  7641. if (!isPot) {
  7642. _this._prepareWorkingCanvas();
  7643. _this._workingCanvas.width = potWidth;
  7644. _this._workingCanvas.height = potHeight;
  7645. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7646. _this._workingContext.imageSmoothingEnabled = false;
  7647. _this._workingContext.mozImageSmoothingEnabled = false;
  7648. _this._workingContext.oImageSmoothingEnabled = false;
  7649. _this._workingContext.webkitImageSmoothingEnabled = false;
  7650. _this._workingContext.msImageSmoothingEnabled = false;
  7651. }
  7652. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7653. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7654. _this._workingContext.imageSmoothingEnabled = true;
  7655. _this._workingContext.mozImageSmoothingEnabled = true;
  7656. _this._workingContext.oImageSmoothingEnabled = true;
  7657. _this._workingContext.webkitImageSmoothingEnabled = true;
  7658. _this._workingContext.msImageSmoothingEnabled = true;
  7659. }
  7660. }
  7661. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7662. }, samplingMode);
  7663. };
  7664. if (!(fromData instanceof Array))
  7665. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7666. else
  7667. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7668. }
  7669. return texture;
  7670. };
  7671. Engine.prototype._getInternalFormat = function (format) {
  7672. var internalFormat = this._gl.RGBA;
  7673. switch (format) {
  7674. case Engine.TEXTUREFORMAT_ALPHA:
  7675. internalFormat = this._gl.ALPHA;
  7676. break;
  7677. case Engine.TEXTUREFORMAT_LUMINANCE:
  7678. internalFormat = this._gl.LUMINANCE;
  7679. break;
  7680. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7681. internalFormat = this._gl.LUMINANCE_ALPHA;
  7682. break;
  7683. case Engine.TEXTUREFORMAT_RGB:
  7684. internalFormat = this._gl.RGB;
  7685. break;
  7686. case Engine.TEXTUREFORMAT_RGBA:
  7687. internalFormat = this._gl.RGBA;
  7688. break;
  7689. }
  7690. return internalFormat;
  7691. };
  7692. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7693. if (compression === void 0) { compression = null; }
  7694. var internalFormat = this._getInternalFormat(format);
  7695. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7696. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7697. if (texture._width % 4 !== 0) {
  7698. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7699. }
  7700. if (compression) {
  7701. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7702. }
  7703. else {
  7704. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7705. }
  7706. if (texture.generateMipMaps) {
  7707. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7708. }
  7709. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7710. this.resetTextureCache();
  7711. texture.isReady = true;
  7712. };
  7713. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7714. if (compression === void 0) { compression = null; }
  7715. var texture = this._gl.createTexture();
  7716. texture._baseWidth = width;
  7717. texture._baseHeight = height;
  7718. texture._width = width;
  7719. texture._height = height;
  7720. texture.references = 1;
  7721. this.updateRawTexture(texture, data, format, invertY, compression);
  7722. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7723. // Filters
  7724. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7725. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7726. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7727. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7728. texture.samplingMode = samplingMode;
  7729. this._loadedTexturesCache.push(texture);
  7730. return texture;
  7731. };
  7732. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7733. var texture = this._gl.createTexture();
  7734. texture._baseWidth = width;
  7735. texture._baseHeight = height;
  7736. if (generateMipMaps) {
  7737. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7738. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7739. }
  7740. this.resetTextureCache();
  7741. texture._width = width;
  7742. texture._height = height;
  7743. texture.isReady = false;
  7744. texture.generateMipMaps = generateMipMaps;
  7745. texture.references = 1;
  7746. texture.samplingMode = samplingMode;
  7747. this.updateTextureSamplingMode(samplingMode, texture);
  7748. this._loadedTexturesCache.push(texture);
  7749. return texture;
  7750. };
  7751. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7752. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7753. if (texture.isCube) {
  7754. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7755. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7756. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7757. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7758. }
  7759. else {
  7760. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7761. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7762. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7763. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7764. }
  7765. };
  7766. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7767. if (premulAlpha === void 0) { premulAlpha = false; }
  7768. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7769. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7770. if (premulAlpha) {
  7771. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7772. }
  7773. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7774. if (texture.generateMipMaps) {
  7775. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7776. }
  7777. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7778. this.resetTextureCache();
  7779. texture.isReady = true;
  7780. };
  7781. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7782. if (texture._isDisabled) {
  7783. return;
  7784. }
  7785. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7786. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7787. try {
  7788. // Testing video texture support
  7789. if (this._videoTextureSupported === undefined) {
  7790. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7791. if (this._gl.getError() !== 0) {
  7792. this._videoTextureSupported = false;
  7793. }
  7794. else {
  7795. this._videoTextureSupported = true;
  7796. }
  7797. }
  7798. // Copy video through the current working canvas if video texture is not supported
  7799. if (!this._videoTextureSupported) {
  7800. if (!texture._workingCanvas) {
  7801. texture._workingCanvas = document.createElement("canvas");
  7802. texture._workingContext = texture._workingCanvas.getContext("2d");
  7803. texture._workingCanvas.width = texture._width;
  7804. texture._workingCanvas.height = texture._height;
  7805. }
  7806. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7807. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7808. }
  7809. else {
  7810. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7811. }
  7812. if (texture.generateMipMaps) {
  7813. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7814. }
  7815. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7816. this.resetTextureCache();
  7817. texture.isReady = true;
  7818. }
  7819. catch (ex) {
  7820. // Something unexpected
  7821. // Let's disable the texture
  7822. texture._isDisabled = true;
  7823. }
  7824. };
  7825. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7826. // old version had a "generateMipMaps" arg instead of options.
  7827. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7828. // in the same way, generateDepthBuffer is defaulted to true
  7829. var generateMipMaps = false;
  7830. var generateDepthBuffer = true;
  7831. var generateStencilBuffer = false;
  7832. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7833. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7834. if (options !== undefined) {
  7835. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7836. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7837. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  7838. type = options.type === undefined ? type : options.type;
  7839. if (options.samplingMode !== undefined) {
  7840. samplingMode = options.samplingMode;
  7841. }
  7842. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  7843. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7844. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7845. }
  7846. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  7847. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  7848. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7849. }
  7850. }
  7851. var gl = this._gl;
  7852. var texture = gl.createTexture();
  7853. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7854. var width = size.width || size;
  7855. var height = size.height || size;
  7856. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7857. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7858. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7859. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7860. }
  7861. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7862. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7863. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7864. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7865. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7866. var depthStencilBuffer;
  7867. // Create the depth/stencil buffer
  7868. if (generateStencilBuffer) {
  7869. depthStencilBuffer = gl.createRenderbuffer();
  7870. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7871. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  7872. }
  7873. else if (generateDepthBuffer) {
  7874. depthStencilBuffer = gl.createRenderbuffer();
  7875. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7876. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7877. }
  7878. // Create the framebuffer
  7879. var framebuffer = gl.createFramebuffer();
  7880. this.bindUnboundFramebuffer(framebuffer);
  7881. // Manage attachments
  7882. if (generateStencilBuffer) {
  7883. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7884. }
  7885. else if (generateDepthBuffer) {
  7886. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7887. }
  7888. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  7889. if (generateMipMaps) {
  7890. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7891. }
  7892. // Unbind
  7893. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7894. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7895. this.bindUnboundFramebuffer(null);
  7896. texture._framebuffer = framebuffer;
  7897. if (generateDepthBuffer) {
  7898. texture._depthBuffer = depthStencilBuffer;
  7899. }
  7900. texture._baseWidth = width;
  7901. texture._baseHeight = height;
  7902. texture._width = width;
  7903. texture._height = height;
  7904. texture.isReady = true;
  7905. texture.generateMipMaps = generateMipMaps;
  7906. texture.references = 1;
  7907. texture.samplingMode = samplingMode;
  7908. texture.type = type;
  7909. this.resetTextureCache();
  7910. this._loadedTexturesCache.push(texture);
  7911. return texture;
  7912. };
  7913. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7914. var gl = this._gl;
  7915. var texture = gl.createTexture();
  7916. var generateMipMaps = true;
  7917. var generateDepthBuffer = true;
  7918. var generateStencilBuffer = false;
  7919. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7920. if (options !== undefined) {
  7921. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7922. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7923. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  7924. if (options.samplingMode !== undefined) {
  7925. samplingMode = options.samplingMode;
  7926. }
  7927. }
  7928. texture.isCube = true;
  7929. texture.references = 1;
  7930. texture.generateMipMaps = generateMipMaps;
  7931. texture.references = 1;
  7932. texture.samplingMode = samplingMode;
  7933. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7934. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7935. for (var face = 0; face < 6; face++) {
  7936. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7937. }
  7938. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7939. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7940. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7941. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7942. // Create the depth buffer
  7943. var depthStencilBuffer;
  7944. // Create the depth/stencil buffer
  7945. if (generateStencilBuffer) {
  7946. depthStencilBuffer = gl.createRenderbuffer();
  7947. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7948. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  7949. }
  7950. else if (generateDepthBuffer) {
  7951. depthStencilBuffer = gl.createRenderbuffer();
  7952. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7953. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7954. }
  7955. // Create the framebuffer
  7956. var framebuffer = gl.createFramebuffer();
  7957. this.bindUnboundFramebuffer(framebuffer);
  7958. // Manage attachments
  7959. if (generateStencilBuffer) {
  7960. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7961. }
  7962. else if (generateDepthBuffer) {
  7963. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7964. }
  7965. // Mipmaps
  7966. if (texture.generateMipMaps) {
  7967. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7968. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7969. }
  7970. // Unbind
  7971. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7972. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7973. this.bindUnboundFramebuffer(null);
  7974. texture._framebuffer = framebuffer;
  7975. if (generateDepthBuffer) {
  7976. texture._depthBuffer = depthStencilBuffer;
  7977. }
  7978. texture._width = size;
  7979. texture._height = size;
  7980. texture.isReady = true;
  7981. this.resetTextureCache();
  7982. this._loadedTexturesCache.push(texture);
  7983. return texture;
  7984. };
  7985. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7986. var _this = this;
  7987. var gl = this._gl;
  7988. var texture = gl.createTexture();
  7989. texture.isCube = true;
  7990. texture.url = rootUrl;
  7991. texture.references = 1;
  7992. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7993. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7994. if (isDDS) {
  7995. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7996. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7997. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7998. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7999. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8000. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8001. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8002. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8003. }
  8004. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8005. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8006. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8007. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8008. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8009. _this.resetTextureCache();
  8010. texture._width = info.width;
  8011. texture._height = info.height;
  8012. texture.isReady = true;
  8013. }, null, null, true);
  8014. }
  8015. else {
  8016. cascadeLoad(rootUrl, scene, function (imgs) {
  8017. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8018. var height = width;
  8019. _this._prepareWorkingCanvas();
  8020. _this._workingCanvas.width = width;
  8021. _this._workingCanvas.height = height;
  8022. var faces = [
  8023. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8024. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8025. ];
  8026. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8027. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8028. for (var index = 0; index < faces.length; index++) {
  8029. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8030. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8031. }
  8032. if (!noMipmap) {
  8033. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8034. }
  8035. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8036. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8037. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8038. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8039. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8040. _this.resetTextureCache();
  8041. texture._width = width;
  8042. texture._height = height;
  8043. texture.isReady = true;
  8044. }, files);
  8045. }
  8046. this._loadedTexturesCache.push(texture);
  8047. return texture;
  8048. };
  8049. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8050. texture._width = width;
  8051. texture._height = height;
  8052. texture._size = width * height;
  8053. texture._baseWidth = width;
  8054. texture._baseHeight = height;
  8055. };
  8056. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8057. var _this = this;
  8058. var gl = this._gl;
  8059. var texture = gl.createTexture();
  8060. scene._addPendingData(texture);
  8061. texture.isCube = true;
  8062. texture.references = 1;
  8063. texture.url = url;
  8064. var internalFormat = this._getInternalFormat(format);
  8065. var textureType = gl.UNSIGNED_BYTE;
  8066. if (type === Engine.TEXTURETYPE_FLOAT) {
  8067. textureType = gl.FLOAT;
  8068. }
  8069. var width = size;
  8070. var height = width;
  8071. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8072. texture._width = width;
  8073. texture._height = height;
  8074. var onerror = function () {
  8075. scene._removePendingData(texture);
  8076. };
  8077. var internalCallback = function (data) {
  8078. var rgbeDataArrays = callback(data);
  8079. var facesIndex = [
  8080. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8081. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8082. ];
  8083. width = texture._width;
  8084. height = texture._height;
  8085. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8086. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8087. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8088. if (!noMipmap && isPot) {
  8089. if (mipmmapGenerator) {
  8090. var arrayTemp = [];
  8091. // Data are known to be in +X +Y +Z -X -Y -Z
  8092. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8093. arrayTemp.push(rgbeDataArrays[0]); // +X
  8094. arrayTemp.push(rgbeDataArrays[3]); // -X
  8095. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8096. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8097. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8098. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8099. var mipData = mipmmapGenerator(arrayTemp);
  8100. for (var level = 0; level < mipData.length; level++) {
  8101. var mipSize = width >> level;
  8102. // mipData is order in +X -X +Y -Y +Z -Z
  8103. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8104. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8105. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8106. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8107. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8108. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8109. }
  8110. }
  8111. else {
  8112. // Data are known to be in +X +Y +Z -X -Y -Z
  8113. for (var index = 0; index < facesIndex.length; index++) {
  8114. var faceData = rgbeDataArrays[index];
  8115. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8116. }
  8117. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8118. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8119. // By following the webgl standard changes from Revision 7, 2014/11/24
  8120. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8121. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8122. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8123. // Data are known to be in +X +Y +Z -X -Y -Z
  8124. for (var index = 0; index < facesIndex.length; index++) {
  8125. var faceData = rgbeDataArrays[index];
  8126. // Create a new RGBA Face.
  8127. var newFaceData = new Float32Array(width * height * 4);
  8128. for (var x = 0; x < width; x++) {
  8129. for (var y = 0; y < height; y++) {
  8130. var index_1 = (y * width + x) * 3;
  8131. var newIndex = (y * width + x) * 4;
  8132. // Map Old Value to new value.
  8133. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8134. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8135. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8136. // Add fully opaque alpha channel.
  8137. newFaceData[newIndex + 3] = 1;
  8138. }
  8139. }
  8140. // Reupload the face.
  8141. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8142. }
  8143. // Try to generate mipmap again.
  8144. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8145. }
  8146. }
  8147. }
  8148. else {
  8149. noMipmap = true;
  8150. }
  8151. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8152. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8153. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8154. }
  8155. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8156. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8157. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8158. }
  8159. else {
  8160. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8161. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8162. }
  8163. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8164. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8165. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8166. texture.isReady = true;
  8167. _this.resetTextureCache();
  8168. scene._removePendingData(texture);
  8169. };
  8170. BABYLON.Tools.LoadFile(url, function (data) {
  8171. internalCallback(data);
  8172. }, onerror, scene.database, true);
  8173. return texture;
  8174. };
  8175. ;
  8176. Engine.prototype._releaseTexture = function (texture) {
  8177. var gl = this._gl;
  8178. if (texture._framebuffer) {
  8179. gl.deleteFramebuffer(texture._framebuffer);
  8180. }
  8181. if (texture._depthBuffer) {
  8182. gl.deleteRenderbuffer(texture._depthBuffer);
  8183. }
  8184. gl.deleteTexture(texture);
  8185. // Unbind channels
  8186. this.unbindAllTextures();
  8187. var index = this._loadedTexturesCache.indexOf(texture);
  8188. if (index !== -1) {
  8189. this._loadedTexturesCache.splice(index, 1);
  8190. }
  8191. };
  8192. Engine.prototype.setProgram = function (program) {
  8193. if (this._currentProgram !== program) {
  8194. this._gl.useProgram(program);
  8195. this._currentProgram = program;
  8196. }
  8197. };
  8198. Engine.prototype.bindSamplers = function (effect) {
  8199. this.setProgram(effect.getProgram());
  8200. var samplers = effect.getSamplers();
  8201. for (var index = 0; index < samplers.length; index++) {
  8202. var uniform = effect.getUniform(samplers[index]);
  8203. this._gl.uniform1i(uniform, index);
  8204. }
  8205. this._currentEffect = null;
  8206. };
  8207. Engine.prototype.activateTexture = function (texture) {
  8208. if (this._activeTexture !== texture) {
  8209. this._gl.activeTexture(texture);
  8210. this._activeTexture = texture;
  8211. }
  8212. };
  8213. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8214. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8215. this._gl.bindTexture(target, texture);
  8216. this._activeTexturesCache[this._activeTexture] = texture;
  8217. }
  8218. };
  8219. Engine.prototype._bindTexture = function (channel, texture) {
  8220. if (channel < 0) {
  8221. return;
  8222. }
  8223. this.activateTexture(this._gl["TEXTURE" + channel]);
  8224. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8225. };
  8226. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8227. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8228. };
  8229. Engine.prototype.unbindAllTextures = function () {
  8230. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8231. this.activateTexture(this._gl["TEXTURE" + channel]);
  8232. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8233. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8234. }
  8235. };
  8236. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8237. if (channel < 0) {
  8238. return;
  8239. }
  8240. this._gl.uniform1i(uniform, channel);
  8241. this._setTexture(channel, texture);
  8242. };
  8243. Engine.prototype._setTexture = function (channel, texture) {
  8244. // Not ready?
  8245. if (!texture || !texture.isReady()) {
  8246. if (this._activeTexturesCache[channel] != null) {
  8247. this.activateTexture(this._gl["TEXTURE" + channel]);
  8248. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8249. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8250. }
  8251. return;
  8252. }
  8253. // Video
  8254. var alreadyActivated = false;
  8255. if (texture instanceof BABYLON.VideoTexture) {
  8256. this.activateTexture(this._gl["TEXTURE" + channel]);
  8257. alreadyActivated = true;
  8258. texture.update();
  8259. }
  8260. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8261. texture.delayLoad();
  8262. return;
  8263. }
  8264. var internalTexture = texture.getInternalTexture();
  8265. if (this._activeTexturesCache[channel] === internalTexture) {
  8266. return;
  8267. }
  8268. if (!alreadyActivated) {
  8269. this.activateTexture(this._gl["TEXTURE" + channel]);
  8270. }
  8271. if (internalTexture.isCube) {
  8272. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8273. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8274. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8275. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8276. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8277. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8278. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8279. }
  8280. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8281. }
  8282. else {
  8283. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8284. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8285. internalTexture._cachedWrapU = texture.wrapU;
  8286. switch (texture.wrapU) {
  8287. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8288. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8289. break;
  8290. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8291. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8292. break;
  8293. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8294. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8295. break;
  8296. }
  8297. }
  8298. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8299. internalTexture._cachedWrapV = texture.wrapV;
  8300. switch (texture.wrapV) {
  8301. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8302. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8303. break;
  8304. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8305. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8306. break;
  8307. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8308. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8309. break;
  8310. }
  8311. }
  8312. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8313. }
  8314. };
  8315. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8316. if (channel < 0) {
  8317. return;
  8318. }
  8319. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8320. this._textureUnits = new Int32Array(textures.length);
  8321. }
  8322. for (var i = 0; i < textures.length; i++) {
  8323. this._textureUnits[i] = channel + i;
  8324. }
  8325. this._gl.uniform1iv(uniform, this._textureUnits);
  8326. for (var index = 0; index < textures.length; index++) {
  8327. this._setTexture(channel + index, textures[index]);
  8328. }
  8329. };
  8330. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8331. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8332. var value = texture.anisotropicFilteringLevel;
  8333. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8334. value = 1;
  8335. }
  8336. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8337. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8338. texture._cachedAnisotropicFilteringLevel = value;
  8339. }
  8340. };
  8341. Engine.prototype.readPixels = function (x, y, width, height) {
  8342. var data = new Uint8Array(height * width * 4);
  8343. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8344. return data;
  8345. };
  8346. /**
  8347. * Add an externaly attached data from its key.
  8348. * This method call will fail and return false, if such key already exists.
  8349. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8350. * @param key the unique key that identifies the data
  8351. * @param data the data object to associate to the key for this Engine instance
  8352. * @return true if no such key were already present and the data was added successfully, false otherwise
  8353. */
  8354. Engine.prototype.addExternalData = function (key, data) {
  8355. return this._externalData.add(key, data);
  8356. };
  8357. /**
  8358. * Get an externaly attached data from its key
  8359. * @param key the unique key that identifies the data
  8360. * @return the associated data, if present (can be null), or undefined if not present
  8361. */
  8362. Engine.prototype.getExternalData = function (key) {
  8363. return this._externalData.get(key);
  8364. };
  8365. /**
  8366. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8367. * @param key the unique key that identifies the data
  8368. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8369. * @return the associated data, can be null if the factory returned null.
  8370. */
  8371. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8372. return this._externalData.getOrAddWithFactory(key, factory);
  8373. };
  8374. /**
  8375. * Remove an externaly attached data from the Engine instance
  8376. * @param key the unique key that identifies the data
  8377. * @return true if the data was successfully removed, false if it doesn't exist
  8378. */
  8379. Engine.prototype.removeExternalData = function (key) {
  8380. return this._externalData.remove(key);
  8381. };
  8382. Engine.prototype.releaseInternalTexture = function (texture) {
  8383. if (!texture) {
  8384. return;
  8385. }
  8386. texture.references--;
  8387. // Final reference ?
  8388. if (texture.references === 0) {
  8389. var texturesCache = this.getLoadedTexturesCache();
  8390. var index = texturesCache.indexOf(texture);
  8391. if (index > -1) {
  8392. texturesCache.splice(index, 1);
  8393. }
  8394. this._releaseTexture(texture);
  8395. }
  8396. };
  8397. // Dispose
  8398. Engine.prototype.dispose = function () {
  8399. this.hideLoadingUI();
  8400. this.stopRenderLoop();
  8401. // Release scenes
  8402. while (this.scenes.length) {
  8403. this.scenes[0].dispose();
  8404. }
  8405. // Release audio engine
  8406. Engine.audioEngine.dispose();
  8407. // Release effects
  8408. for (var name in this._compiledEffects) {
  8409. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8410. }
  8411. // Unbind
  8412. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8413. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8414. continue;
  8415. }
  8416. this._gl.disableVertexAttribArray(i);
  8417. }
  8418. this._gl = null;
  8419. //WebVR
  8420. this.disableVR();
  8421. // Events
  8422. window.removeEventListener("blur", this._onBlur);
  8423. window.removeEventListener("focus", this._onFocus);
  8424. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8425. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8426. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8427. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8428. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8429. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8430. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8431. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8432. };
  8433. // Loading screen
  8434. Engine.prototype.displayLoadingUI = function () {
  8435. this._loadingScreen.displayLoadingUI();
  8436. };
  8437. Engine.prototype.hideLoadingUI = function () {
  8438. this._loadingScreen.hideLoadingUI();
  8439. };
  8440. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8441. get: function () {
  8442. return this._loadingScreen;
  8443. },
  8444. set: function (loadingScreen) {
  8445. this._loadingScreen = loadingScreen;
  8446. },
  8447. enumerable: true,
  8448. configurable: true
  8449. });
  8450. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8451. set: function (text) {
  8452. this._loadingScreen.loadingUIText = text;
  8453. },
  8454. enumerable: true,
  8455. configurable: true
  8456. });
  8457. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8458. set: function (color) {
  8459. this._loadingScreen.loadingUIBackgroundColor = color;
  8460. },
  8461. enumerable: true,
  8462. configurable: true
  8463. });
  8464. Engine.prototype.attachContextLostEvent = function (callback) {
  8465. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8466. };
  8467. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8468. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8469. };
  8470. // FPS
  8471. Engine.prototype.getFps = function () {
  8472. return this.fps;
  8473. };
  8474. Engine.prototype.getDeltaTime = function () {
  8475. return this.deltaTime;
  8476. };
  8477. Engine.prototype._measureFps = function () {
  8478. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8479. var length = this.previousFramesDuration.length;
  8480. if (length >= 2) {
  8481. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8482. }
  8483. if (length >= this.fpsRange) {
  8484. if (length > this.fpsRange) {
  8485. this.previousFramesDuration.splice(0, 1);
  8486. length = this.previousFramesDuration.length;
  8487. }
  8488. var sum = 0;
  8489. for (var id = 0; id < length - 1; id++) {
  8490. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8491. }
  8492. this.fps = 1000.0 / (sum / (length - 1));
  8493. }
  8494. };
  8495. Engine.prototype._canRenderToFloatTexture = function () {
  8496. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8497. };
  8498. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8499. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8500. };
  8501. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8502. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8503. var tempcanvas = document.createElement("canvas");
  8504. tempcanvas.height = 16;
  8505. tempcanvas.width = 16;
  8506. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8507. // extension.
  8508. var ext = gl.getExtension(extension);
  8509. if (!ext) {
  8510. return false;
  8511. }
  8512. // setup GLSL program
  8513. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8514. 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 }";
  8515. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8516. gl.useProgram(program);
  8517. // look up where the vertex data needs to go.
  8518. var positionLocation = gl.getAttribLocation(program, "a_position");
  8519. var colorLoc = gl.getUniformLocation(program, "u_color");
  8520. // provide texture coordinates for the rectangle.
  8521. var positionBuffer = gl.createBuffer();
  8522. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8523. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8524. -1.0, -1.0,
  8525. 1.0, -1.0,
  8526. -1.0, 1.0,
  8527. -1.0, 1.0,
  8528. 1.0, -1.0,
  8529. 1.0, 1.0]), gl.STATIC_DRAW);
  8530. gl.enableVertexAttribArray(positionLocation);
  8531. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8532. var whiteTex = gl.createTexture();
  8533. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8534. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8535. var tex = gl.createTexture();
  8536. gl.bindTexture(gl.TEXTURE_2D, tex);
  8537. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8538. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8539. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8540. var fb = gl.createFramebuffer();
  8541. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8542. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8543. var cleanup = function () {
  8544. gl.deleteProgram(program);
  8545. gl.disableVertexAttribArray(positionLocation);
  8546. gl.deleteBuffer(positionBuffer);
  8547. gl.deleteFramebuffer(fb);
  8548. gl.deleteTexture(whiteTex);
  8549. gl.deleteTexture(tex);
  8550. };
  8551. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8552. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8553. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8554. cleanup();
  8555. return false;
  8556. }
  8557. // Draw the rectangle.
  8558. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8559. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8560. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8561. gl.bindTexture(gl.TEXTURE_2D, tex);
  8562. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8563. gl.clearColor(1, 0, 0, 1);
  8564. gl.clear(gl.COLOR_BUFFER_BIT);
  8565. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8566. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8567. var pixel = new Uint8Array(4);
  8568. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8569. if (pixel[0] !== 0 ||
  8570. pixel[1] < 248 ||
  8571. pixel[2] < 248 ||
  8572. pixel[3] < 254) {
  8573. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8574. cleanup();
  8575. return false;
  8576. }
  8577. // Succesfully rendered to "format" texture.
  8578. cleanup();
  8579. return true;
  8580. };
  8581. // Statics
  8582. Engine.isSupported = function () {
  8583. try {
  8584. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8585. if (navigator.isCocoonJS) {
  8586. return true;
  8587. }
  8588. var tempcanvas = document.createElement("canvas");
  8589. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8590. return gl != null && !!window.WebGLRenderingContext;
  8591. }
  8592. catch (e) {
  8593. return false;
  8594. }
  8595. };
  8596. // Const statics
  8597. Engine._ALPHA_DISABLE = 0;
  8598. Engine._ALPHA_ADD = 1;
  8599. Engine._ALPHA_COMBINE = 2;
  8600. Engine._ALPHA_SUBTRACT = 3;
  8601. Engine._ALPHA_MULTIPLY = 4;
  8602. Engine._ALPHA_MAXIMIZED = 5;
  8603. Engine._ALPHA_ONEONE = 6;
  8604. Engine._DELAYLOADSTATE_NONE = 0;
  8605. Engine._DELAYLOADSTATE_LOADED = 1;
  8606. Engine._DELAYLOADSTATE_LOADING = 2;
  8607. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8608. Engine._TEXTUREFORMAT_ALPHA = 0;
  8609. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8610. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8611. Engine._TEXTUREFORMAT_RGB = 4;
  8612. Engine._TEXTUREFORMAT_RGBA = 5;
  8613. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8614. Engine._TEXTURETYPE_FLOAT = 1;
  8615. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8616. // Updatable statics so stick with vars here
  8617. Engine.CollisionsEpsilon = 0.001;
  8618. Engine.CodeRepository = "src/";
  8619. Engine.ShadersRepository = "src/Shaders/";
  8620. return Engine;
  8621. })();
  8622. BABYLON.Engine = Engine;
  8623. })(BABYLON || (BABYLON = {}));
  8624. var BABYLON;
  8625. (function (BABYLON) {
  8626. /**
  8627. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8628. */
  8629. var Node = (function () {
  8630. /**
  8631. * @constructor
  8632. * @param {string} name - the name and id to be given to this node
  8633. * @param {BABYLON.Scene} the scene this node will be added to
  8634. */
  8635. function Node(name, scene) {
  8636. this.state = "";
  8637. this.animations = new Array();
  8638. this._ranges = {};
  8639. this._childrenFlag = -1;
  8640. this._isEnabled = true;
  8641. this._isReady = true;
  8642. this._currentRenderId = -1;
  8643. this._parentRenderId = -1;
  8644. this.name = name;
  8645. this.id = name;
  8646. this._scene = scene;
  8647. this._initCache();
  8648. }
  8649. Object.defineProperty(Node.prototype, "parent", {
  8650. get: function () {
  8651. return this._parentNode;
  8652. },
  8653. set: function (parent) {
  8654. if (this._parentNode === parent) {
  8655. return;
  8656. }
  8657. if (this._parentNode) {
  8658. var index = this._parentNode._children.indexOf(this);
  8659. if (index !== -1) {
  8660. this._parentNode._children.splice(index, 1);
  8661. }
  8662. }
  8663. this._parentNode = parent;
  8664. if (this._parentNode) {
  8665. if (!this._parentNode._children) {
  8666. this._parentNode._children = new Array();
  8667. }
  8668. this._parentNode._children.push(this);
  8669. }
  8670. },
  8671. enumerable: true,
  8672. configurable: true
  8673. });
  8674. Node.prototype.getScene = function () {
  8675. return this._scene;
  8676. };
  8677. Node.prototype.getEngine = function () {
  8678. return this._scene.getEngine();
  8679. };
  8680. // override it in derived class
  8681. Node.prototype.getWorldMatrix = function () {
  8682. return BABYLON.Matrix.Identity();
  8683. };
  8684. // override it in derived class if you add new variables to the cache
  8685. // and call the parent class method
  8686. Node.prototype._initCache = function () {
  8687. this._cache = {};
  8688. this._cache.parent = undefined;
  8689. };
  8690. Node.prototype.updateCache = function (force) {
  8691. if (!force && this.isSynchronized())
  8692. return;
  8693. this._cache.parent = this.parent;
  8694. this._updateCache();
  8695. };
  8696. // override it in derived class if you add new variables to the cache
  8697. // and call the parent class method if !ignoreParentClass
  8698. Node.prototype._updateCache = function (ignoreParentClass) {
  8699. };
  8700. // override it in derived class if you add new variables to the cache
  8701. Node.prototype._isSynchronized = function () {
  8702. return true;
  8703. };
  8704. Node.prototype._markSyncedWithParent = function () {
  8705. this._parentRenderId = this.parent._currentRenderId;
  8706. };
  8707. Node.prototype.isSynchronizedWithParent = function () {
  8708. if (!this.parent) {
  8709. return true;
  8710. }
  8711. if (this._parentRenderId !== this.parent._currentRenderId) {
  8712. return false;
  8713. }
  8714. return this.parent.isSynchronized();
  8715. };
  8716. Node.prototype.isSynchronized = function (updateCache) {
  8717. var check = this.hasNewParent();
  8718. check = check || !this.isSynchronizedWithParent();
  8719. check = check || !this._isSynchronized();
  8720. if (updateCache)
  8721. this.updateCache(true);
  8722. return !check;
  8723. };
  8724. Node.prototype.hasNewParent = function (update) {
  8725. if (this._cache.parent === this.parent)
  8726. return false;
  8727. if (update)
  8728. this._cache.parent = this.parent;
  8729. return true;
  8730. };
  8731. /**
  8732. * Is this node ready to be used/rendered
  8733. * @return {boolean} is it ready
  8734. */
  8735. Node.prototype.isReady = function () {
  8736. return this._isReady;
  8737. };
  8738. /**
  8739. * Is this node enabled.
  8740. * If the node has a parent and is enabled, the parent will be inspected as well.
  8741. * @return {boolean} whether this node (and its parent) is enabled.
  8742. * @see setEnabled
  8743. */
  8744. Node.prototype.isEnabled = function () {
  8745. if (!this._isEnabled) {
  8746. return false;
  8747. }
  8748. if (this.parent) {
  8749. return this.parent.isEnabled();
  8750. }
  8751. return true;
  8752. };
  8753. /**
  8754. * Set the enabled state of this node.
  8755. * @param {boolean} value - the new enabled state
  8756. * @see isEnabled
  8757. */
  8758. Node.prototype.setEnabled = function (value) {
  8759. this._isEnabled = value;
  8760. };
  8761. /**
  8762. * Is this node a descendant of the given node.
  8763. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  8764. * @param {BABYLON.Node} ancestor - The parent node to inspect
  8765. * @see parent
  8766. */
  8767. Node.prototype.isDescendantOf = function (ancestor) {
  8768. if (this.parent) {
  8769. if (this.parent === ancestor) {
  8770. return true;
  8771. }
  8772. return this.parent.isDescendantOf(ancestor);
  8773. }
  8774. return false;
  8775. };
  8776. /**
  8777. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  8778. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  8779. * @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.
  8780. * @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.
  8781. */
  8782. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  8783. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  8784. if (!this._children) {
  8785. return;
  8786. }
  8787. for (var index = 0; index < this._children.length; index++) {
  8788. var item = this._children[index];
  8789. if (!predicate || predicate(item)) {
  8790. results.push(item);
  8791. }
  8792. if (!directDescendantsOnly) {
  8793. item._getDescendants(results, false, predicate);
  8794. }
  8795. }
  8796. };
  8797. /**
  8798. * Will return all nodes that have this node as ascendant.
  8799. * @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.
  8800. * @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.
  8801. * @return {BABYLON.Node[]} all children nodes of all types.
  8802. */
  8803. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8804. var results = [];
  8805. this._getDescendants(results, directDescendantsOnly, predicate);
  8806. return results;
  8807. };
  8808. /**
  8809. * @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.
  8810. * @Deprecated, legacy support.
  8811. * use getDecendants instead.
  8812. */
  8813. Node.prototype.getChildren = function (predicate) {
  8814. return this.getDescendants(true, predicate);
  8815. };
  8816. /**
  8817. * Get all child-meshes of this node.
  8818. */
  8819. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8820. var results = [];
  8821. this._getDescendants(results, directDecendantsOnly, function (node) {
  8822. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8823. });
  8824. return results;
  8825. };
  8826. Node.prototype._setReady = function (state) {
  8827. if (state === this._isReady) {
  8828. return;
  8829. }
  8830. if (!state) {
  8831. this._isReady = false;
  8832. return;
  8833. }
  8834. this._isReady = true;
  8835. if (this.onReady) {
  8836. this.onReady(this);
  8837. }
  8838. };
  8839. Node.prototype.getAnimationByName = function (name) {
  8840. for (var i = 0; i < this.animations.length; i++) {
  8841. var animation = this.animations[i];
  8842. if (animation.name === name) {
  8843. return animation;
  8844. }
  8845. }
  8846. return null;
  8847. };
  8848. Node.prototype.createAnimationRange = function (name, from, to) {
  8849. // check name not already in use
  8850. if (!this._ranges[name]) {
  8851. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8852. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8853. if (this.animations[i]) {
  8854. this.animations[i].createRange(name, from, to);
  8855. }
  8856. }
  8857. }
  8858. };
  8859. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8860. if (deleteFrames === void 0) { deleteFrames = true; }
  8861. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8862. if (this.animations[i]) {
  8863. this.animations[i].deleteRange(name, deleteFrames);
  8864. }
  8865. }
  8866. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8867. };
  8868. Node.prototype.getAnimationRange = function (name) {
  8869. return this._ranges[name];
  8870. };
  8871. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8872. var range = this.getAnimationRange(name);
  8873. if (!range) {
  8874. return null;
  8875. }
  8876. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8877. };
  8878. Node.prototype.serializeAnimationRanges = function () {
  8879. var serializationRanges = [];
  8880. for (var name in this._ranges) {
  8881. var range = {};
  8882. range.name = name;
  8883. range.from = this._ranges[name].from;
  8884. range.to = this._ranges[name].to;
  8885. serializationRanges.push(range);
  8886. }
  8887. return serializationRanges;
  8888. };
  8889. Node.prototype.dispose = function () {
  8890. this.parent = null;
  8891. };
  8892. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8893. if (parsedNode.ranges) {
  8894. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8895. var data = parsedNode.ranges[index];
  8896. node.createAnimationRange(data.name, data.from, data.to);
  8897. }
  8898. }
  8899. };
  8900. __decorate([
  8901. BABYLON.serialize()
  8902. ], Node.prototype, "name", void 0);
  8903. __decorate([
  8904. BABYLON.serialize()
  8905. ], Node.prototype, "id", void 0);
  8906. __decorate([
  8907. BABYLON.serialize()
  8908. ], Node.prototype, "uniqueId", void 0);
  8909. __decorate([
  8910. BABYLON.serialize()
  8911. ], Node.prototype, "state", void 0);
  8912. return Node;
  8913. })();
  8914. BABYLON.Node = Node;
  8915. })(BABYLON || (BABYLON = {}));
  8916. var BABYLON;
  8917. (function (BABYLON) {
  8918. var FilesInput = (function () {
  8919. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8920. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8921. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8922. this._engine = p_engine;
  8923. this._canvas = p_canvas;
  8924. this._currentScene = p_scene;
  8925. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8926. this._progressCallback = p_progressCallback;
  8927. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8928. this._textureLoadingCallback = p_textureLoadingCallback;
  8929. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8930. }
  8931. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8932. var _this = this;
  8933. if (p_elementToMonitor) {
  8934. this._elementToMonitor = p_elementToMonitor;
  8935. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8936. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8937. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8938. }
  8939. };
  8940. FilesInput.prototype.renderFunction = function () {
  8941. if (this._additionnalRenderLoopLogicCallback) {
  8942. this._additionnalRenderLoopLogicCallback();
  8943. }
  8944. if (this._currentScene) {
  8945. if (this._textureLoadingCallback) {
  8946. var remaining = this._currentScene.getWaitingItemsCount();
  8947. if (remaining > 0) {
  8948. this._textureLoadingCallback(remaining);
  8949. }
  8950. }
  8951. this._currentScene.render();
  8952. }
  8953. };
  8954. FilesInput.prototype.drag = function (e) {
  8955. e.stopPropagation();
  8956. e.preventDefault();
  8957. };
  8958. FilesInput.prototype.drop = function (eventDrop) {
  8959. eventDrop.stopPropagation();
  8960. eventDrop.preventDefault();
  8961. this.loadFiles(eventDrop);
  8962. };
  8963. FilesInput.prototype.loadFiles = function (event) {
  8964. if (this._startingProcessingFilesCallback)
  8965. this._startingProcessingFilesCallback();
  8966. // Handling data transfer via drag'n'drop
  8967. if (event && event.dataTransfer && event.dataTransfer.files) {
  8968. this._filesToLoad = event.dataTransfer.files;
  8969. }
  8970. // Handling files from input files
  8971. if (event && event.target && event.target.files) {
  8972. this._filesToLoad = event.target.files;
  8973. }
  8974. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8975. for (var i = 0; i < this._filesToLoad.length; i++) {
  8976. switch (this._filesToLoad[i].type) {
  8977. case "image/jpeg":
  8978. case "image/png":
  8979. case "image/bmp":
  8980. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8981. break;
  8982. case "image/targa":
  8983. case "image/vnd.ms-dds":
  8984. case "audio/wav":
  8985. case "audio/x-wav":
  8986. case "audio/mp3":
  8987. case "audio/mpeg":
  8988. case "audio/mpeg3":
  8989. case "audio/x-mpeg-3":
  8990. case "audio/ogg":
  8991. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8992. break;
  8993. default:
  8994. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8995. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8996. }
  8997. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8998. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8999. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9000. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9001. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9002. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9003. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9004. this._sceneFileToLoad = this._filesToLoad[i];
  9005. }
  9006. break;
  9007. }
  9008. }
  9009. this.reload();
  9010. }
  9011. };
  9012. FilesInput.prototype.reload = function () {
  9013. var _this = this;
  9014. var that = this;
  9015. // If a ".babylon" file has been provided
  9016. if (this._sceneFileToLoad) {
  9017. if (this._currentScene) {
  9018. if (BABYLON.Tools.errorsCount > 0) {
  9019. BABYLON.Tools.ClearLogCache();
  9020. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9021. }
  9022. this._engine.stopRenderLoop();
  9023. this._currentScene.dispose();
  9024. }
  9025. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9026. that._currentScene = newScene;
  9027. // Wait for textures and shaders to be ready
  9028. that._currentScene.executeWhenReady(function () {
  9029. // Attach camera to canvas inputs
  9030. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9031. that._currentScene.createDefaultCameraOrLight();
  9032. }
  9033. that._currentScene.activeCamera.attachControl(that._canvas);
  9034. if (that._sceneLoadedCallback) {
  9035. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9036. }
  9037. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9038. });
  9039. }, function (progress) {
  9040. if (_this._progressCallback) {
  9041. _this._progressCallback(progress);
  9042. }
  9043. });
  9044. }
  9045. else {
  9046. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9047. }
  9048. };
  9049. FilesInput.FilesTextures = new Array();
  9050. FilesInput.FilesToLoad = new Array();
  9051. return FilesInput;
  9052. })();
  9053. BABYLON.FilesInput = FilesInput;
  9054. })(BABYLON || (BABYLON = {}));
  9055. var BABYLON;
  9056. (function (BABYLON) {
  9057. var IntersectionInfo = (function () {
  9058. function IntersectionInfo(bu, bv, distance) {
  9059. this.bu = bu;
  9060. this.bv = bv;
  9061. this.distance = distance;
  9062. this.faceId = 0;
  9063. this.subMeshId = 0;
  9064. }
  9065. return IntersectionInfo;
  9066. })();
  9067. BABYLON.IntersectionInfo = IntersectionInfo;
  9068. var PickingInfo = (function () {
  9069. function PickingInfo() {
  9070. this.hit = false;
  9071. this.distance = 0;
  9072. this.pickedPoint = null;
  9073. this.pickedMesh = null;
  9074. this.bu = 0;
  9075. this.bv = 0;
  9076. this.faceId = -1;
  9077. this.subMeshId = 0;
  9078. this.pickedSprite = null;
  9079. }
  9080. // Methods
  9081. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9082. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9083. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9084. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9085. return null;
  9086. }
  9087. var indices = this.pickedMesh.getIndices();
  9088. var result;
  9089. if (useVerticesNormals) {
  9090. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9091. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9092. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9093. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9094. normal0 = normal0.scale(this.bu);
  9095. normal1 = normal1.scale(this.bv);
  9096. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9097. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9098. }
  9099. else {
  9100. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9101. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9102. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9103. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9104. var p1p2 = vertex1.subtract(vertex2);
  9105. var p3p2 = vertex3.subtract(vertex2);
  9106. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9107. }
  9108. if (useWorldCoordinates) {
  9109. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9110. }
  9111. return BABYLON.Vector3.Normalize(result);
  9112. };
  9113. PickingInfo.prototype.getTextureCoordinates = function () {
  9114. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9115. return null;
  9116. }
  9117. var indices = this.pickedMesh.getIndices();
  9118. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9119. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9120. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9121. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9122. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9123. uv1 = uv1.scale(this.bu);
  9124. uv2 = uv2.scale(this.bv);
  9125. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9126. };
  9127. return PickingInfo;
  9128. })();
  9129. BABYLON.PickingInfo = PickingInfo;
  9130. })(BABYLON || (BABYLON = {}));
  9131. var BABYLON;
  9132. (function (BABYLON) {
  9133. var BoundingSphere = (function () {
  9134. function BoundingSphere(minimum, maximum) {
  9135. this.minimum = minimum;
  9136. this.maximum = maximum;
  9137. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9138. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9139. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9140. this.radius = distance * 0.5;
  9141. this.centerWorld = BABYLON.Vector3.Zero();
  9142. this._update(BABYLON.Matrix.Identity());
  9143. }
  9144. // Methods
  9145. BoundingSphere.prototype._update = function (world) {
  9146. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9147. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9148. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9149. };
  9150. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9151. for (var i = 0; i < 6; i++) {
  9152. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9153. return false;
  9154. }
  9155. return true;
  9156. };
  9157. BoundingSphere.prototype.intersectsPoint = function (point) {
  9158. var x = this.centerWorld.x - point.x;
  9159. var y = this.centerWorld.y - point.y;
  9160. var z = this.centerWorld.z - point.z;
  9161. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9162. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9163. return false;
  9164. return true;
  9165. };
  9166. // Statics
  9167. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9168. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9169. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9170. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9171. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9172. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9173. return false;
  9174. return true;
  9175. };
  9176. return BoundingSphere;
  9177. })();
  9178. BABYLON.BoundingSphere = BoundingSphere;
  9179. })(BABYLON || (BABYLON = {}));
  9180. var BABYLON;
  9181. (function (BABYLON) {
  9182. var BoundingBox = (function () {
  9183. function BoundingBox(minimum, maximum) {
  9184. this.minimum = minimum;
  9185. this.maximum = maximum;
  9186. this.vectors = new Array();
  9187. this.vectorsWorld = new Array();
  9188. // Bounding vectors
  9189. this.vectors.push(this.minimum.clone());
  9190. this.vectors.push(this.maximum.clone());
  9191. this.vectors.push(this.minimum.clone());
  9192. this.vectors[2].x = this.maximum.x;
  9193. this.vectors.push(this.minimum.clone());
  9194. this.vectors[3].y = this.maximum.y;
  9195. this.vectors.push(this.minimum.clone());
  9196. this.vectors[4].z = this.maximum.z;
  9197. this.vectors.push(this.maximum.clone());
  9198. this.vectors[5].z = this.minimum.z;
  9199. this.vectors.push(this.maximum.clone());
  9200. this.vectors[6].x = this.minimum.x;
  9201. this.vectors.push(this.maximum.clone());
  9202. this.vectors[7].y = this.minimum.y;
  9203. // OBB
  9204. this.center = this.maximum.add(this.minimum).scale(0.5);
  9205. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9206. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9207. // World
  9208. for (var index = 0; index < this.vectors.length; index++) {
  9209. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9210. }
  9211. this.minimumWorld = BABYLON.Vector3.Zero();
  9212. this.maximumWorld = BABYLON.Vector3.Zero();
  9213. this._update(BABYLON.Matrix.Identity());
  9214. }
  9215. // Methods
  9216. BoundingBox.prototype.getWorldMatrix = function () {
  9217. return this._worldMatrix;
  9218. };
  9219. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9220. this._worldMatrix.copyFrom(matrix);
  9221. return this;
  9222. };
  9223. BoundingBox.prototype._update = function (world) {
  9224. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9225. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9226. for (var index = 0; index < this.vectors.length; index++) {
  9227. var v = this.vectorsWorld[index];
  9228. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9229. if (v.x < this.minimumWorld.x)
  9230. this.minimumWorld.x = v.x;
  9231. if (v.y < this.minimumWorld.y)
  9232. this.minimumWorld.y = v.y;
  9233. if (v.z < this.minimumWorld.z)
  9234. this.minimumWorld.z = v.z;
  9235. if (v.x > this.maximumWorld.x)
  9236. this.maximumWorld.x = v.x;
  9237. if (v.y > this.maximumWorld.y)
  9238. this.maximumWorld.y = v.y;
  9239. if (v.z > this.maximumWorld.z)
  9240. this.maximumWorld.z = v.z;
  9241. }
  9242. // OBB
  9243. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9244. this.center.scaleInPlace(0.5);
  9245. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9246. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9247. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9248. this._worldMatrix = world;
  9249. };
  9250. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9251. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9252. };
  9253. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9254. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9255. };
  9256. BoundingBox.prototype.intersectsPoint = function (point) {
  9257. var delta = -BABYLON.Epsilon;
  9258. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9259. return false;
  9260. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9261. return false;
  9262. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9263. return false;
  9264. return true;
  9265. };
  9266. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9267. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9268. };
  9269. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9270. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9271. return false;
  9272. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9273. return false;
  9274. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9275. return false;
  9276. return true;
  9277. };
  9278. // Statics
  9279. BoundingBox.Intersects = function (box0, box1) {
  9280. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9281. return false;
  9282. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9283. return false;
  9284. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9285. return false;
  9286. return true;
  9287. };
  9288. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9289. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9290. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9291. return (num <= (sphereRadius * sphereRadius));
  9292. };
  9293. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9294. for (var p = 0; p < 6; p++) {
  9295. for (var i = 0; i < 8; i++) {
  9296. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9297. return false;
  9298. }
  9299. }
  9300. }
  9301. return true;
  9302. };
  9303. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9304. for (var p = 0; p < 6; p++) {
  9305. var inCount = 8;
  9306. for (var i = 0; i < 8; i++) {
  9307. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9308. --inCount;
  9309. }
  9310. else {
  9311. break;
  9312. }
  9313. }
  9314. if (inCount === 0)
  9315. return false;
  9316. }
  9317. return true;
  9318. };
  9319. return BoundingBox;
  9320. })();
  9321. BABYLON.BoundingBox = BoundingBox;
  9322. })(BABYLON || (BABYLON = {}));
  9323. var BABYLON;
  9324. (function (BABYLON) {
  9325. var computeBoxExtents = function (axis, box) {
  9326. var p = BABYLON.Vector3.Dot(box.center, axis);
  9327. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9328. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9329. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9330. var r = r0 + r1 + r2;
  9331. return {
  9332. min: p - r,
  9333. max: p + r
  9334. };
  9335. };
  9336. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9337. var axisOverlap = function (axis, box0, box1) {
  9338. var result0 = computeBoxExtents(axis, box0);
  9339. var result1 = computeBoxExtents(axis, box1);
  9340. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9341. };
  9342. var BoundingInfo = (function () {
  9343. function BoundingInfo(minimum, maximum) {
  9344. this.minimum = minimum;
  9345. this.maximum = maximum;
  9346. this._isLocked = false;
  9347. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9348. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9349. }
  9350. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9351. get: function () {
  9352. return this._isLocked;
  9353. },
  9354. set: function (value) {
  9355. this._isLocked = value;
  9356. },
  9357. enumerable: true,
  9358. configurable: true
  9359. });
  9360. // Methods
  9361. BoundingInfo.prototype.update = function (world) {
  9362. if (this._isLocked) {
  9363. return;
  9364. }
  9365. this.boundingBox._update(world);
  9366. this.boundingSphere._update(world);
  9367. };
  9368. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9369. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9370. return false;
  9371. return this.boundingBox.isInFrustum(frustumPlanes);
  9372. };
  9373. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9374. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9375. };
  9376. BoundingInfo.prototype._checkCollision = function (collider) {
  9377. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9378. };
  9379. BoundingInfo.prototype.intersectsPoint = function (point) {
  9380. if (!this.boundingSphere.centerWorld) {
  9381. return false;
  9382. }
  9383. if (!this.boundingSphere.intersectsPoint(point)) {
  9384. return false;
  9385. }
  9386. if (!this.boundingBox.intersectsPoint(point)) {
  9387. return false;
  9388. }
  9389. return true;
  9390. };
  9391. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9392. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9393. return false;
  9394. }
  9395. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9396. return false;
  9397. }
  9398. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9399. return false;
  9400. }
  9401. if (!precise) {
  9402. return true;
  9403. }
  9404. var box0 = this.boundingBox;
  9405. var box1 = boundingInfo.boundingBox;
  9406. if (!axisOverlap(box0.directions[0], box0, box1))
  9407. return false;
  9408. if (!axisOverlap(box0.directions[1], box0, box1))
  9409. return false;
  9410. if (!axisOverlap(box0.directions[2], box0, box1))
  9411. return false;
  9412. if (!axisOverlap(box1.directions[0], box0, box1))
  9413. return false;
  9414. if (!axisOverlap(box1.directions[1], box0, box1))
  9415. return false;
  9416. if (!axisOverlap(box1.directions[2], box0, box1))
  9417. return false;
  9418. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9419. return false;
  9420. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9421. return false;
  9422. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9423. return false;
  9424. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9425. return false;
  9426. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9427. return false;
  9428. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9429. return false;
  9430. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9431. return false;
  9432. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9433. return false;
  9434. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9435. return false;
  9436. return true;
  9437. };
  9438. return BoundingInfo;
  9439. })();
  9440. BABYLON.BoundingInfo = BoundingInfo;
  9441. })(BABYLON || (BABYLON = {}));
  9442. var BABYLON;
  9443. (function (BABYLON) {
  9444. var Ray = (function () {
  9445. function Ray(origin, direction, length) {
  9446. if (length === void 0) { length = Number.MAX_VALUE; }
  9447. this.origin = origin;
  9448. this.direction = direction;
  9449. this.length = length;
  9450. }
  9451. // Methods
  9452. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9453. var d = 0.0;
  9454. var maxValue = Number.MAX_VALUE;
  9455. var inv;
  9456. var min;
  9457. var max;
  9458. var temp;
  9459. if (Math.abs(this.direction.x) < 0.0000001) {
  9460. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9461. return false;
  9462. }
  9463. }
  9464. else {
  9465. inv = 1.0 / this.direction.x;
  9466. min = (minimum.x - this.origin.x) * inv;
  9467. max = (maximum.x - this.origin.x) * inv;
  9468. if (max === -Infinity) {
  9469. max = Infinity;
  9470. }
  9471. if (min > max) {
  9472. temp = min;
  9473. min = max;
  9474. max = temp;
  9475. }
  9476. d = Math.max(min, d);
  9477. maxValue = Math.min(max, maxValue);
  9478. if (d > maxValue) {
  9479. return false;
  9480. }
  9481. }
  9482. if (Math.abs(this.direction.y) < 0.0000001) {
  9483. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9484. return false;
  9485. }
  9486. }
  9487. else {
  9488. inv = 1.0 / this.direction.y;
  9489. min = (minimum.y - this.origin.y) * inv;
  9490. max = (maximum.y - this.origin.y) * inv;
  9491. if (max === -Infinity) {
  9492. max = Infinity;
  9493. }
  9494. if (min > max) {
  9495. temp = min;
  9496. min = max;
  9497. max = temp;
  9498. }
  9499. d = Math.max(min, d);
  9500. maxValue = Math.min(max, maxValue);
  9501. if (d > maxValue) {
  9502. return false;
  9503. }
  9504. }
  9505. if (Math.abs(this.direction.z) < 0.0000001) {
  9506. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9507. return false;
  9508. }
  9509. }
  9510. else {
  9511. inv = 1.0 / this.direction.z;
  9512. min = (minimum.z - this.origin.z) * inv;
  9513. max = (maximum.z - this.origin.z) * inv;
  9514. if (max === -Infinity) {
  9515. max = Infinity;
  9516. }
  9517. if (min > max) {
  9518. temp = min;
  9519. min = max;
  9520. max = temp;
  9521. }
  9522. d = Math.max(min, d);
  9523. maxValue = Math.min(max, maxValue);
  9524. if (d > maxValue) {
  9525. return false;
  9526. }
  9527. }
  9528. return true;
  9529. };
  9530. Ray.prototype.intersectsBox = function (box) {
  9531. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9532. };
  9533. Ray.prototype.intersectsSphere = function (sphere) {
  9534. var x = sphere.center.x - this.origin.x;
  9535. var y = sphere.center.y - this.origin.y;
  9536. var z = sphere.center.z - this.origin.z;
  9537. var pyth = (x * x) + (y * y) + (z * z);
  9538. var rr = sphere.radius * sphere.radius;
  9539. if (pyth <= rr) {
  9540. return true;
  9541. }
  9542. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9543. if (dot < 0.0) {
  9544. return false;
  9545. }
  9546. var temp = pyth - (dot * dot);
  9547. return temp <= rr;
  9548. };
  9549. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9550. if (!this._edge1) {
  9551. this._edge1 = BABYLON.Vector3.Zero();
  9552. this._edge2 = BABYLON.Vector3.Zero();
  9553. this._pvec = BABYLON.Vector3.Zero();
  9554. this._tvec = BABYLON.Vector3.Zero();
  9555. this._qvec = BABYLON.Vector3.Zero();
  9556. }
  9557. vertex1.subtractToRef(vertex0, this._edge1);
  9558. vertex2.subtractToRef(vertex0, this._edge2);
  9559. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9560. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9561. if (det === 0) {
  9562. return null;
  9563. }
  9564. var invdet = 1 / det;
  9565. this.origin.subtractToRef(vertex0, this._tvec);
  9566. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9567. if (bu < 0 || bu > 1.0) {
  9568. return null;
  9569. }
  9570. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9571. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9572. if (bv < 0 || bu + bv > 1.0) {
  9573. return null;
  9574. }
  9575. //check if the distance is longer than the predefined length.
  9576. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9577. if (distance > this.length) {
  9578. return null;
  9579. }
  9580. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9581. };
  9582. Ray.prototype.intersectsPlane = function (plane) {
  9583. var distance;
  9584. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9585. if (Math.abs(result1) < 9.99999997475243E-07) {
  9586. return null;
  9587. }
  9588. else {
  9589. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9590. distance = (-plane.d - result2) / result1;
  9591. if (distance < 0.0) {
  9592. if (distance < -9.99999997475243E-07) {
  9593. return null;
  9594. }
  9595. else {
  9596. return 0;
  9597. }
  9598. }
  9599. return distance;
  9600. }
  9601. };
  9602. /**
  9603. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9604. * @param sega the first point of the segment to test the intersection against
  9605. * @param segb the second point of the segment to test the intersection against
  9606. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9607. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9608. */
  9609. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9610. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9611. var u = segb.subtract(sega);
  9612. var v = rsegb.subtract(this.origin);
  9613. var w = sega.subtract(this.origin);
  9614. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9615. var b = BABYLON.Vector3.Dot(u, v);
  9616. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9617. var d = BABYLON.Vector3.Dot(u, w);
  9618. var e = BABYLON.Vector3.Dot(v, w);
  9619. var D = a * c - b * b; // always >= 0
  9620. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9621. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9622. // compute the line parameters of the two closest points
  9623. if (D < Ray.smallnum) {
  9624. sN = 0.0; // force using point P0 on segment S1
  9625. sD = 1.0; // to prevent possible division by 0.0 later
  9626. tN = e;
  9627. tD = c;
  9628. }
  9629. else {
  9630. sN = (b * e - c * d);
  9631. tN = (a * e - b * d);
  9632. if (sN < 0.0) {
  9633. sN = 0.0;
  9634. tN = e;
  9635. tD = c;
  9636. }
  9637. else if (sN > sD) {
  9638. sN = sD;
  9639. tN = e + b;
  9640. tD = c;
  9641. }
  9642. }
  9643. if (tN < 0.0) {
  9644. tN = 0.0;
  9645. // recompute sc for this edge
  9646. if (-d < 0.0) {
  9647. sN = 0.0;
  9648. }
  9649. else if (-d > a)
  9650. sN = sD;
  9651. else {
  9652. sN = -d;
  9653. sD = a;
  9654. }
  9655. }
  9656. else if (tN > tD) {
  9657. tN = tD;
  9658. // recompute sc for this edge
  9659. if ((-d + b) < 0.0) {
  9660. sN = 0;
  9661. }
  9662. else if ((-d + b) > a) {
  9663. sN = sD;
  9664. }
  9665. else {
  9666. sN = (-d + b);
  9667. sD = a;
  9668. }
  9669. }
  9670. // finally do the division to get sc and tc
  9671. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9672. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9673. // get the difference of the two closest points
  9674. var qtc = v.multiplyByFloats(tc, tc, tc);
  9675. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9676. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9677. if (isIntersected) {
  9678. return qtc.length();
  9679. }
  9680. return -1;
  9681. };
  9682. // Statics
  9683. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9684. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9685. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9686. var direction = end.subtract(start);
  9687. direction.normalize();
  9688. return new Ray(start, direction);
  9689. };
  9690. /**
  9691. * 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
  9692. * transformed to the given world matrix.
  9693. * @param origin The origin point
  9694. * @param end The end point
  9695. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9696. */
  9697. Ray.CreateNewFromTo = function (origin, end, world) {
  9698. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9699. var direction = end.subtract(origin);
  9700. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9701. direction.normalize();
  9702. return Ray.Transform(new Ray(origin, direction, length), world);
  9703. };
  9704. Ray.Transform = function (ray, matrix) {
  9705. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9706. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9707. newDirection.normalize();
  9708. return new Ray(newOrigin, newDirection, ray.length);
  9709. };
  9710. Ray.smallnum = 0.00000001;
  9711. Ray.rayl = 10e8;
  9712. return Ray;
  9713. })();
  9714. BABYLON.Ray = Ray;
  9715. })(BABYLON || (BABYLON = {}));
  9716. var BABYLON;
  9717. (function (BABYLON) {
  9718. var AbstractMesh = (function (_super) {
  9719. __extends(AbstractMesh, _super);
  9720. // Constructor
  9721. function AbstractMesh(name, scene) {
  9722. var _this = this;
  9723. _super.call(this, name, scene);
  9724. // Events
  9725. /**
  9726. * An event triggered when the mesh is disposed.
  9727. * @type {BABYLON.Observable}
  9728. */
  9729. this.onDisposeObservable = new BABYLON.Observable();
  9730. /**
  9731. * An event triggered when this mesh collides with another one
  9732. * @type {BABYLON.Observable}
  9733. */
  9734. this.onCollideObservable = new BABYLON.Observable();
  9735. /**
  9736. * An event triggered when the collision's position changes
  9737. * @type {BABYLON.Observable}
  9738. */
  9739. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9740. /**
  9741. * An event triggered after the world matrix is updated
  9742. * @type {BABYLON.Observable}
  9743. */
  9744. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9745. // Properties
  9746. this.definedFacingForward = true; // orientation for POV movement & rotation
  9747. this.position = new BABYLON.Vector3(0, 0, 0);
  9748. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9749. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9750. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9751. this.visibility = 1.0;
  9752. this.alphaIndex = Number.MAX_VALUE;
  9753. this.infiniteDistance = false;
  9754. this.isVisible = true;
  9755. this.isPickable = true;
  9756. this.showBoundingBox = false;
  9757. this.showSubMeshesBoundingBox = false;
  9758. this.isBlocker = false;
  9759. this.renderingGroupId = 0;
  9760. this.receiveShadows = false;
  9761. this.renderOutline = false;
  9762. this.outlineColor = BABYLON.Color3.Red();
  9763. this.outlineWidth = 0.02;
  9764. this.renderOverlay = false;
  9765. this.overlayColor = BABYLON.Color3.Red();
  9766. this.overlayAlpha = 0.5;
  9767. this.hasVertexAlpha = false;
  9768. this.useVertexColors = true;
  9769. this.applyFog = true;
  9770. this.computeBonesUsingShaders = true;
  9771. this.scalingDeterminant = 1;
  9772. this.numBoneInfluencers = 4;
  9773. this.useOctreeForRenderingSelection = true;
  9774. this.useOctreeForPicking = true;
  9775. this.useOctreeForCollisions = true;
  9776. this.layerMask = 0x0FFFFFFF;
  9777. this.alwaysSelectAsActiveMesh = false;
  9778. // Collisions
  9779. this._checkCollisions = false;
  9780. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9781. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9782. this._collider = new BABYLON.Collider();
  9783. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9784. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9785. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9786. // Edges
  9787. this.edgesWidth = 1;
  9788. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  9789. // Cache
  9790. this._localWorld = BABYLON.Matrix.Zero();
  9791. this._worldMatrix = BABYLON.Matrix.Zero();
  9792. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9793. this._absolutePosition = BABYLON.Vector3.Zero();
  9794. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9795. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9796. this._isDirty = false;
  9797. this._pivotMatrix = BABYLON.Matrix.Identity();
  9798. this._isDisposed = false;
  9799. this._renderId = 0;
  9800. this._intersectionsInProgress = new Array();
  9801. this._isWorldMatrixFrozen = false;
  9802. this._unIndexed = false;
  9803. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9804. if (collidedMesh === void 0) { collidedMesh = null; }
  9805. //TODO move this to the collision coordinator!
  9806. if (_this.getScene().workerCollisions)
  9807. newPosition.multiplyInPlace(_this._collider.radius);
  9808. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9809. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9810. _this.position.addInPlace(_this._diffPositionForCollisions);
  9811. }
  9812. if (collidedMesh) {
  9813. _this.onCollideObservable.notifyObservers(collidedMesh);
  9814. }
  9815. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9816. };
  9817. scene.addMesh(this);
  9818. }
  9819. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9820. get: function () {
  9821. return AbstractMesh._BILLBOARDMODE_NONE;
  9822. },
  9823. enumerable: true,
  9824. configurable: true
  9825. });
  9826. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9827. get: function () {
  9828. return AbstractMesh._BILLBOARDMODE_X;
  9829. },
  9830. enumerable: true,
  9831. configurable: true
  9832. });
  9833. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9834. get: function () {
  9835. return AbstractMesh._BILLBOARDMODE_Y;
  9836. },
  9837. enumerable: true,
  9838. configurable: true
  9839. });
  9840. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9841. get: function () {
  9842. return AbstractMesh._BILLBOARDMODE_Z;
  9843. },
  9844. enumerable: true,
  9845. configurable: true
  9846. });
  9847. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9848. get: function () {
  9849. return AbstractMesh._BILLBOARDMODE_ALL;
  9850. },
  9851. enumerable: true,
  9852. configurable: true
  9853. });
  9854. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9855. set: function (callback) {
  9856. if (this._onDisposeObserver) {
  9857. this.onDisposeObservable.remove(this._onDisposeObserver);
  9858. }
  9859. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9860. },
  9861. enumerable: true,
  9862. configurable: true
  9863. });
  9864. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9865. set: function (callback) {
  9866. if (this._onCollideObserver) {
  9867. this.onCollideObservable.remove(this._onCollideObserver);
  9868. }
  9869. this._onCollideObserver = this.onCollideObservable.add(callback);
  9870. },
  9871. enumerable: true,
  9872. configurable: true
  9873. });
  9874. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9875. set: function (callback) {
  9876. if (this._onCollisionPositionChangeObserver) {
  9877. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9878. }
  9879. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9885. get: function () {
  9886. return this._skeleton;
  9887. },
  9888. set: function (value) {
  9889. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9890. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9891. }
  9892. if (value && value.needInitialSkinMatrix) {
  9893. value._registerMeshWithPoseMatrix(this);
  9894. }
  9895. this._skeleton = value;
  9896. if (!this._skeleton) {
  9897. this._bonesTransformMatrices = null;
  9898. }
  9899. },
  9900. enumerable: true,
  9901. configurable: true
  9902. });
  9903. /**
  9904. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9905. */
  9906. AbstractMesh.prototype.toString = function (fullDetails) {
  9907. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9908. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9909. if (this._skeleton) {
  9910. ret += ", skeleton: " + this._skeleton.name;
  9911. }
  9912. if (fullDetails) {
  9913. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9914. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9915. }
  9916. return ret;
  9917. };
  9918. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9919. /**
  9920. * Getting the rotation object.
  9921. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9922. */
  9923. get: function () {
  9924. return this._rotation;
  9925. },
  9926. set: function (newRotation) {
  9927. this._rotation = newRotation;
  9928. },
  9929. enumerable: true,
  9930. configurable: true
  9931. });
  9932. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9933. get: function () {
  9934. return this._scaling;
  9935. },
  9936. set: function (newScaling) {
  9937. this._scaling = newScaling;
  9938. if (this.physicsImpostor) {
  9939. this.physicsImpostor.forceUpdate();
  9940. }
  9941. },
  9942. enumerable: true,
  9943. configurable: true
  9944. });
  9945. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9946. get: function () {
  9947. return this._rotationQuaternion;
  9948. },
  9949. set: function (quaternion) {
  9950. this._rotationQuaternion = quaternion;
  9951. //reset the rotation vector.
  9952. if (quaternion && this.rotation.length()) {
  9953. this.rotation.copyFromFloats(0, 0, 0);
  9954. }
  9955. },
  9956. enumerable: true,
  9957. configurable: true
  9958. });
  9959. // Methods
  9960. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9961. this._poseMatrix.copyFrom(matrix);
  9962. };
  9963. AbstractMesh.prototype.getPoseMatrix = function () {
  9964. return this._poseMatrix;
  9965. };
  9966. AbstractMesh.prototype.disableEdgesRendering = function () {
  9967. if (this._edgesRenderer !== undefined) {
  9968. this._edgesRenderer.dispose();
  9969. this._edgesRenderer = undefined;
  9970. }
  9971. };
  9972. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9973. if (epsilon === void 0) { epsilon = 0.95; }
  9974. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9975. this.disableEdgesRendering();
  9976. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9977. };
  9978. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9979. get: function () {
  9980. return false;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. AbstractMesh.prototype.getLOD = function (camera) {
  9986. return this;
  9987. };
  9988. AbstractMesh.prototype.getTotalVertices = function () {
  9989. return 0;
  9990. };
  9991. AbstractMesh.prototype.getIndices = function () {
  9992. return null;
  9993. };
  9994. AbstractMesh.prototype.getVerticesData = function (kind) {
  9995. return null;
  9996. };
  9997. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9998. return false;
  9999. };
  10000. AbstractMesh.prototype.getBoundingInfo = function () {
  10001. if (this._masterMesh) {
  10002. return this._masterMesh.getBoundingInfo();
  10003. }
  10004. if (!this._boundingInfo) {
  10005. this._updateBoundingInfo();
  10006. }
  10007. return this._boundingInfo;
  10008. };
  10009. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10010. this._boundingInfo = boundingInfo;
  10011. };
  10012. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10013. get: function () {
  10014. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10015. },
  10016. enumerable: true,
  10017. configurable: true
  10018. });
  10019. AbstractMesh.prototype._preActivate = function () {
  10020. };
  10021. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10022. };
  10023. AbstractMesh.prototype._activate = function (renderId) {
  10024. this._renderId = renderId;
  10025. };
  10026. AbstractMesh.prototype.getWorldMatrix = function () {
  10027. if (this._masterMesh) {
  10028. return this._masterMesh.getWorldMatrix();
  10029. }
  10030. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10031. this.computeWorldMatrix();
  10032. }
  10033. return this._worldMatrix;
  10034. };
  10035. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10036. get: function () {
  10037. return this._worldMatrix;
  10038. },
  10039. enumerable: true,
  10040. configurable: true
  10041. });
  10042. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10043. get: function () {
  10044. return this._absolutePosition;
  10045. },
  10046. enumerable: true,
  10047. configurable: true
  10048. });
  10049. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10050. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10051. this.computeWorldMatrix(true);
  10052. this._isWorldMatrixFrozen = true;
  10053. };
  10054. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10055. this._isWorldMatrixFrozen = false;
  10056. this.computeWorldMatrix(true);
  10057. };
  10058. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10059. get: function () {
  10060. return this._isWorldMatrixFrozen;
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10066. axis.normalize();
  10067. if (!this.rotationQuaternion) {
  10068. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10069. this.rotation = BABYLON.Vector3.Zero();
  10070. }
  10071. var rotationQuaternion;
  10072. if (!space || space === BABYLON.Space.LOCAL) {
  10073. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10074. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10075. }
  10076. else {
  10077. if (this.parent) {
  10078. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10079. invertParentWorldMatrix.invert();
  10080. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10081. }
  10082. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10083. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10084. }
  10085. };
  10086. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10087. var displacementVector = axis.scale(distance);
  10088. if (!space || space === BABYLON.Space.LOCAL) {
  10089. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10090. this.setPositionWithLocalVector(tempV3);
  10091. }
  10092. else {
  10093. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10094. }
  10095. };
  10096. AbstractMesh.prototype.getAbsolutePosition = function () {
  10097. this.computeWorldMatrix();
  10098. return this._absolutePosition;
  10099. };
  10100. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10101. if (!absolutePosition) {
  10102. return;
  10103. }
  10104. var absolutePositionX;
  10105. var absolutePositionY;
  10106. var absolutePositionZ;
  10107. if (absolutePosition.x === undefined) {
  10108. if (arguments.length < 3) {
  10109. return;
  10110. }
  10111. absolutePositionX = arguments[0];
  10112. absolutePositionY = arguments[1];
  10113. absolutePositionZ = arguments[2];
  10114. }
  10115. else {
  10116. absolutePositionX = absolutePosition.x;
  10117. absolutePositionY = absolutePosition.y;
  10118. absolutePositionZ = absolutePosition.z;
  10119. }
  10120. if (this.parent) {
  10121. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10122. invertParentWorldMatrix.invert();
  10123. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10124. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10125. }
  10126. else {
  10127. this.position.x = absolutePositionX;
  10128. this.position.y = absolutePositionY;
  10129. this.position.z = absolutePositionZ;
  10130. }
  10131. };
  10132. // ================================== Point of View Movement =================================
  10133. /**
  10134. * Perform relative position change from the point of view of behind the front of the mesh.
  10135. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10136. * Supports definition of mesh facing forward or backward.
  10137. * @param {number} amountRight
  10138. * @param {number} amountUp
  10139. * @param {number} amountForward
  10140. */
  10141. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10142. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10143. };
  10144. /**
  10145. * Calculate relative position change from the point of view of behind the front of the mesh.
  10146. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10147. * Supports definition of mesh facing forward or backward.
  10148. * @param {number} amountRight
  10149. * @param {number} amountUp
  10150. * @param {number} amountForward
  10151. */
  10152. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10153. var rotMatrix = new BABYLON.Matrix();
  10154. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10155. rotQuaternion.toRotationMatrix(rotMatrix);
  10156. var translationDelta = BABYLON.Vector3.Zero();
  10157. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10158. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10159. return translationDelta;
  10160. };
  10161. // ================================== Point of View Rotation =================================
  10162. /**
  10163. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10164. * Supports definition of mesh facing forward or backward.
  10165. * @param {number} flipBack
  10166. * @param {number} twirlClockwise
  10167. * @param {number} tiltRight
  10168. */
  10169. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10170. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10171. };
  10172. /**
  10173. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10174. * Supports definition of mesh facing forward or backward.
  10175. * @param {number} flipBack
  10176. * @param {number} twirlClockwise
  10177. * @param {number} tiltRight
  10178. */
  10179. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10180. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10181. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10182. };
  10183. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10184. this._pivotMatrix = matrix;
  10185. this._cache.pivotMatrixUpdated = true;
  10186. };
  10187. AbstractMesh.prototype.getPivotMatrix = function () {
  10188. return this._pivotMatrix;
  10189. };
  10190. AbstractMesh.prototype._isSynchronized = function () {
  10191. if (this._isDirty) {
  10192. return false;
  10193. }
  10194. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10195. return false;
  10196. if (this._cache.pivotMatrixUpdated) {
  10197. return false;
  10198. }
  10199. if (this.infiniteDistance) {
  10200. return false;
  10201. }
  10202. if (!this._cache.position.equals(this.position))
  10203. return false;
  10204. if (this.rotationQuaternion) {
  10205. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10206. return false;
  10207. }
  10208. if (!this._cache.rotation.equals(this.rotation))
  10209. return false;
  10210. if (!this._cache.scaling.equals(this.scaling))
  10211. return false;
  10212. return true;
  10213. };
  10214. AbstractMesh.prototype._initCache = function () {
  10215. _super.prototype._initCache.call(this);
  10216. this._cache.localMatrixUpdated = false;
  10217. this._cache.position = BABYLON.Vector3.Zero();
  10218. this._cache.scaling = BABYLON.Vector3.Zero();
  10219. this._cache.rotation = BABYLON.Vector3.Zero();
  10220. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10221. this._cache.billboardMode = -1;
  10222. };
  10223. AbstractMesh.prototype.markAsDirty = function (property) {
  10224. if (property === "rotation") {
  10225. this.rotationQuaternion = null;
  10226. }
  10227. this._currentRenderId = Number.MAX_VALUE;
  10228. this._isDirty = true;
  10229. };
  10230. AbstractMesh.prototype._updateBoundingInfo = function () {
  10231. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10232. this._boundingInfo.update(this.worldMatrixFromCache);
  10233. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10234. };
  10235. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10236. if (!this.subMeshes) {
  10237. return;
  10238. }
  10239. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10240. var subMesh = this.subMeshes[subIndex];
  10241. if (!subMesh.IsGlobal) {
  10242. subMesh.updateBoundingInfo(matrix);
  10243. }
  10244. }
  10245. };
  10246. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10247. if (this._isWorldMatrixFrozen) {
  10248. return this._worldMatrix;
  10249. }
  10250. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10251. this._currentRenderId = this.getScene().getRenderId();
  10252. return this._worldMatrix;
  10253. }
  10254. this._cache.position.copyFrom(this.position);
  10255. this._cache.scaling.copyFrom(this.scaling);
  10256. this._cache.pivotMatrixUpdated = false;
  10257. this._cache.billboardMode = this.billboardMode;
  10258. this._currentRenderId = this.getScene().getRenderId();
  10259. this._isDirty = false;
  10260. // Scaling
  10261. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10262. // Rotation
  10263. //rotate, if quaternion is set and rotation was used
  10264. if (this.rotationQuaternion) {
  10265. var len = this.rotation.length();
  10266. if (len) {
  10267. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10268. this.rotation.copyFromFloats(0, 0, 0);
  10269. }
  10270. }
  10271. if (this.rotationQuaternion) {
  10272. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10273. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10274. }
  10275. else {
  10276. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10277. this._cache.rotation.copyFrom(this.rotation);
  10278. }
  10279. // Translation
  10280. if (this.infiniteDistance && !this.parent) {
  10281. var camera = this.getScene().activeCamera;
  10282. if (camera) {
  10283. var cameraWorldMatrix = camera.getWorldMatrix();
  10284. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10285. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10286. }
  10287. }
  10288. else {
  10289. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10290. }
  10291. // Composing transformations
  10292. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10293. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10294. // Billboarding
  10295. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10296. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10297. var localPosition = BABYLON.Tmp.Vector3[0];
  10298. if (this.parent && this.parent.getWorldMatrix) {
  10299. this._markSyncedWithParent();
  10300. var parentMatrix;
  10301. if (this._meshToBoneReferal) {
  10302. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10303. parentMatrix = BABYLON.Tmp.Matrix[6];
  10304. }
  10305. else {
  10306. parentMatrix = this.parent.getWorldMatrix();
  10307. }
  10308. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10309. localPosition = BABYLON.Tmp.Vector3[1];
  10310. }
  10311. var zero = this.getScene().activeCamera.globalPosition.clone();
  10312. if (this.parent && this.parent.position) {
  10313. localPosition.addInPlace(this.parent.position);
  10314. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10315. }
  10316. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10317. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10318. zero.x = localPosition.x + BABYLON.Epsilon;
  10319. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10320. zero.y = localPosition.y + BABYLON.Epsilon;
  10321. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10322. zero.z = localPosition.z + BABYLON.Epsilon;
  10323. }
  10324. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10325. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10326. BABYLON.Tmp.Matrix[3].invert();
  10327. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10328. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10329. }
  10330. // Local world
  10331. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10332. // Parent
  10333. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10334. this._markSyncedWithParent();
  10335. if (this._meshToBoneReferal) {
  10336. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10337. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10338. }
  10339. else {
  10340. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10341. }
  10342. }
  10343. else {
  10344. this._worldMatrix.copyFrom(this._localWorld);
  10345. }
  10346. // Bounding info
  10347. this._updateBoundingInfo();
  10348. // Absolute position
  10349. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10350. // Callbacks
  10351. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10352. if (!this._poseMatrix) {
  10353. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10354. }
  10355. return this._worldMatrix;
  10356. };
  10357. /**
  10358. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10359. * @param func: callback function to add
  10360. */
  10361. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10362. this.onAfterWorldMatrixUpdateObservable.add(func);
  10363. };
  10364. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10365. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10366. };
  10367. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10368. this.computeWorldMatrix();
  10369. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10370. };
  10371. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10372. this.computeWorldMatrix();
  10373. var invLocalWorldMatrix = this._localWorld.clone();
  10374. invLocalWorldMatrix.invert();
  10375. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10376. };
  10377. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10378. this.computeWorldMatrix(true);
  10379. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10380. };
  10381. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10382. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10383. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10384. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10385. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10386. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10387. /// <returns>Mesh oriented towards targetMesh</returns>
  10388. if (yawCor === void 0) { yawCor = 0; }
  10389. if (pitchCor === void 0) { pitchCor = 0; }
  10390. if (rollCor === void 0) { rollCor = 0; }
  10391. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10392. var dv = AbstractMesh._lookAtVectorCache;
  10393. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10394. targetPoint.subtractToRef(pos, dv);
  10395. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10396. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10397. var pitch = Math.atan2(dv.y, len);
  10398. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10399. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10400. };
  10401. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10402. this._meshToBoneReferal = affectedMesh;
  10403. this.parent = bone;
  10404. if (bone.getWorldMatrix().determinant() < 0) {
  10405. this.scalingDeterminant *= -1;
  10406. }
  10407. };
  10408. AbstractMesh.prototype.detachFromBone = function () {
  10409. if (this.parent.getWorldMatrix().determinant() < 0) {
  10410. this.scalingDeterminant *= -1;
  10411. }
  10412. this._meshToBoneReferal = null;
  10413. this.parent = null;
  10414. };
  10415. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10416. return this._boundingInfo.isInFrustum(frustumPlanes);
  10417. };
  10418. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10419. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10420. ;
  10421. };
  10422. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10423. if (!this._boundingInfo || !mesh._boundingInfo) {
  10424. return false;
  10425. }
  10426. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10427. };
  10428. AbstractMesh.prototype.intersectsPoint = function (point) {
  10429. if (!this._boundingInfo) {
  10430. return false;
  10431. }
  10432. return this._boundingInfo.intersectsPoint(point);
  10433. };
  10434. // Physics
  10435. /**
  10436. * @Deprecated. Use new PhysicsImpostor instead.
  10437. * */
  10438. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10439. //legacy support
  10440. if (impostor.impostor) {
  10441. options = impostor;
  10442. impostor = impostor.impostor;
  10443. }
  10444. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10445. return this.physicsImpostor.physicsBody;
  10446. };
  10447. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10448. return this.physicsImpostor;
  10449. };
  10450. /**
  10451. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10452. */
  10453. AbstractMesh.prototype.getPhysicsMass = function () {
  10454. return this.physicsImpostor.getParam("mass");
  10455. };
  10456. /**
  10457. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10458. */
  10459. AbstractMesh.prototype.getPhysicsFriction = function () {
  10460. return this.physicsImpostor.getParam("friction");
  10461. };
  10462. /**
  10463. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10464. */
  10465. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10466. return this.physicsImpostor.getParam("restitution");
  10467. };
  10468. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10469. if (!camera) {
  10470. camera = this.getScene().activeCamera;
  10471. }
  10472. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10473. };
  10474. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10475. if (!camera) {
  10476. camera = this.getScene().activeCamera;
  10477. }
  10478. return this.absolutePosition.subtract(camera.position).length();
  10479. };
  10480. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10481. if (!this.physicsImpostor) {
  10482. return;
  10483. }
  10484. this.physicsImpostor.applyImpulse(force, contactPoint);
  10485. };
  10486. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10487. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10488. return;
  10489. }
  10490. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10491. mainPivot: pivot1,
  10492. connectedPivot: pivot2,
  10493. nativeParams: options
  10494. });
  10495. };
  10496. /**
  10497. * @Deprecated
  10498. */
  10499. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10500. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10501. this.updatePhysicsBody();
  10502. };
  10503. /**
  10504. * @Deprecated
  10505. * Calling this function is not needed anymore.
  10506. * The physics engine takes care of transofmration automatically.
  10507. */
  10508. AbstractMesh.prototype.updatePhysicsBody = function () {
  10509. //Unneeded
  10510. };
  10511. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10512. // Collisions
  10513. get: function () {
  10514. return this._checkCollisions;
  10515. },
  10516. set: function (collisionEnabled) {
  10517. this._checkCollisions = collisionEnabled;
  10518. if (this.getScene().workerCollisions) {
  10519. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10520. }
  10521. },
  10522. enumerable: true,
  10523. configurable: true
  10524. });
  10525. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10526. var globalPosition = this.getAbsolutePosition();
  10527. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10528. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10529. this._collider.radius = this.ellipsoid;
  10530. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10531. };
  10532. // Submeshes octree
  10533. /**
  10534. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10535. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10536. */
  10537. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10538. if (maxCapacity === void 0) { maxCapacity = 64; }
  10539. if (maxDepth === void 0) { maxDepth = 2; }
  10540. if (!this._submeshesOctree) {
  10541. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10542. }
  10543. this.computeWorldMatrix(true);
  10544. // Update octree
  10545. var bbox = this.getBoundingInfo().boundingBox;
  10546. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10547. return this._submeshesOctree;
  10548. };
  10549. // Collisions
  10550. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10551. this._generatePointsArray();
  10552. // Transformation
  10553. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10554. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10555. subMesh._lastColliderWorldVertices = [];
  10556. subMesh._trianglePlanes = [];
  10557. var start = subMesh.verticesStart;
  10558. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10559. for (var i = start; i < end; i++) {
  10560. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10561. }
  10562. }
  10563. // Collide
  10564. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10565. if (collider.collisionFound) {
  10566. collider.collidedMesh = this;
  10567. }
  10568. };
  10569. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10570. var subMeshes;
  10571. var len;
  10572. // Octrees
  10573. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10574. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10575. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10576. len = intersections.length;
  10577. subMeshes = intersections.data;
  10578. }
  10579. else {
  10580. subMeshes = this.subMeshes;
  10581. len = subMeshes.length;
  10582. }
  10583. for (var index = 0; index < len; index++) {
  10584. var subMesh = subMeshes[index];
  10585. // Bounding test
  10586. if (len > 1 && !subMesh._checkCollision(collider))
  10587. continue;
  10588. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10589. }
  10590. };
  10591. AbstractMesh.prototype._checkCollision = function (collider) {
  10592. // Bounding box test
  10593. if (!this._boundingInfo._checkCollision(collider))
  10594. return;
  10595. // Transformation matrix
  10596. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10597. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10598. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10599. };
  10600. // Picking
  10601. AbstractMesh.prototype._generatePointsArray = function () {
  10602. return false;
  10603. };
  10604. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10605. var pickingInfo = new BABYLON.PickingInfo();
  10606. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10607. return pickingInfo;
  10608. }
  10609. if (!this._generatePointsArray()) {
  10610. return pickingInfo;
  10611. }
  10612. var intersectInfo = null;
  10613. // Octrees
  10614. var subMeshes;
  10615. var len;
  10616. if (this._submeshesOctree && this.useOctreeForPicking) {
  10617. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10618. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10619. len = intersections.length;
  10620. subMeshes = intersections.data;
  10621. }
  10622. else {
  10623. subMeshes = this.subMeshes;
  10624. len = subMeshes.length;
  10625. }
  10626. for (var index = 0; index < len; index++) {
  10627. var subMesh = subMeshes[index];
  10628. // Bounding test
  10629. if (len > 1 && !subMesh.canIntersects(ray))
  10630. continue;
  10631. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10632. if (currentIntersectInfo) {
  10633. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10634. intersectInfo = currentIntersectInfo;
  10635. intersectInfo.subMeshId = index;
  10636. if (fastCheck) {
  10637. break;
  10638. }
  10639. }
  10640. }
  10641. }
  10642. if (intersectInfo) {
  10643. // Get picked point
  10644. var world = this.getWorldMatrix();
  10645. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10646. var direction = ray.direction.clone();
  10647. direction = direction.scale(intersectInfo.distance);
  10648. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10649. var pickedPoint = worldOrigin.add(worldDirection);
  10650. // Return result
  10651. pickingInfo.hit = true;
  10652. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10653. pickingInfo.pickedPoint = pickedPoint;
  10654. pickingInfo.pickedMesh = this;
  10655. pickingInfo.bu = intersectInfo.bu;
  10656. pickingInfo.bv = intersectInfo.bv;
  10657. pickingInfo.faceId = intersectInfo.faceId;
  10658. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10659. return pickingInfo;
  10660. }
  10661. return pickingInfo;
  10662. };
  10663. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10664. return null;
  10665. };
  10666. AbstractMesh.prototype.releaseSubMeshes = function () {
  10667. if (this.subMeshes) {
  10668. while (this.subMeshes.length) {
  10669. this.subMeshes[0].dispose();
  10670. }
  10671. }
  10672. else {
  10673. this.subMeshes = new Array();
  10674. }
  10675. };
  10676. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10677. var _this = this;
  10678. var index;
  10679. // Action manager
  10680. if (this.actionManager) {
  10681. this.actionManager.dispose();
  10682. this.actionManager = null;
  10683. }
  10684. // Skeleton
  10685. this.skeleton = null;
  10686. // Animations
  10687. this.getScene().stopAnimation(this);
  10688. // Physics
  10689. if (this.physicsImpostor) {
  10690. this.physicsImpostor.dispose();
  10691. }
  10692. // Intersections in progress
  10693. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10694. var other = this._intersectionsInProgress[index];
  10695. var pos = other._intersectionsInProgress.indexOf(this);
  10696. other._intersectionsInProgress.splice(pos, 1);
  10697. }
  10698. this._intersectionsInProgress = [];
  10699. // Lights
  10700. var lights = this.getScene().lights;
  10701. lights.forEach(function (light) {
  10702. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10703. if (meshIndex !== -1) {
  10704. light.includedOnlyMeshes.splice(meshIndex, 1);
  10705. }
  10706. meshIndex = light.excludedMeshes.indexOf(_this);
  10707. if (meshIndex !== -1) {
  10708. light.excludedMeshes.splice(meshIndex, 1);
  10709. }
  10710. });
  10711. // Edges
  10712. if (this._edgesRenderer) {
  10713. this._edgesRenderer.dispose();
  10714. this._edgesRenderer = null;
  10715. }
  10716. // SubMeshes
  10717. this.releaseSubMeshes();
  10718. // Remove from scene
  10719. this.getScene().removeMesh(this);
  10720. if (!doNotRecurse) {
  10721. // Particles
  10722. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10723. if (this.getScene().particleSystems[index].emitter === this) {
  10724. this.getScene().particleSystems[index].dispose();
  10725. index--;
  10726. }
  10727. }
  10728. // Children
  10729. var objects = this.getDescendants(true);
  10730. for (index = 0; index < objects.length; index++) {
  10731. objects[index].dispose();
  10732. }
  10733. }
  10734. else {
  10735. var childMeshes = this.getChildMeshes(true);
  10736. for (index = 0; index < childMeshes.length; index++) {
  10737. var child = childMeshes[index];
  10738. child.parent = null;
  10739. child.computeWorldMatrix(true);
  10740. }
  10741. }
  10742. _super.prototype.dispose.call(this);
  10743. this.onAfterWorldMatrixUpdateObservable.clear();
  10744. this.onCollideObservable.clear();
  10745. this.onCollisionPositionChangeObservable.clear();
  10746. this._isDisposed = true;
  10747. // Callback
  10748. this.onDisposeObservable.notifyObservers(this);
  10749. this.onDisposeObservable.clear();
  10750. };
  10751. // Statics
  10752. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10753. AbstractMesh._BILLBOARDMODE_X = 1;
  10754. AbstractMesh._BILLBOARDMODE_Y = 2;
  10755. AbstractMesh._BILLBOARDMODE_Z = 4;
  10756. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10757. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  10758. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  10759. return AbstractMesh;
  10760. })(BABYLON.Node);
  10761. BABYLON.AbstractMesh = AbstractMesh;
  10762. })(BABYLON || (BABYLON = {}));
  10763. var BABYLON;
  10764. (function (BABYLON) {
  10765. var Light = (function (_super) {
  10766. __extends(Light, _super);
  10767. function Light(name, scene) {
  10768. _super.call(this, name, scene);
  10769. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  10770. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  10771. this.intensity = 1.0;
  10772. this.range = Number.MAX_VALUE;
  10773. this.includeOnlyWithLayerMask = 0;
  10774. this.includedOnlyMeshes = new Array();
  10775. this.excludedMeshes = new Array();
  10776. this.excludeWithLayerMask = 0;
  10777. // PBR Properties.
  10778. this.radius = 0.00001;
  10779. this._excludedMeshesIds = new Array();
  10780. this._includedOnlyMeshesIds = new Array();
  10781. scene.addLight(this);
  10782. }
  10783. /**
  10784. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10785. */
  10786. Light.prototype.toString = function (fullDetails) {
  10787. var ret = "Name: " + this.name;
  10788. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  10789. if (this.animations) {
  10790. for (var i = 0; i < this.animations.length; i++) {
  10791. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10792. }
  10793. }
  10794. if (fullDetails) {
  10795. }
  10796. return ret;
  10797. };
  10798. Light.prototype.getShadowGenerator = function () {
  10799. return this._shadowGenerator;
  10800. };
  10801. Light.prototype.getAbsolutePosition = function () {
  10802. return BABYLON.Vector3.Zero();
  10803. };
  10804. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10805. };
  10806. Light.prototype._getWorldMatrix = function () {
  10807. return BABYLON.Matrix.Identity();
  10808. };
  10809. Light.prototype.canAffectMesh = function (mesh) {
  10810. if (!mesh) {
  10811. return true;
  10812. }
  10813. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10814. return false;
  10815. }
  10816. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10817. return false;
  10818. }
  10819. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10820. return false;
  10821. }
  10822. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10823. return false;
  10824. }
  10825. return true;
  10826. };
  10827. Light.prototype.getWorldMatrix = function () {
  10828. this._currentRenderId = this.getScene().getRenderId();
  10829. var worldMatrix = this._getWorldMatrix();
  10830. if (this.parent && this.parent.getWorldMatrix) {
  10831. if (!this._parentedWorldMatrix) {
  10832. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10833. }
  10834. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10835. this._markSyncedWithParent();
  10836. return this._parentedWorldMatrix;
  10837. }
  10838. return worldMatrix;
  10839. };
  10840. Light.prototype.dispose = function () {
  10841. if (this._shadowGenerator) {
  10842. this._shadowGenerator.dispose();
  10843. this._shadowGenerator = null;
  10844. }
  10845. // Animations
  10846. this.getScene().stopAnimation(this);
  10847. // Remove from scene
  10848. this.getScene().removeLight(this);
  10849. _super.prototype.dispose.call(this);
  10850. };
  10851. Light.prototype.getTypeID = function () {
  10852. return 0;
  10853. };
  10854. Light.prototype.clone = function (name) {
  10855. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10856. };
  10857. Light.prototype.serialize = function () {
  10858. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10859. // Type
  10860. serializationObject.type = this.getTypeID();
  10861. // Parent
  10862. if (this.parent) {
  10863. serializationObject.parentId = this.parent.id;
  10864. }
  10865. // Inclusion / exclusions
  10866. if (this.excludedMeshes.length > 0) {
  10867. serializationObject.excludedMeshesIds = [];
  10868. this.excludedMeshes.forEach(function (mesh) {
  10869. serializationObject.excludedMeshesIds.push(mesh.id);
  10870. });
  10871. }
  10872. if (this.includedOnlyMeshes.length > 0) {
  10873. serializationObject.includedOnlyMeshesIds = [];
  10874. this.includedOnlyMeshes.forEach(function (mesh) {
  10875. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10876. });
  10877. }
  10878. // Animations
  10879. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10880. serializationObject.ranges = this.serializeAnimationRanges();
  10881. return serializationObject;
  10882. };
  10883. Light.GetConstructorFromName = function (type, name, scene) {
  10884. switch (type) {
  10885. case 0:
  10886. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10887. case 1:
  10888. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10889. case 2:
  10890. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10891. case 3:
  10892. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10893. }
  10894. };
  10895. Light.Parse = function (parsedLight, scene) {
  10896. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10897. // Inclusion / exclusions
  10898. if (parsedLight.excludedMeshesIds) {
  10899. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10900. }
  10901. if (parsedLight.includedOnlyMeshesIds) {
  10902. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10903. }
  10904. // Parent
  10905. if (parsedLight.parentId) {
  10906. light._waitingParentId = parsedLight.parentId;
  10907. }
  10908. // Animations
  10909. if (parsedLight.animations) {
  10910. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10911. var parsedAnimation = parsedLight.animations[animationIndex];
  10912. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10913. }
  10914. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10915. }
  10916. if (parsedLight.autoAnimate) {
  10917. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10918. }
  10919. return light;
  10920. };
  10921. __decorate([
  10922. BABYLON.serializeAsColor3()
  10923. ], Light.prototype, "diffuse", void 0);
  10924. __decorate([
  10925. BABYLON.serializeAsColor3()
  10926. ], Light.prototype, "specular", void 0);
  10927. __decorate([
  10928. BABYLON.serialize()
  10929. ], Light.prototype, "intensity", void 0);
  10930. __decorate([
  10931. BABYLON.serialize()
  10932. ], Light.prototype, "range", void 0);
  10933. __decorate([
  10934. BABYLON.serialize()
  10935. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10936. __decorate([
  10937. BABYLON.serialize()
  10938. ], Light.prototype, "excludeWithLayerMask", void 0);
  10939. __decorate([
  10940. BABYLON.serialize()
  10941. ], Light.prototype, "radius", void 0);
  10942. return Light;
  10943. })(BABYLON.Node);
  10944. BABYLON.Light = Light;
  10945. })(BABYLON || (BABYLON = {}));
  10946. var BABYLON;
  10947. (function (BABYLON) {
  10948. var PointLight = (function (_super) {
  10949. __extends(PointLight, _super);
  10950. function PointLight(name, position, scene) {
  10951. _super.call(this, name, scene);
  10952. this.position = position;
  10953. }
  10954. PointLight.prototype.getAbsolutePosition = function () {
  10955. return this.transformedPosition ? this.transformedPosition : this.position;
  10956. };
  10957. PointLight.prototype.computeTransformedPosition = function () {
  10958. if (this.parent && this.parent.getWorldMatrix) {
  10959. if (!this.transformedPosition) {
  10960. this.transformedPosition = BABYLON.Vector3.Zero();
  10961. }
  10962. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10963. return true;
  10964. }
  10965. return false;
  10966. };
  10967. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10968. if (this.parent && this.parent.getWorldMatrix) {
  10969. this.computeTransformedPosition();
  10970. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10971. return;
  10972. }
  10973. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10974. };
  10975. PointLight.prototype.needCube = function () {
  10976. return true;
  10977. };
  10978. PointLight.prototype.supportsVSM = function () {
  10979. return false;
  10980. };
  10981. PointLight.prototype.needRefreshPerFrame = function () {
  10982. return false;
  10983. };
  10984. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10985. switch (faceIndex) {
  10986. case 0:
  10987. return new BABYLON.Vector3(1, 0, 0);
  10988. case 1:
  10989. return new BABYLON.Vector3(-1, 0, 0);
  10990. case 2:
  10991. return new BABYLON.Vector3(0, -1, 0);
  10992. case 3:
  10993. return new BABYLON.Vector3(0, 1, 0);
  10994. case 4:
  10995. return new BABYLON.Vector3(0, 0, 1);
  10996. case 5:
  10997. return new BABYLON.Vector3(0, 0, -1);
  10998. }
  10999. return BABYLON.Vector3.Zero();
  11000. };
  11001. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11002. var activeCamera = this.getScene().activeCamera;
  11003. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11004. };
  11005. PointLight.prototype._getWorldMatrix = function () {
  11006. if (!this._worldMatrix) {
  11007. this._worldMatrix = BABYLON.Matrix.Identity();
  11008. }
  11009. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11010. return this._worldMatrix;
  11011. };
  11012. PointLight.prototype.getTypeID = function () {
  11013. return 0;
  11014. };
  11015. __decorate([
  11016. BABYLON.serializeAsVector3()
  11017. ], PointLight.prototype, "position", void 0);
  11018. return PointLight;
  11019. })(BABYLON.Light);
  11020. BABYLON.PointLight = PointLight;
  11021. })(BABYLON || (BABYLON = {}));
  11022. var BABYLON;
  11023. (function (BABYLON) {
  11024. var SpotLight = (function (_super) {
  11025. __extends(SpotLight, _super);
  11026. function SpotLight(name, position, direction, angle, exponent, scene) {
  11027. _super.call(this, name, scene);
  11028. this.position = position;
  11029. this.direction = direction;
  11030. this.angle = angle;
  11031. this.exponent = exponent;
  11032. }
  11033. SpotLight.prototype.getAbsolutePosition = function () {
  11034. return this.transformedPosition ? this.transformedPosition : this.position;
  11035. };
  11036. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11037. var activeCamera = this.getScene().activeCamera;
  11038. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11039. };
  11040. SpotLight.prototype.needCube = function () {
  11041. return false;
  11042. };
  11043. SpotLight.prototype.supportsVSM = function () {
  11044. return true;
  11045. };
  11046. SpotLight.prototype.needRefreshPerFrame = function () {
  11047. return false;
  11048. };
  11049. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11050. return this.direction;
  11051. };
  11052. SpotLight.prototype.setDirectionToTarget = function (target) {
  11053. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11054. return this.direction;
  11055. };
  11056. SpotLight.prototype.computeTransformedPosition = function () {
  11057. if (this.parent && this.parent.getWorldMatrix) {
  11058. if (!this.transformedPosition) {
  11059. this.transformedPosition = BABYLON.Vector3.Zero();
  11060. }
  11061. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11062. return true;
  11063. }
  11064. return false;
  11065. };
  11066. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11067. var normalizeDirection;
  11068. if (this.parent && this.parent.getWorldMatrix) {
  11069. if (!this._transformedDirection) {
  11070. this._transformedDirection = BABYLON.Vector3.Zero();
  11071. }
  11072. this.computeTransformedPosition();
  11073. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11074. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11075. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11076. }
  11077. else {
  11078. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11079. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11080. }
  11081. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11082. };
  11083. SpotLight.prototype._getWorldMatrix = function () {
  11084. if (!this._worldMatrix) {
  11085. this._worldMatrix = BABYLON.Matrix.Identity();
  11086. }
  11087. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11088. return this._worldMatrix;
  11089. };
  11090. SpotLight.prototype.getTypeID = function () {
  11091. return 2;
  11092. };
  11093. __decorate([
  11094. BABYLON.serializeAsVector3()
  11095. ], SpotLight.prototype, "position", void 0);
  11096. __decorate([
  11097. BABYLON.serializeAsVector3()
  11098. ], SpotLight.prototype, "direction", void 0);
  11099. __decorate([
  11100. BABYLON.serialize()
  11101. ], SpotLight.prototype, "angle", void 0);
  11102. __decorate([
  11103. BABYLON.serialize()
  11104. ], SpotLight.prototype, "exponent", void 0);
  11105. return SpotLight;
  11106. })(BABYLON.Light);
  11107. BABYLON.SpotLight = SpotLight;
  11108. })(BABYLON || (BABYLON = {}));
  11109. var BABYLON;
  11110. (function (BABYLON) {
  11111. var HemisphericLight = (function (_super) {
  11112. __extends(HemisphericLight, _super);
  11113. function HemisphericLight(name, direction, scene) {
  11114. _super.call(this, name, scene);
  11115. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11116. this.direction = direction;
  11117. }
  11118. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11119. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11120. return this.direction;
  11121. };
  11122. HemisphericLight.prototype.getShadowGenerator = function () {
  11123. return null;
  11124. };
  11125. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11126. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11127. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11128. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11129. };
  11130. HemisphericLight.prototype._getWorldMatrix = function () {
  11131. if (!this._worldMatrix) {
  11132. this._worldMatrix = BABYLON.Matrix.Identity();
  11133. }
  11134. return this._worldMatrix;
  11135. };
  11136. HemisphericLight.prototype.getTypeID = function () {
  11137. return 3;
  11138. };
  11139. __decorate([
  11140. BABYLON.serializeAsColor3()
  11141. ], HemisphericLight.prototype, "groundColor", void 0);
  11142. __decorate([
  11143. BABYLON.serializeAsVector3()
  11144. ], HemisphericLight.prototype, "direction", void 0);
  11145. return HemisphericLight;
  11146. })(BABYLON.Light);
  11147. BABYLON.HemisphericLight = HemisphericLight;
  11148. })(BABYLON || (BABYLON = {}));
  11149. var BABYLON;
  11150. (function (BABYLON) {
  11151. var DirectionalLight = (function (_super) {
  11152. __extends(DirectionalLight, _super);
  11153. function DirectionalLight(name, direction, scene) {
  11154. _super.call(this, name, scene);
  11155. this.shadowOrthoScale = 0.5;
  11156. this.autoUpdateExtends = true;
  11157. // Cache
  11158. this._orthoLeft = Number.MAX_VALUE;
  11159. this._orthoRight = Number.MIN_VALUE;
  11160. this._orthoTop = Number.MIN_VALUE;
  11161. this._orthoBottom = Number.MAX_VALUE;
  11162. this.position = direction.scale(-1);
  11163. this.direction = direction;
  11164. }
  11165. DirectionalLight.prototype.getAbsolutePosition = function () {
  11166. return this.transformedPosition ? this.transformedPosition : this.position;
  11167. };
  11168. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11169. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11170. return this.direction;
  11171. };
  11172. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11173. var activeCamera = this.getScene().activeCamera;
  11174. // Check extends
  11175. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11176. var tempVector3 = BABYLON.Vector3.Zero();
  11177. this._orthoLeft = Number.MAX_VALUE;
  11178. this._orthoRight = Number.MIN_VALUE;
  11179. this._orthoTop = Number.MIN_VALUE;
  11180. this._orthoBottom = Number.MAX_VALUE;
  11181. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11182. var mesh = renderList[meshIndex];
  11183. if (!mesh) {
  11184. continue;
  11185. }
  11186. var boundingInfo = mesh.getBoundingInfo();
  11187. if (!boundingInfo) {
  11188. continue;
  11189. }
  11190. var boundingBox = boundingInfo.boundingBox;
  11191. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11192. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11193. if (tempVector3.x < this._orthoLeft)
  11194. this._orthoLeft = tempVector3.x;
  11195. if (tempVector3.y < this._orthoBottom)
  11196. this._orthoBottom = tempVector3.y;
  11197. if (tempVector3.x > this._orthoRight)
  11198. this._orthoRight = tempVector3.x;
  11199. if (tempVector3.y > this._orthoTop)
  11200. this._orthoTop = tempVector3.y;
  11201. }
  11202. }
  11203. }
  11204. var xOffset = this._orthoRight - this._orthoLeft;
  11205. var yOffset = this._orthoTop - this._orthoBottom;
  11206. 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);
  11207. };
  11208. DirectionalLight.prototype.supportsVSM = function () {
  11209. return true;
  11210. };
  11211. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11212. return true;
  11213. };
  11214. DirectionalLight.prototype.needCube = function () {
  11215. return false;
  11216. };
  11217. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11218. return this.direction;
  11219. };
  11220. DirectionalLight.prototype.computeTransformedPosition = function () {
  11221. if (this.parent && this.parent.getWorldMatrix) {
  11222. if (!this.transformedPosition) {
  11223. this.transformedPosition = BABYLON.Vector3.Zero();
  11224. }
  11225. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11226. return true;
  11227. }
  11228. return false;
  11229. };
  11230. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11231. if (this.parent && this.parent.getWorldMatrix) {
  11232. if (!this._transformedDirection) {
  11233. this._transformedDirection = BABYLON.Vector3.Zero();
  11234. }
  11235. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11236. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11237. return;
  11238. }
  11239. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11240. };
  11241. DirectionalLight.prototype._getWorldMatrix = function () {
  11242. if (!this._worldMatrix) {
  11243. this._worldMatrix = BABYLON.Matrix.Identity();
  11244. }
  11245. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11246. return this._worldMatrix;
  11247. };
  11248. DirectionalLight.prototype.getTypeID = function () {
  11249. return 1;
  11250. };
  11251. __decorate([
  11252. BABYLON.serializeAsVector3()
  11253. ], DirectionalLight.prototype, "position", void 0);
  11254. __decorate([
  11255. BABYLON.serializeAsVector3()
  11256. ], DirectionalLight.prototype, "direction", void 0);
  11257. __decorate([
  11258. BABYLON.serialize()
  11259. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11260. __decorate([
  11261. BABYLON.serialize()
  11262. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11263. return DirectionalLight;
  11264. })(BABYLON.Light);
  11265. BABYLON.DirectionalLight = DirectionalLight;
  11266. })(BABYLON || (BABYLON = {}));
  11267. var BABYLON;
  11268. (function (BABYLON) {
  11269. var ShadowGenerator = (function () {
  11270. function ShadowGenerator(mapSize, light) {
  11271. var _this = this;
  11272. // Members
  11273. this._filter = ShadowGenerator.FILTER_NONE;
  11274. this.blurScale = 2;
  11275. this._blurBoxOffset = 0;
  11276. this._bias = 0.00005;
  11277. this._lightDirection = BABYLON.Vector3.Zero();
  11278. this.forceBackFacesOnly = false;
  11279. this._darkness = 0;
  11280. this._transparencyShadow = false;
  11281. this._viewMatrix = BABYLON.Matrix.Zero();
  11282. this._projectionMatrix = BABYLON.Matrix.Zero();
  11283. this._transformMatrix = BABYLON.Matrix.Zero();
  11284. this._worldViewProjection = BABYLON.Matrix.Zero();
  11285. this._currentFaceIndex = 0;
  11286. this._currentFaceIndexCache = 0;
  11287. this._useFullFloat = true;
  11288. this._light = light;
  11289. this._scene = light.getScene();
  11290. this._mapSize = mapSize;
  11291. light._shadowGenerator = this;
  11292. // Texture type fallback from float to int if not supported.
  11293. var textureType;
  11294. var caps = this._scene.getEngine().getCaps();
  11295. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11296. this._useFullFloat = true;
  11297. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11298. }
  11299. else {
  11300. this._useFullFloat = false;
  11301. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11302. }
  11303. // Render target
  11304. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11305. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11306. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11307. this._shadowMap.anisotropicFilteringLevel = 1;
  11308. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11309. this._shadowMap.renderParticles = false;
  11310. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11311. _this._currentFaceIndex = faceIndex;
  11312. });
  11313. this._shadowMap.onAfterUnbindObservable.add(function () {
  11314. if (!_this.useBlurVarianceShadowMap) {
  11315. return;
  11316. }
  11317. if (!_this._shadowMap2) {
  11318. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11319. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11320. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11321. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11322. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11323. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11324. effect.setTexture("textureSampler", _this._shadowMap);
  11325. });
  11326. _this.blurBoxOffset = 1;
  11327. }
  11328. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11329. });
  11330. // Custom render function
  11331. var renderSubMesh = function (subMesh) {
  11332. var mesh = subMesh.getRenderingMesh();
  11333. var scene = _this._scene;
  11334. var engine = scene.getEngine();
  11335. // Culling
  11336. engine.setState(subMesh.getMaterial().backFaceCulling);
  11337. // Managing instances
  11338. var batch = mesh._getInstancesRenderList(subMesh._id);
  11339. if (batch.mustReturn) {
  11340. return;
  11341. }
  11342. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11343. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11344. engine.enableEffect(_this._effect);
  11345. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11346. var material = subMesh.getMaterial();
  11347. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11348. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11349. if (_this.getLight().needCube()) {
  11350. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11351. }
  11352. // Alpha test
  11353. if (material && material.needAlphaTesting()) {
  11354. var alphaTexture = material.getAlphaTestTexture();
  11355. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11356. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11357. }
  11358. // Bones
  11359. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11360. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11361. }
  11362. if (_this.forceBackFacesOnly) {
  11363. engine.setState(true, 0, false, true);
  11364. }
  11365. // Draw
  11366. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11367. if (_this.forceBackFacesOnly) {
  11368. engine.setState(true, 0, false, false);
  11369. }
  11370. }
  11371. else {
  11372. // Need to reset refresh rate of the shadowMap
  11373. _this._shadowMap.resetRefreshCounter();
  11374. }
  11375. };
  11376. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11377. var index;
  11378. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11379. renderSubMesh(opaqueSubMeshes.data[index]);
  11380. }
  11381. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11382. renderSubMesh(alphaTestSubMeshes.data[index]);
  11383. }
  11384. if (_this._transparencyShadow) {
  11385. for (index = 0; index < transparentSubMeshes.length; index++) {
  11386. renderSubMesh(transparentSubMeshes.data[index]);
  11387. }
  11388. }
  11389. };
  11390. this._shadowMap.onClearObservable.add(function (engine) {
  11391. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11392. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11393. }
  11394. else {
  11395. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11396. }
  11397. });
  11398. }
  11399. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11400. // Static
  11401. get: function () {
  11402. return ShadowGenerator._FILTER_NONE;
  11403. },
  11404. enumerable: true,
  11405. configurable: true
  11406. });
  11407. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11408. get: function () {
  11409. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11410. },
  11411. enumerable: true,
  11412. configurable: true
  11413. });
  11414. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11415. get: function () {
  11416. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11417. },
  11418. enumerable: true,
  11419. configurable: true
  11420. });
  11421. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11422. get: function () {
  11423. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11424. },
  11425. enumerable: true,
  11426. configurable: true
  11427. });
  11428. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11429. get: function () {
  11430. return this._bias;
  11431. },
  11432. set: function (bias) {
  11433. this._bias = bias;
  11434. },
  11435. enumerable: true,
  11436. configurable: true
  11437. });
  11438. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11439. get: function () {
  11440. return this._blurBoxOffset;
  11441. },
  11442. set: function (value) {
  11443. var _this = this;
  11444. if (this._blurBoxOffset === value) {
  11445. return;
  11446. }
  11447. this._blurBoxOffset = value;
  11448. if (this._boxBlurPostprocess) {
  11449. this._boxBlurPostprocess.dispose();
  11450. }
  11451. 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);
  11452. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11453. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11454. });
  11455. },
  11456. enumerable: true,
  11457. configurable: true
  11458. });
  11459. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11460. get: function () {
  11461. return this._filter;
  11462. },
  11463. set: function (value) {
  11464. if (this._filter === value) {
  11465. return;
  11466. }
  11467. this._filter = value;
  11468. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11469. this._shadowMap.anisotropicFilteringLevel = 16;
  11470. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11471. }
  11472. else {
  11473. this._shadowMap.anisotropicFilteringLevel = 1;
  11474. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11475. }
  11476. },
  11477. enumerable: true,
  11478. configurable: true
  11479. });
  11480. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11481. get: function () {
  11482. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11483. },
  11484. set: function (value) {
  11485. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11486. },
  11487. enumerable: true,
  11488. configurable: true
  11489. });
  11490. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11491. get: function () {
  11492. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11493. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11494. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11495. },
  11496. set: function (value) {
  11497. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11498. },
  11499. enumerable: true,
  11500. configurable: true
  11501. });
  11502. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11503. get: function () {
  11504. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11505. },
  11506. set: function (value) {
  11507. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11508. },
  11509. enumerable: true,
  11510. configurable: true
  11511. });
  11512. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11513. var defines = [];
  11514. if (this._useFullFloat) {
  11515. defines.push("#define FULLFLOAT");
  11516. }
  11517. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11518. defines.push("#define VSM");
  11519. }
  11520. if (this.getLight().needCube()) {
  11521. defines.push("#define CUBEMAP");
  11522. }
  11523. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11524. var mesh = subMesh.getMesh();
  11525. var material = subMesh.getMaterial();
  11526. // Alpha test
  11527. if (material && material.needAlphaTesting()) {
  11528. defines.push("#define ALPHATEST");
  11529. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11530. attribs.push(BABYLON.VertexBuffer.UVKind);
  11531. defines.push("#define UV1");
  11532. }
  11533. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11534. var alphaTexture = material.getAlphaTestTexture();
  11535. if (alphaTexture.coordinatesIndex === 1) {
  11536. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11537. defines.push("#define UV2");
  11538. }
  11539. }
  11540. }
  11541. // Bones
  11542. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11543. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11544. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11545. if (mesh.numBoneInfluencers > 4) {
  11546. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11547. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11548. }
  11549. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11550. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11551. }
  11552. else {
  11553. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11554. }
  11555. // Instances
  11556. if (useInstances) {
  11557. defines.push("#define INSTANCES");
  11558. attribs.push("world0");
  11559. attribs.push("world1");
  11560. attribs.push("world2");
  11561. attribs.push("world3");
  11562. }
  11563. // Get correct effect
  11564. var join = defines.join("\n");
  11565. if (this._cachedDefines !== join) {
  11566. this._cachedDefines = join;
  11567. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11568. }
  11569. return this._effect.isReady();
  11570. };
  11571. ShadowGenerator.prototype.getShadowMap = function () {
  11572. return this._shadowMap;
  11573. };
  11574. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11575. if (this._shadowMap2) {
  11576. return this._shadowMap2;
  11577. }
  11578. return this._shadowMap;
  11579. };
  11580. ShadowGenerator.prototype.getLight = function () {
  11581. return this._light;
  11582. };
  11583. // Methods
  11584. ShadowGenerator.prototype.getTransformMatrix = function () {
  11585. var scene = this._scene;
  11586. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11587. return this._transformMatrix;
  11588. }
  11589. this._currentRenderID = scene.getRenderId();
  11590. this._currentFaceIndexCache = this._currentFaceIndex;
  11591. var lightPosition = this._light.position;
  11592. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11593. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11594. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11595. }
  11596. if (this._light.computeTransformedPosition()) {
  11597. lightPosition = this._light.transformedPosition;
  11598. }
  11599. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11600. this._cachedPosition = lightPosition.clone();
  11601. this._cachedDirection = this._lightDirection.clone();
  11602. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11603. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11604. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11605. }
  11606. return this._transformMatrix;
  11607. };
  11608. ShadowGenerator.prototype.getDarkness = function () {
  11609. return this._darkness;
  11610. };
  11611. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11612. if (darkness >= 1.0)
  11613. this._darkness = 1.0;
  11614. else if (darkness <= 0.0)
  11615. this._darkness = 0.0;
  11616. else
  11617. this._darkness = darkness;
  11618. };
  11619. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11620. this._transparencyShadow = hasShadow;
  11621. };
  11622. ShadowGenerator.prototype._packHalf = function (depth) {
  11623. var scale = depth * 255.0;
  11624. var fract = scale - Math.floor(scale);
  11625. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11626. };
  11627. ShadowGenerator.prototype.dispose = function () {
  11628. this._shadowMap.dispose();
  11629. if (this._shadowMap2) {
  11630. this._shadowMap2.dispose();
  11631. }
  11632. if (this._downSamplePostprocess) {
  11633. this._downSamplePostprocess.dispose();
  11634. }
  11635. if (this._boxBlurPostprocess) {
  11636. this._boxBlurPostprocess.dispose();
  11637. }
  11638. };
  11639. ShadowGenerator.prototype.serialize = function () {
  11640. var serializationObject = {};
  11641. serializationObject.lightId = this._light.id;
  11642. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11643. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11644. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11645. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11646. serializationObject.renderList = [];
  11647. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11648. var mesh = this.getShadowMap().renderList[meshIndex];
  11649. serializationObject.renderList.push(mesh.id);
  11650. }
  11651. return serializationObject;
  11652. };
  11653. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11654. //casting to point light, as light is missing the position attr and typescript complains.
  11655. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11656. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11657. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11658. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11659. meshes.forEach(function (mesh) {
  11660. shadowGenerator.getShadowMap().renderList.push(mesh);
  11661. });
  11662. }
  11663. if (parsedShadowGenerator.usePoissonSampling) {
  11664. shadowGenerator.usePoissonSampling = true;
  11665. }
  11666. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11667. shadowGenerator.useVarianceShadowMap = true;
  11668. }
  11669. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11670. shadowGenerator.useBlurVarianceShadowMap = true;
  11671. if (parsedShadowGenerator.blurScale) {
  11672. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11673. }
  11674. if (parsedShadowGenerator.blurBoxOffset) {
  11675. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11676. }
  11677. }
  11678. if (parsedShadowGenerator.bias !== undefined) {
  11679. shadowGenerator.bias = parsedShadowGenerator.bias;
  11680. }
  11681. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11682. return shadowGenerator;
  11683. };
  11684. ShadowGenerator._FILTER_NONE = 0;
  11685. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11686. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11687. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11688. return ShadowGenerator;
  11689. })();
  11690. BABYLON.ShadowGenerator = ShadowGenerator;
  11691. })(BABYLON || (BABYLON = {}));
  11692. var BABYLON;
  11693. (function (BABYLON) {
  11694. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  11695. if (boxMin.x > sphereCenter.x + sphereRadius)
  11696. return false;
  11697. if (sphereCenter.x - sphereRadius > boxMax.x)
  11698. return false;
  11699. if (boxMin.y > sphereCenter.y + sphereRadius)
  11700. return false;
  11701. if (sphereCenter.y - sphereRadius > boxMax.y)
  11702. return false;
  11703. if (boxMin.z > sphereCenter.z + sphereRadius)
  11704. return false;
  11705. if (sphereCenter.z - sphereRadius > boxMax.z)
  11706. return false;
  11707. return true;
  11708. };
  11709. var getLowestRoot = (function () {
  11710. var result = { root: 0, found: false };
  11711. return function (a, b, c, maxR) {
  11712. result.root = 0;
  11713. result.found = false;
  11714. var determinant = b * b - 4.0 * a * c;
  11715. if (determinant < 0)
  11716. return result;
  11717. var sqrtD = Math.sqrt(determinant);
  11718. var r1 = (-b - sqrtD) / (2.0 * a);
  11719. var r2 = (-b + sqrtD) / (2.0 * a);
  11720. if (r1 > r2) {
  11721. var temp = r2;
  11722. r2 = r1;
  11723. r1 = temp;
  11724. }
  11725. if (r1 > 0 && r1 < maxR) {
  11726. result.root = r1;
  11727. result.found = true;
  11728. return result;
  11729. }
  11730. if (r2 > 0 && r2 < maxR) {
  11731. result.root = r2;
  11732. result.found = true;
  11733. return result;
  11734. }
  11735. return result;
  11736. };
  11737. })();
  11738. var Collider = (function () {
  11739. function Collider() {
  11740. this.radius = new BABYLON.Vector3(1, 1, 1);
  11741. this.retry = 0;
  11742. this.basePointWorld = BABYLON.Vector3.Zero();
  11743. this.velocityWorld = BABYLON.Vector3.Zero();
  11744. this.normalizedVelocity = BABYLON.Vector3.Zero();
  11745. this._collisionPoint = BABYLON.Vector3.Zero();
  11746. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  11747. this._tempVector = BABYLON.Vector3.Zero();
  11748. this._tempVector2 = BABYLON.Vector3.Zero();
  11749. this._tempVector3 = BABYLON.Vector3.Zero();
  11750. this._tempVector4 = BABYLON.Vector3.Zero();
  11751. this._edge = BABYLON.Vector3.Zero();
  11752. this._baseToVertex = BABYLON.Vector3.Zero();
  11753. this._destinationPoint = BABYLON.Vector3.Zero();
  11754. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  11755. this._displacementVector = BABYLON.Vector3.Zero();
  11756. }
  11757. // Methods
  11758. Collider.prototype._initialize = function (source, dir, e) {
  11759. this.velocity = dir;
  11760. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  11761. this.basePoint = source;
  11762. source.multiplyToRef(this.radius, this.basePointWorld);
  11763. dir.multiplyToRef(this.radius, this.velocityWorld);
  11764. this.velocityWorldLength = this.velocityWorld.length();
  11765. this.epsilon = e;
  11766. this.collisionFound = false;
  11767. };
  11768. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  11769. pa.subtractToRef(point, this._tempVector);
  11770. pb.subtractToRef(point, this._tempVector2);
  11771. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  11772. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11773. if (d < 0)
  11774. return false;
  11775. pc.subtractToRef(point, this._tempVector3);
  11776. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  11777. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11778. if (d < 0)
  11779. return false;
  11780. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  11781. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11782. return d >= 0;
  11783. };
  11784. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  11785. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  11786. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  11787. if (distance > this.velocityWorldLength + max + sphereRadius) {
  11788. return false;
  11789. }
  11790. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  11791. return false;
  11792. return true;
  11793. };
  11794. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  11795. var t0;
  11796. var embeddedInPlane = false;
  11797. //defensive programming, actually not needed.
  11798. if (!trianglePlaneArray) {
  11799. trianglePlaneArray = [];
  11800. }
  11801. if (!trianglePlaneArray[faceIndex]) {
  11802. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  11803. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  11804. }
  11805. var trianglePlane = trianglePlaneArray[faceIndex];
  11806. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  11807. return;
  11808. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  11809. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  11810. if (normalDotVelocity == 0) {
  11811. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  11812. return;
  11813. embeddedInPlane = true;
  11814. t0 = 0;
  11815. }
  11816. else {
  11817. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11818. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11819. if (t0 > t1) {
  11820. var temp = t1;
  11821. t1 = t0;
  11822. t0 = temp;
  11823. }
  11824. if (t0 > 1.0 || t1 < 0.0)
  11825. return;
  11826. if (t0 < 0)
  11827. t0 = 0;
  11828. if (t0 > 1.0)
  11829. t0 = 1.0;
  11830. }
  11831. this._collisionPoint.copyFromFloats(0, 0, 0);
  11832. var found = false;
  11833. var t = 1.0;
  11834. if (!embeddedInPlane) {
  11835. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  11836. this.velocity.scaleToRef(t0, this._tempVector);
  11837. this._planeIntersectionPoint.addInPlace(this._tempVector);
  11838. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  11839. found = true;
  11840. t = t0;
  11841. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  11842. }
  11843. }
  11844. if (!found) {
  11845. var velocitySquaredLength = this.velocity.lengthSquared();
  11846. var a = velocitySquaredLength;
  11847. this.basePoint.subtractToRef(p1, this._tempVector);
  11848. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11849. var c = this._tempVector.lengthSquared() - 1.0;
  11850. var lowestRoot = getLowestRoot(a, b, c, t);
  11851. if (lowestRoot.found) {
  11852. t = lowestRoot.root;
  11853. found = true;
  11854. this._collisionPoint.copyFrom(p1);
  11855. }
  11856. this.basePoint.subtractToRef(p2, this._tempVector);
  11857. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11858. c = this._tempVector.lengthSquared() - 1.0;
  11859. lowestRoot = getLowestRoot(a, b, c, t);
  11860. if (lowestRoot.found) {
  11861. t = lowestRoot.root;
  11862. found = true;
  11863. this._collisionPoint.copyFrom(p2);
  11864. }
  11865. this.basePoint.subtractToRef(p3, this._tempVector);
  11866. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11867. c = this._tempVector.lengthSquared() - 1.0;
  11868. lowestRoot = getLowestRoot(a, b, c, t);
  11869. if (lowestRoot.found) {
  11870. t = lowestRoot.root;
  11871. found = true;
  11872. this._collisionPoint.copyFrom(p3);
  11873. }
  11874. p2.subtractToRef(p1, this._edge);
  11875. p1.subtractToRef(this.basePoint, this._baseToVertex);
  11876. var edgeSquaredLength = this._edge.lengthSquared();
  11877. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11878. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11879. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11880. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11881. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11882. lowestRoot = getLowestRoot(a, b, c, t);
  11883. if (lowestRoot.found) {
  11884. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11885. if (f >= 0.0 && f <= 1.0) {
  11886. t = lowestRoot.root;
  11887. found = true;
  11888. this._edge.scaleInPlace(f);
  11889. p1.addToRef(this._edge, this._collisionPoint);
  11890. }
  11891. }
  11892. p3.subtractToRef(p2, this._edge);
  11893. p2.subtractToRef(this.basePoint, this._baseToVertex);
  11894. edgeSquaredLength = this._edge.lengthSquared();
  11895. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11896. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11897. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11898. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11899. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11900. lowestRoot = getLowestRoot(a, b, c, t);
  11901. if (lowestRoot.found) {
  11902. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11903. if (f >= 0.0 && f <= 1.0) {
  11904. t = lowestRoot.root;
  11905. found = true;
  11906. this._edge.scaleInPlace(f);
  11907. p2.addToRef(this._edge, this._collisionPoint);
  11908. }
  11909. }
  11910. p1.subtractToRef(p3, this._edge);
  11911. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11912. edgeSquaredLength = this._edge.lengthSquared();
  11913. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11914. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11915. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11916. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11917. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11918. lowestRoot = getLowestRoot(a, b, c, t);
  11919. if (lowestRoot.found) {
  11920. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11921. if (f >= 0.0 && f <= 1.0) {
  11922. t = lowestRoot.root;
  11923. found = true;
  11924. this._edge.scaleInPlace(f);
  11925. p3.addToRef(this._edge, this._collisionPoint);
  11926. }
  11927. }
  11928. }
  11929. if (found) {
  11930. var distToCollision = t * this.velocity.length();
  11931. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11932. if (!this.intersectionPoint) {
  11933. this.intersectionPoint = this._collisionPoint.clone();
  11934. }
  11935. else {
  11936. this.intersectionPoint.copyFrom(this._collisionPoint);
  11937. }
  11938. this.nearestDistance = distToCollision;
  11939. this.collisionFound = true;
  11940. }
  11941. }
  11942. };
  11943. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11944. for (var i = indexStart; i < indexEnd; i += 3) {
  11945. var p1 = pts[indices[i] - decal];
  11946. var p2 = pts[indices[i + 1] - decal];
  11947. var p3 = pts[indices[i + 2] - decal];
  11948. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11949. }
  11950. };
  11951. Collider.prototype._getResponse = function (pos, vel) {
  11952. pos.addToRef(vel, this._destinationPoint);
  11953. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11954. this.basePoint.addToRef(vel, pos);
  11955. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11956. this._slidePlaneNormal.normalize();
  11957. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11958. pos.addInPlace(this._displacementVector);
  11959. this.intersectionPoint.addInPlace(this._displacementVector);
  11960. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11961. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11962. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11963. };
  11964. return Collider;
  11965. })();
  11966. BABYLON.Collider = Collider;
  11967. })(BABYLON || (BABYLON = {}));
  11968. var BABYLON;
  11969. (function (BABYLON) {
  11970. //WebWorker code will be inserted to this variable.
  11971. BABYLON.CollisionWorker = "";
  11972. (function (WorkerTaskType) {
  11973. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11974. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11975. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11976. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11977. var WorkerTaskType = BABYLON.WorkerTaskType;
  11978. (function (WorkerReplyType) {
  11979. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11980. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11981. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11982. var WorkerReplyType = BABYLON.WorkerReplyType;
  11983. var CollisionCoordinatorWorker = (function () {
  11984. function CollisionCoordinatorWorker() {
  11985. var _this = this;
  11986. this._scaledPosition = BABYLON.Vector3.Zero();
  11987. this._scaledVelocity = BABYLON.Vector3.Zero();
  11988. this.onMeshUpdated = function (mesh) {
  11989. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11990. };
  11991. this.onGeometryUpdated = function (geometry) {
  11992. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11993. };
  11994. this._afterRender = function () {
  11995. if (!_this._init)
  11996. return;
  11997. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11998. return;
  11999. }
  12000. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12001. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12002. if (_this._runningUpdated > 4) {
  12003. return;
  12004. }
  12005. ++_this._runningUpdated;
  12006. var payload = {
  12007. updatedMeshes: _this._addUpdateMeshesList,
  12008. updatedGeometries: _this._addUpdateGeometriesList,
  12009. removedGeometries: _this._toRemoveGeometryArray,
  12010. removedMeshes: _this._toRemoveMeshesArray
  12011. };
  12012. var message = {
  12013. payload: payload,
  12014. taskType: WorkerTaskType.UPDATE
  12015. };
  12016. var serializable = [];
  12017. for (var id in payload.updatedGeometries) {
  12018. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12019. //prepare transferables
  12020. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12021. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12022. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12023. }
  12024. }
  12025. _this._worker.postMessage(message, serializable);
  12026. _this._addUpdateMeshesList = {};
  12027. _this._addUpdateGeometriesList = {};
  12028. _this._toRemoveGeometryArray = [];
  12029. _this._toRemoveMeshesArray = [];
  12030. };
  12031. this._onMessageFromWorker = function (e) {
  12032. var returnData = e.data;
  12033. if (returnData.error != WorkerReplyType.SUCCESS) {
  12034. //TODO what errors can be returned from the worker?
  12035. BABYLON.Tools.Warn("error returned from worker!");
  12036. return;
  12037. }
  12038. switch (returnData.taskType) {
  12039. case WorkerTaskType.INIT:
  12040. _this._init = true;
  12041. //Update the worked with ALL of the scene's current state
  12042. _this._scene.meshes.forEach(function (mesh) {
  12043. _this.onMeshAdded(mesh);
  12044. });
  12045. _this._scene.getGeometries().forEach(function (geometry) {
  12046. _this.onGeometryAdded(geometry);
  12047. });
  12048. break;
  12049. case WorkerTaskType.UPDATE:
  12050. _this._runningUpdated--;
  12051. break;
  12052. case WorkerTaskType.COLLIDE:
  12053. _this._runningCollisionTask = false;
  12054. var returnPayload = returnData.payload;
  12055. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12056. return;
  12057. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12058. //cleanup
  12059. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12060. break;
  12061. }
  12062. };
  12063. this._collisionsCallbackArray = [];
  12064. this._init = false;
  12065. this._runningUpdated = 0;
  12066. this._runningCollisionTask = false;
  12067. this._addUpdateMeshesList = {};
  12068. this._addUpdateGeometriesList = {};
  12069. this._toRemoveGeometryArray = [];
  12070. this._toRemoveMeshesArray = [];
  12071. }
  12072. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12073. if (!this._init)
  12074. return;
  12075. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12076. return;
  12077. position.divideToRef(collider.radius, this._scaledPosition);
  12078. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12079. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12080. var payload = {
  12081. collider: {
  12082. position: this._scaledPosition.asArray(),
  12083. velocity: this._scaledVelocity.asArray(),
  12084. radius: collider.radius.asArray()
  12085. },
  12086. collisionId: collisionIndex,
  12087. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12088. maximumRetry: maximumRetry
  12089. };
  12090. var message = {
  12091. payload: payload,
  12092. taskType: WorkerTaskType.COLLIDE
  12093. };
  12094. this._worker.postMessage(message);
  12095. };
  12096. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12097. this._scene = scene;
  12098. this._scene.registerAfterRender(this._afterRender);
  12099. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12100. this._worker = new Worker(workerUrl);
  12101. this._worker.onmessage = this._onMessageFromWorker;
  12102. var message = {
  12103. payload: {},
  12104. taskType: WorkerTaskType.INIT
  12105. };
  12106. this._worker.postMessage(message);
  12107. };
  12108. CollisionCoordinatorWorker.prototype.destroy = function () {
  12109. this._scene.unregisterAfterRender(this._afterRender);
  12110. this._worker.terminate();
  12111. };
  12112. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12113. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12114. this.onMeshUpdated(mesh);
  12115. };
  12116. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12117. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12118. };
  12119. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12120. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12121. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12122. this.onGeometryUpdated(geometry);
  12123. };
  12124. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12125. this._toRemoveGeometryArray.push(geometry.id);
  12126. };
  12127. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12128. var submeshes = [];
  12129. if (mesh.subMeshes) {
  12130. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12131. return {
  12132. position: idx,
  12133. verticesStart: sm.verticesStart,
  12134. verticesCount: sm.verticesCount,
  12135. indexStart: sm.indexStart,
  12136. indexCount: sm.indexCount,
  12137. hasMaterial: !!sm.getMaterial(),
  12138. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12139. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12140. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12141. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12142. };
  12143. });
  12144. }
  12145. var geometryId = null;
  12146. if (mesh instanceof BABYLON.Mesh) {
  12147. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12148. }
  12149. else if (mesh instanceof BABYLON.InstancedMesh) {
  12150. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12151. }
  12152. return {
  12153. uniqueId: mesh.uniqueId,
  12154. id: mesh.id,
  12155. name: mesh.name,
  12156. geometryId: geometryId,
  12157. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12158. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12159. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12160. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12161. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12162. subMeshes: submeshes,
  12163. checkCollisions: mesh.checkCollisions
  12164. };
  12165. };
  12166. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12167. return {
  12168. id: geometry.id,
  12169. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12170. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12171. indices: new Int32Array(geometry.getIndices() || []),
  12172. };
  12173. };
  12174. return CollisionCoordinatorWorker;
  12175. })();
  12176. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12177. var CollisionCoordinatorLegacy = (function () {
  12178. function CollisionCoordinatorLegacy() {
  12179. this._scaledPosition = BABYLON.Vector3.Zero();
  12180. this._scaledVelocity = BABYLON.Vector3.Zero();
  12181. this._finalPosition = BABYLON.Vector3.Zero();
  12182. }
  12183. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12184. position.divideToRef(collider.radius, this._scaledPosition);
  12185. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12186. collider.collidedMesh = null;
  12187. collider.retry = 0;
  12188. collider.initialVelocity = this._scaledVelocity;
  12189. collider.initialPosition = this._scaledPosition;
  12190. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12191. this._finalPosition.multiplyInPlace(collider.radius);
  12192. //run the callback
  12193. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12194. };
  12195. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12196. this._scene = scene;
  12197. };
  12198. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12199. //Legacy need no destruction method.
  12200. };
  12201. //No update in legacy mode
  12202. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12203. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12204. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12205. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12206. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12207. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12208. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12209. if (excludedMesh === void 0) { excludedMesh = null; }
  12210. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12211. if (collider.retry >= maximumRetry) {
  12212. finalPosition.copyFrom(position);
  12213. return;
  12214. }
  12215. collider._initialize(position, velocity, closeDistance);
  12216. // Check all meshes
  12217. for (var index = 0; index < this._scene.meshes.length; index++) {
  12218. var mesh = this._scene.meshes[index];
  12219. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12220. mesh._checkCollision(collider);
  12221. }
  12222. }
  12223. if (!collider.collisionFound) {
  12224. position.addToRef(velocity, finalPosition);
  12225. return;
  12226. }
  12227. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12228. collider._getResponse(position, velocity);
  12229. }
  12230. if (velocity.length() <= closeDistance) {
  12231. finalPosition.copyFrom(position);
  12232. return;
  12233. }
  12234. collider.retry++;
  12235. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12236. };
  12237. return CollisionCoordinatorLegacy;
  12238. })();
  12239. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12240. })(BABYLON || (BABYLON = {}));
  12241. var BABYLON;
  12242. (function (BABYLON) {
  12243. var Camera = (function (_super) {
  12244. __extends(Camera, _super);
  12245. function Camera(name, position, scene) {
  12246. _super.call(this, name, scene);
  12247. this.upVector = BABYLON.Vector3.Up();
  12248. this.orthoLeft = null;
  12249. this.orthoRight = null;
  12250. this.orthoBottom = null;
  12251. this.orthoTop = null;
  12252. this.fov = 0.8;
  12253. this.minZ = 1.0;
  12254. this.maxZ = 10000.0;
  12255. this.inertia = 0.9;
  12256. this.mode = Camera.PERSPECTIVE_CAMERA;
  12257. this.isIntermediate = false;
  12258. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12259. this.layerMask = 0x0FFFFFFF;
  12260. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12261. // Camera rig members
  12262. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12263. this._rigCameras = new Array();
  12264. // Cache
  12265. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12266. this._projectionMatrix = new BABYLON.Matrix();
  12267. this._postProcesses = new Array();
  12268. this._transformMatrix = BABYLON.Matrix.Zero();
  12269. this._activeMeshes = new BABYLON.SmartArray(256);
  12270. this._globalPosition = BABYLON.Vector3.Zero();
  12271. this._refreshFrustumPlanes = true;
  12272. scene.addCamera(this);
  12273. if (!scene.activeCamera) {
  12274. scene.activeCamera = this;
  12275. }
  12276. this.position = position;
  12277. }
  12278. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12279. get: function () {
  12280. return Camera._PERSPECTIVE_CAMERA;
  12281. },
  12282. enumerable: true,
  12283. configurable: true
  12284. });
  12285. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12286. get: function () {
  12287. return Camera._ORTHOGRAPHIC_CAMERA;
  12288. },
  12289. enumerable: true,
  12290. configurable: true
  12291. });
  12292. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12293. get: function () {
  12294. return Camera._FOVMODE_VERTICAL_FIXED;
  12295. },
  12296. enumerable: true,
  12297. configurable: true
  12298. });
  12299. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12300. get: function () {
  12301. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12302. },
  12303. enumerable: true,
  12304. configurable: true
  12305. });
  12306. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12307. get: function () {
  12308. return Camera._RIG_MODE_NONE;
  12309. },
  12310. enumerable: true,
  12311. configurable: true
  12312. });
  12313. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12314. get: function () {
  12315. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12316. },
  12317. enumerable: true,
  12318. configurable: true
  12319. });
  12320. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12321. get: function () {
  12322. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12323. },
  12324. enumerable: true,
  12325. configurable: true
  12326. });
  12327. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12328. get: function () {
  12329. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12330. },
  12331. enumerable: true,
  12332. configurable: true
  12333. });
  12334. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12335. get: function () {
  12336. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12337. },
  12338. enumerable: true,
  12339. configurable: true
  12340. });
  12341. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12342. get: function () {
  12343. return Camera._RIG_MODE_VR;
  12344. },
  12345. enumerable: true,
  12346. configurable: true
  12347. });
  12348. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  12349. get: function () {
  12350. return Camera._RIG_MODE_WEBVR;
  12351. },
  12352. enumerable: true,
  12353. configurable: true
  12354. });
  12355. /**
  12356. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12357. */
  12358. Camera.prototype.toString = function (fullDetails) {
  12359. var ret = "Name: " + this.name;
  12360. ret += ", type: " + this.getTypeName();
  12361. if (this.animations) {
  12362. for (var i = 0; i < this.animations.length; i++) {
  12363. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12364. }
  12365. }
  12366. if (fullDetails) {
  12367. }
  12368. return ret;
  12369. };
  12370. Object.defineProperty(Camera.prototype, "globalPosition", {
  12371. get: function () {
  12372. return this._globalPosition;
  12373. },
  12374. enumerable: true,
  12375. configurable: true
  12376. });
  12377. Camera.prototype.getActiveMeshes = function () {
  12378. return this._activeMeshes;
  12379. };
  12380. Camera.prototype.isActiveMesh = function (mesh) {
  12381. return (this._activeMeshes.indexOf(mesh) !== -1);
  12382. };
  12383. //Cache
  12384. Camera.prototype._initCache = function () {
  12385. _super.prototype._initCache.call(this);
  12386. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12387. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12388. this._cache.mode = undefined;
  12389. this._cache.minZ = undefined;
  12390. this._cache.maxZ = undefined;
  12391. this._cache.fov = undefined;
  12392. this._cache.aspectRatio = undefined;
  12393. this._cache.orthoLeft = undefined;
  12394. this._cache.orthoRight = undefined;
  12395. this._cache.orthoBottom = undefined;
  12396. this._cache.orthoTop = undefined;
  12397. this._cache.renderWidth = undefined;
  12398. this._cache.renderHeight = undefined;
  12399. };
  12400. Camera.prototype._updateCache = function (ignoreParentClass) {
  12401. if (!ignoreParentClass) {
  12402. _super.prototype._updateCache.call(this);
  12403. }
  12404. var engine = this.getEngine();
  12405. this._cache.position.copyFrom(this.position);
  12406. this._cache.upVector.copyFrom(this.upVector);
  12407. this._cache.mode = this.mode;
  12408. this._cache.minZ = this.minZ;
  12409. this._cache.maxZ = this.maxZ;
  12410. this._cache.fov = this.fov;
  12411. this._cache.aspectRatio = engine.getAspectRatio(this);
  12412. this._cache.orthoLeft = this.orthoLeft;
  12413. this._cache.orthoRight = this.orthoRight;
  12414. this._cache.orthoBottom = this.orthoBottom;
  12415. this._cache.orthoTop = this.orthoTop;
  12416. this._cache.renderWidth = engine.getRenderWidth();
  12417. this._cache.renderHeight = engine.getRenderHeight();
  12418. };
  12419. Camera.prototype._updateFromScene = function () {
  12420. this.updateCache();
  12421. this.update();
  12422. };
  12423. // Synchronized
  12424. Camera.prototype._isSynchronized = function () {
  12425. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12426. };
  12427. Camera.prototype._isSynchronizedViewMatrix = function () {
  12428. if (!_super.prototype._isSynchronized.call(this))
  12429. return false;
  12430. return this._cache.position.equals(this.position)
  12431. && this._cache.upVector.equals(this.upVector)
  12432. && this.isSynchronizedWithParent();
  12433. };
  12434. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12435. var check = this._cache.mode === this.mode
  12436. && this._cache.minZ === this.minZ
  12437. && this._cache.maxZ === this.maxZ;
  12438. if (!check) {
  12439. return false;
  12440. }
  12441. var engine = this.getEngine();
  12442. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12443. check = this._cache.fov === this.fov
  12444. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12445. }
  12446. else {
  12447. check = this._cache.orthoLeft === this.orthoLeft
  12448. && this._cache.orthoRight === this.orthoRight
  12449. && this._cache.orthoBottom === this.orthoBottom
  12450. && this._cache.orthoTop === this.orthoTop
  12451. && this._cache.renderWidth === engine.getRenderWidth()
  12452. && this._cache.renderHeight === engine.getRenderHeight();
  12453. }
  12454. return check;
  12455. };
  12456. // Controls
  12457. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12458. };
  12459. Camera.prototype.detachControl = function (element) {
  12460. };
  12461. Camera.prototype.update = function () {
  12462. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12463. this._updateRigCameras();
  12464. }
  12465. this._checkInputs();
  12466. };
  12467. Camera.prototype._checkInputs = function () {
  12468. };
  12469. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12470. // invalidate framebuffer
  12471. if (this._postProcesses.length > 0) {
  12472. this._postProcesses[0].markTextureDirty();
  12473. }
  12474. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12475. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12476. var cam = this._rigCameras[i];
  12477. var rigPostProcess = cam._rigPostProcess;
  12478. // for VR rig, there does not have to be a post process
  12479. if (rigPostProcess) {
  12480. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12481. if (isPass) {
  12482. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12483. cam.isIntermediate = this._postProcesses.length === 0;
  12484. }
  12485. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12486. rigPostProcess.markTextureDirty();
  12487. }
  12488. else {
  12489. cam._postProcesses = this._postProcesses.slice(0);
  12490. }
  12491. }
  12492. };
  12493. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12494. if (insertAt === void 0) { insertAt = null; }
  12495. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12496. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12497. return 0;
  12498. }
  12499. if (insertAt == null || insertAt < 0) {
  12500. this._postProcesses.push(postProcess);
  12501. }
  12502. else {
  12503. this._postProcesses.splice(insertAt, 0, postProcess);
  12504. }
  12505. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12506. return this._postProcesses.indexOf(postProcess);
  12507. };
  12508. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12509. if (atIndices === void 0) { atIndices = null; }
  12510. var result = [];
  12511. var i;
  12512. var index;
  12513. if (!atIndices) {
  12514. var idx = this._postProcesses.indexOf(postProcess);
  12515. if (idx !== -1) {
  12516. this._postProcesses.splice(idx, 1);
  12517. }
  12518. }
  12519. else {
  12520. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12521. // iterate descending, so can just splice as we go
  12522. for (i = atIndices.length - 1; i >= 0; i--) {
  12523. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12524. result.push(i);
  12525. continue;
  12526. }
  12527. this._postProcesses.splice(index, 1);
  12528. }
  12529. }
  12530. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12531. return result;
  12532. };
  12533. Camera.prototype.getWorldMatrix = function () {
  12534. if (!this._worldMatrix) {
  12535. this._worldMatrix = BABYLON.Matrix.Identity();
  12536. }
  12537. var viewMatrix = this.getViewMatrix();
  12538. viewMatrix.invertToRef(this._worldMatrix);
  12539. return this._worldMatrix;
  12540. };
  12541. Camera.prototype._getViewMatrix = function () {
  12542. return BABYLON.Matrix.Identity();
  12543. };
  12544. Camera.prototype.getViewMatrix = function (force) {
  12545. this._computedViewMatrix = this._computeViewMatrix(force);
  12546. if (!force && this._isSynchronizedViewMatrix()) {
  12547. return this._computedViewMatrix;
  12548. }
  12549. this._refreshFrustumPlanes = true;
  12550. if (!this.parent || !this.parent.getWorldMatrix) {
  12551. this._globalPosition.copyFrom(this.position);
  12552. }
  12553. else {
  12554. if (!this._worldMatrix) {
  12555. this._worldMatrix = BABYLON.Matrix.Identity();
  12556. }
  12557. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12558. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12559. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12560. this._computedViewMatrix.invert();
  12561. this._markSyncedWithParent();
  12562. }
  12563. this._currentRenderId = this.getScene().getRenderId();
  12564. return this._computedViewMatrix;
  12565. };
  12566. Camera.prototype._computeViewMatrix = function (force) {
  12567. if (!force && this._isSynchronizedViewMatrix()) {
  12568. return this._computedViewMatrix;
  12569. }
  12570. this._computedViewMatrix = this._getViewMatrix();
  12571. this._currentRenderId = this.getScene().getRenderId();
  12572. return this._computedViewMatrix;
  12573. };
  12574. Camera.prototype.getProjectionMatrix = function (force) {
  12575. if (!force && this._isSynchronizedProjectionMatrix()) {
  12576. return this._projectionMatrix;
  12577. }
  12578. this._refreshFrustumPlanes = true;
  12579. var engine = this.getEngine();
  12580. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12581. if (this.minZ <= 0) {
  12582. this.minZ = 0.1;
  12583. }
  12584. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12585. return this._projectionMatrix;
  12586. }
  12587. var halfWidth = engine.getRenderWidth() / 2.0;
  12588. var halfHeight = engine.getRenderHeight() / 2.0;
  12589. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12590. return this._projectionMatrix;
  12591. };
  12592. Camera.prototype.getTranformationMatrix = function () {
  12593. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12594. return this._transformMatrix;
  12595. };
  12596. Camera.prototype.updateFrustumPlanes = function () {
  12597. if (!this._refreshFrustumPlanes) {
  12598. return;
  12599. }
  12600. this.getTranformationMatrix();
  12601. if (!this._frustumPlanes) {
  12602. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12603. }
  12604. else {
  12605. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12606. }
  12607. this._refreshFrustumPlanes = false;
  12608. };
  12609. Camera.prototype.isInFrustum = function (target) {
  12610. this.updateFrustumPlanes();
  12611. return target.isInFrustum(this._frustumPlanes);
  12612. };
  12613. Camera.prototype.isCompletelyInFrustum = function (target) {
  12614. this.updateFrustumPlanes();
  12615. return target.isCompletelyInFrustum(this._frustumPlanes);
  12616. };
  12617. Camera.prototype.dispose = function () {
  12618. // Animations
  12619. this.getScene().stopAnimation(this);
  12620. // Remove from scene
  12621. this.getScene().removeCamera(this);
  12622. while (this._rigCameras.length > 0) {
  12623. this._rigCameras.pop().dispose();
  12624. }
  12625. // Postprocesses
  12626. for (var i = 0; i < this._postProcesses.length; ++i) {
  12627. this._postProcesses[i].dispose(this);
  12628. }
  12629. _super.prototype.dispose.call(this);
  12630. };
  12631. // ---- Camera rigs section ----
  12632. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12633. while (this._rigCameras.length > 0) {
  12634. this._rigCameras.pop().dispose();
  12635. }
  12636. this.cameraRigMode = mode;
  12637. this._cameraRigParams = {};
  12638. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12639. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12640. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12641. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12642. // create the rig cameras, unless none
  12643. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12644. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12645. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12646. }
  12647. switch (this.cameraRigMode) {
  12648. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12649. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12650. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12651. break;
  12652. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12653. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12654. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12655. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12656. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12657. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12658. break;
  12659. case Camera.RIG_MODE_VR:
  12660. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12661. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12662. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12663. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12664. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12665. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12666. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12667. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12668. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12669. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12670. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12671. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12672. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12673. if (metrics.compensateDistortion) {
  12674. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  12675. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  12676. }
  12677. break;
  12678. case Camera.RIG_MODE_WEBVR:
  12679. if (rigParams.vrDisplay) {
  12680. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  12681. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  12682. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12683. this._rigCameras[0].setCameraRigParameter("vrFieldOfView", leftEye.fieldOfView);
  12684. this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  12685. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12686. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  12687. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12688. this._rigCameras[1].setCameraRigParameter("vrFieldOfView", rightEye.fieldOfView);
  12689. this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  12690. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12691. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  12692. }
  12693. break;
  12694. }
  12695. this._cascadePostProcessesToRigCams();
  12696. this.
  12697. update();
  12698. };
  12699. Camera.prototype._getVRProjectionMatrix = function () {
  12700. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12701. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  12702. return this._projectionMatrix;
  12703. };
  12704. Camera.prototype._getWebVRProjectionMatrix = function () {
  12705. BABYLON.Matrix.PerspectiveFovWebVRToRef(this._cameraRigParams['vrFieldOfView'], this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12706. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams['vrOffsetMatrix'], this._projectionMatrix);
  12707. return this._projectionMatrix;
  12708. };
  12709. Camera.prototype.setCameraRigParameter = function (name, value) {
  12710. if (!this._cameraRigParams) {
  12711. this._cameraRigParams = {};
  12712. }
  12713. this._cameraRigParams[name] = value;
  12714. //provisionnally:
  12715. if (name === "interaxialDistance") {
  12716. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  12717. }
  12718. };
  12719. /**
  12720. * needs to be overridden by children so sub has required properties to be copied
  12721. */
  12722. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  12723. return null;
  12724. };
  12725. /**
  12726. * May need to be overridden by children
  12727. */
  12728. Camera.prototype._updateRigCameras = function () {
  12729. for (var i = 0; i < this._rigCameras.length; i++) {
  12730. this._rigCameras[i].minZ = this.minZ;
  12731. this._rigCameras[i].maxZ = this.maxZ;
  12732. this._rigCameras[i].fov = this.fov;
  12733. }
  12734. // only update viewport when ANAGLYPH
  12735. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  12736. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  12737. }
  12738. };
  12739. Camera.prototype._setupInputs = function () {
  12740. };
  12741. Camera.prototype.serialize = function () {
  12742. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12743. // Type
  12744. serializationObject.type = this.getTypeName();
  12745. // Parent
  12746. if (this.parent) {
  12747. serializationObject.parentId = this.parent.id;
  12748. }
  12749. if (this.inputs) {
  12750. this.inputs.serialize(serializationObject);
  12751. }
  12752. // Animations
  12753. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12754. serializationObject.ranges = this.serializeAnimationRanges();
  12755. return serializationObject;
  12756. };
  12757. Camera.prototype.getTypeName = function () {
  12758. return "Camera";
  12759. };
  12760. Camera.prototype.clone = function (name) {
  12761. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  12762. };
  12763. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  12764. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  12765. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  12766. switch (type) {
  12767. case "ArcRotateCamera":
  12768. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  12769. case "DeviceOrientationCamera":
  12770. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  12771. case "FollowCamera":
  12772. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  12773. case "ArcFollowCamera":
  12774. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  12775. case "GamepadCamera":
  12776. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  12777. case "TouchCamera":
  12778. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  12779. case "VirtualJoysticksCamera":
  12780. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  12781. case "WebVRFreeCamera":
  12782. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12783. case "VRDeviceOrientationFreeCamera":
  12784. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12785. case "AnaglyphArcRotateCamera":
  12786. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12787. case "AnaglyphFreeCamera":
  12788. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12789. case "AnaglyphGamepadCamera":
  12790. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12791. case "AnaglyphUniversalCamera":
  12792. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12793. case "StereoscopicArcRotateCamera":
  12794. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12795. case "StereoscopicFreeCamera":
  12796. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12797. case "StereoscopicGamepadCamera":
  12798. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12799. case "StereoscopicUniversalCamera":
  12800. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12801. case "FreeCamera":
  12802. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12803. default:
  12804. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12805. }
  12806. };
  12807. Camera.Parse = function (parsedCamera, scene) {
  12808. var type = parsedCamera.type;
  12809. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  12810. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  12811. // Parent
  12812. if (parsedCamera.parentId) {
  12813. camera._waitingParentId = parsedCamera.parentId;
  12814. }
  12815. //If camera has an input manager, let it parse inputs settings
  12816. if (camera.inputs) {
  12817. camera.inputs.parse(parsedCamera);
  12818. camera._setupInputs();
  12819. }
  12820. // Target
  12821. if (parsedCamera.target) {
  12822. if (camera.setTarget) {
  12823. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  12824. }
  12825. }
  12826. // Apply 3d rig, when found
  12827. if (parsedCamera.cameraRigMode) {
  12828. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  12829. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  12830. }
  12831. // Animations
  12832. if (parsedCamera.animations) {
  12833. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  12834. var parsedAnimation = parsedCamera.animations[animationIndex];
  12835. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12836. }
  12837. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  12838. }
  12839. if (parsedCamera.autoAnimate) {
  12840. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  12841. }
  12842. return camera;
  12843. };
  12844. // Statics
  12845. Camera._PERSPECTIVE_CAMERA = 0;
  12846. Camera._ORTHOGRAPHIC_CAMERA = 1;
  12847. Camera._FOVMODE_VERTICAL_FIXED = 0;
  12848. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  12849. Camera._RIG_MODE_NONE = 0;
  12850. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  12851. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  12852. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  12853. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  12854. Camera._RIG_MODE_VR = 20;
  12855. Camera._RIG_MODE_WEBVR = 21;
  12856. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  12857. __decorate([
  12858. BABYLON.serializeAsVector3()
  12859. ], Camera.prototype, "position", void 0);
  12860. __decorate([
  12861. BABYLON.serializeAsVector3()
  12862. ], Camera.prototype, "upVector", void 0);
  12863. __decorate([
  12864. BABYLON.serialize()
  12865. ], Camera.prototype, "orthoLeft", void 0);
  12866. __decorate([
  12867. BABYLON.serialize()
  12868. ], Camera.prototype, "orthoRight", void 0);
  12869. __decorate([
  12870. BABYLON.serialize()
  12871. ], Camera.prototype, "orthoBottom", void 0);
  12872. __decorate([
  12873. BABYLON.serialize()
  12874. ], Camera.prototype, "orthoTop", void 0);
  12875. __decorate([
  12876. BABYLON.serialize()
  12877. ], Camera.prototype, "fov", void 0);
  12878. __decorate([
  12879. BABYLON.serialize()
  12880. ], Camera.prototype, "minZ", void 0);
  12881. __decorate([
  12882. BABYLON.serialize()
  12883. ], Camera.prototype, "maxZ", void 0);
  12884. __decorate([
  12885. BABYLON.serialize()
  12886. ], Camera.prototype, "inertia", void 0);
  12887. __decorate([
  12888. BABYLON.serialize()
  12889. ], Camera.prototype, "mode", void 0);
  12890. __decorate([
  12891. BABYLON.serialize()
  12892. ], Camera.prototype, "layerMask", void 0);
  12893. __decorate([
  12894. BABYLON.serialize()
  12895. ], Camera.prototype, "fovMode", void 0);
  12896. __decorate([
  12897. BABYLON.serialize()
  12898. ], Camera.prototype, "cameraRigMode", void 0);
  12899. __decorate([
  12900. BABYLON.serialize()
  12901. ], Camera.prototype, "interaxialDistance", void 0);
  12902. __decorate([
  12903. BABYLON.serialize()
  12904. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  12905. return Camera;
  12906. })(BABYLON.Node);
  12907. BABYLON.Camera = Camera;
  12908. })(BABYLON || (BABYLON = {}));
  12909. var BABYLON;
  12910. (function (BABYLON) {
  12911. BABYLON.CameraInputTypes = {};
  12912. var CameraInputsManager = (function () {
  12913. function CameraInputsManager(camera) {
  12914. this.attached = {};
  12915. this.camera = camera;
  12916. this.checkInputs = function () { };
  12917. }
  12918. CameraInputsManager.prototype.add = function (input) {
  12919. var type = input.getSimpleName();
  12920. if (this.attached[type]) {
  12921. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  12922. return;
  12923. }
  12924. this.attached[type] = input;
  12925. input.camera = this.camera;
  12926. //for checkInputs, we are dynamically creating a function
  12927. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  12928. if (input.checkInputs) {
  12929. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12930. }
  12931. if (this.attachedElement) {
  12932. input.attachControl(this.attachedElement);
  12933. }
  12934. };
  12935. CameraInputsManager.prototype.remove = function (inputToRemove) {
  12936. for (var cam in this.attached) {
  12937. var input = this.attached[cam];
  12938. if (input === inputToRemove) {
  12939. input.detachControl(this.attachedElement);
  12940. delete this.attached[cam];
  12941. this.rebuildInputCheck();
  12942. }
  12943. }
  12944. };
  12945. CameraInputsManager.prototype.removeByType = function (inputType) {
  12946. for (var cam in this.attached) {
  12947. var input = this.attached[cam];
  12948. if (input.getTypeName() === inputType) {
  12949. input.detachControl(this.attachedElement);
  12950. delete this.attached[cam];
  12951. this.rebuildInputCheck();
  12952. }
  12953. }
  12954. };
  12955. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  12956. var current = this.checkInputs;
  12957. return function () {
  12958. current();
  12959. fn();
  12960. };
  12961. };
  12962. CameraInputsManager.prototype.attachInput = function (input) {
  12963. input.attachControl(this.attachedElement, this.noPreventDefault);
  12964. };
  12965. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12966. if (this.attachedElement) {
  12967. return;
  12968. }
  12969. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12970. this.attachedElement = element;
  12971. this.noPreventDefault = noPreventDefault;
  12972. for (var cam in this.attached) {
  12973. var input = this.attached[cam];
  12974. this.attached[cam].attachControl(element, noPreventDefault);
  12975. }
  12976. };
  12977. CameraInputsManager.prototype.detachElement = function (element) {
  12978. if (this.attachedElement !== element) {
  12979. return;
  12980. }
  12981. for (var cam in this.attached) {
  12982. var input = this.attached[cam];
  12983. this.attached[cam].detachControl(element);
  12984. }
  12985. this.attachedElement = null;
  12986. };
  12987. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12988. this.checkInputs = function () { };
  12989. for (var cam in this.attached) {
  12990. var input = this.attached[cam];
  12991. if (input.checkInputs) {
  12992. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12993. }
  12994. }
  12995. };
  12996. CameraInputsManager.prototype.clear = function () {
  12997. if (this.attachedElement) {
  12998. this.detachElement(this.attachedElement);
  12999. }
  13000. this.attached = {};
  13001. this.attachedElement = null;
  13002. this.checkInputs = function () { };
  13003. };
  13004. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13005. var inputs = {};
  13006. for (var cam in this.attached) {
  13007. var input = this.attached[cam];
  13008. var res = BABYLON.SerializationHelper.Serialize(input);
  13009. inputs[input.getTypeName()] = res;
  13010. }
  13011. serializedCamera.inputsmgr = inputs;
  13012. };
  13013. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13014. var parsedInputs = parsedCamera.inputsmgr;
  13015. if (parsedInputs) {
  13016. this.clear();
  13017. for (var n in parsedInputs) {
  13018. var construct = BABYLON.CameraInputTypes[n];
  13019. if (construct) {
  13020. var parsedinput = parsedInputs[n];
  13021. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13022. this.add(input);
  13023. }
  13024. }
  13025. }
  13026. else {
  13027. //2016-03-08 this part is for managing backward compatibility
  13028. for (var n in this.attached) {
  13029. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13030. if (construct) {
  13031. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13032. this.remove(this.attached[n]);
  13033. this.add(input);
  13034. }
  13035. }
  13036. }
  13037. };
  13038. return CameraInputsManager;
  13039. })();
  13040. BABYLON.CameraInputsManager = CameraInputsManager;
  13041. })(BABYLON || (BABYLON = {}));
  13042. var BABYLON;
  13043. (function (BABYLON) {
  13044. var FreeCameraMouseInput = (function () {
  13045. function FreeCameraMouseInput(touchEnabled) {
  13046. if (touchEnabled === void 0) { touchEnabled = true; }
  13047. this.touchEnabled = touchEnabled;
  13048. this.angularSensibility = 2000.0;
  13049. }
  13050. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13051. var _this = this;
  13052. if (!this._pointerInput) {
  13053. var camera = this.camera;
  13054. var engine = this.camera.getEngine();
  13055. this._pointerInput = function (p, s) {
  13056. var evt = p.event;
  13057. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13058. return;
  13059. }
  13060. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13061. try {
  13062. evt.srcElement.setPointerCapture(evt.pointerId);
  13063. }
  13064. catch (e) {
  13065. }
  13066. _this.previousPosition = {
  13067. x: evt.clientX,
  13068. y: evt.clientY
  13069. };
  13070. if (!noPreventDefault) {
  13071. evt.preventDefault();
  13072. element.focus();
  13073. }
  13074. }
  13075. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13076. try {
  13077. evt.srcElement.releasePointerCapture(evt.pointerId);
  13078. }
  13079. catch (e) {
  13080. }
  13081. _this.previousPosition = null;
  13082. if (!noPreventDefault) {
  13083. evt.preventDefault();
  13084. }
  13085. }
  13086. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13087. if (!_this.previousPosition && !engine.isPointerLock) {
  13088. return;
  13089. }
  13090. var offsetX;
  13091. var offsetY;
  13092. if (!engine.isPointerLock) {
  13093. offsetX = evt.clientX - _this.previousPosition.x;
  13094. offsetY = evt.clientY - _this.previousPosition.y;
  13095. }
  13096. else {
  13097. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13098. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13099. }
  13100. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13101. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13102. _this.previousPosition = {
  13103. x: evt.clientX,
  13104. y: evt.clientY
  13105. };
  13106. if (!noPreventDefault) {
  13107. evt.preventDefault();
  13108. }
  13109. }
  13110. };
  13111. }
  13112. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13113. };
  13114. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13115. if (this._observer && element) {
  13116. this.camera.getScene().onPointerObservable.remove(this._observer);
  13117. this._observer = null;
  13118. this.previousPosition = null;
  13119. }
  13120. };
  13121. FreeCameraMouseInput.prototype.getTypeName = function () {
  13122. return "FreeCameraMouseInput";
  13123. };
  13124. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13125. return "mouse";
  13126. };
  13127. __decorate([
  13128. BABYLON.serialize()
  13129. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13130. return FreeCameraMouseInput;
  13131. })();
  13132. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13133. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13134. })(BABYLON || (BABYLON = {}));
  13135. var BABYLON;
  13136. (function (BABYLON) {
  13137. var FreeCameraKeyboardMoveInput = (function () {
  13138. function FreeCameraKeyboardMoveInput() {
  13139. this._keys = [];
  13140. this.keysUp = [38];
  13141. this.keysDown = [40];
  13142. this.keysLeft = [37];
  13143. this.keysRight = [39];
  13144. }
  13145. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13146. var _this = this;
  13147. if (!this._onKeyDown) {
  13148. element.tabIndex = 1;
  13149. this._onKeyDown = function (evt) {
  13150. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13151. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13152. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13153. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13154. var index = _this._keys.indexOf(evt.keyCode);
  13155. if (index === -1) {
  13156. _this._keys.push(evt.keyCode);
  13157. }
  13158. if (!noPreventDefault) {
  13159. evt.preventDefault();
  13160. }
  13161. }
  13162. };
  13163. this._onKeyUp = function (evt) {
  13164. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13165. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13166. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13167. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13168. var index = _this._keys.indexOf(evt.keyCode);
  13169. if (index >= 0) {
  13170. _this._keys.splice(index, 1);
  13171. }
  13172. if (!noPreventDefault) {
  13173. evt.preventDefault();
  13174. }
  13175. }
  13176. };
  13177. element.addEventListener("keydown", this._onKeyDown, false);
  13178. element.addEventListener("keyup", this._onKeyUp, false);
  13179. BABYLON.Tools.RegisterTopRootEvents([
  13180. { name: "blur", handler: this._onLostFocus }
  13181. ]);
  13182. }
  13183. };
  13184. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13185. if (this._onKeyDown) {
  13186. element.removeEventListener("keydown", this._onKeyDown);
  13187. element.removeEventListener("keyup", this._onKeyUp);
  13188. BABYLON.Tools.UnregisterTopRootEvents([
  13189. { name: "blur", handler: this._onLostFocus }
  13190. ]);
  13191. this._keys = [];
  13192. this._onKeyDown = null;
  13193. this._onKeyUp = null;
  13194. }
  13195. };
  13196. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13197. if (this._onKeyDown) {
  13198. var camera = this.camera;
  13199. // Keyboard
  13200. for (var index = 0; index < this._keys.length; index++) {
  13201. var keyCode = this._keys[index];
  13202. var speed = camera._computeLocalCameraSpeed();
  13203. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13204. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13205. }
  13206. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13207. camera._localDirection.copyFromFloats(0, 0, speed);
  13208. }
  13209. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13210. camera._localDirection.copyFromFloats(speed, 0, 0);
  13211. }
  13212. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13213. camera._localDirection.copyFromFloats(0, 0, -speed);
  13214. }
  13215. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13216. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13217. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13218. }
  13219. }
  13220. };
  13221. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13222. return "FreeCameraKeyboardMoveInput";
  13223. };
  13224. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13225. this._keys = [];
  13226. };
  13227. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13228. return "keyboard";
  13229. };
  13230. __decorate([
  13231. BABYLON.serialize()
  13232. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13233. __decorate([
  13234. BABYLON.serialize()
  13235. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13236. __decorate([
  13237. BABYLON.serialize()
  13238. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13239. __decorate([
  13240. BABYLON.serialize()
  13241. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13242. return FreeCameraKeyboardMoveInput;
  13243. })();
  13244. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13245. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13246. })(BABYLON || (BABYLON = {}));
  13247. var BABYLON;
  13248. (function (BABYLON) {
  13249. var FreeCameraTouchInput = (function () {
  13250. function FreeCameraTouchInput() {
  13251. this._offsetX = null;
  13252. this._offsetY = null;
  13253. this._pointerCount = 0;
  13254. this._pointerPressed = [];
  13255. this.touchAngularSensibility = 200000.0;
  13256. this.touchMoveSensibility = 250.0;
  13257. }
  13258. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13259. var _this = this;
  13260. var previousPosition;
  13261. if (this._pointerInput === undefined) {
  13262. this._onLostFocus = function (evt) {
  13263. _this._offsetX = null;
  13264. _this._offsetY = null;
  13265. };
  13266. this._pointerInput = function (p, s) {
  13267. var evt = p.event;
  13268. if (evt.pointerType === "mouse") {
  13269. return;
  13270. }
  13271. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13272. if (!noPreventDefault) {
  13273. evt.preventDefault();
  13274. }
  13275. _this._pointerPressed.push(evt.pointerId);
  13276. if (_this._pointerPressed.length !== 1) {
  13277. return;
  13278. }
  13279. previousPosition = {
  13280. x: evt.clientX,
  13281. y: evt.clientY
  13282. };
  13283. }
  13284. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13285. if (!noPreventDefault) {
  13286. evt.preventDefault();
  13287. }
  13288. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13289. if (index === -1) {
  13290. return;
  13291. }
  13292. _this._pointerPressed.splice(index, 1);
  13293. if (index != 0) {
  13294. return;
  13295. }
  13296. previousPosition = null;
  13297. _this._offsetX = null;
  13298. _this._offsetY = null;
  13299. }
  13300. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13301. if (!noPreventDefault) {
  13302. evt.preventDefault();
  13303. }
  13304. if (!previousPosition) {
  13305. return;
  13306. }
  13307. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13308. if (index != 0) {
  13309. return;
  13310. }
  13311. _this._offsetX = evt.clientX - previousPosition.x;
  13312. _this._offsetY = -(evt.clientY - previousPosition.y);
  13313. }
  13314. };
  13315. }
  13316. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13317. element.addEventListener("blur", this._onLostFocus);
  13318. };
  13319. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13320. if (this._pointerInput && element) {
  13321. this.camera.getScene().onPointerObservable.remove(this._observer);
  13322. this._observer = null;
  13323. element.removeEventListener("blur", this._onLostFocus);
  13324. this._onLostFocus = null;
  13325. this._pointerPressed = [];
  13326. this._offsetX = null;
  13327. this._offsetY = null;
  13328. this._pointerCount = 0;
  13329. }
  13330. };
  13331. FreeCameraTouchInput.prototype.checkInputs = function () {
  13332. if (this._offsetX) {
  13333. var camera = this.camera;
  13334. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13335. if (this._pointerPressed.length > 1) {
  13336. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13337. }
  13338. else {
  13339. var speed = camera._computeLocalCameraSpeed();
  13340. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13341. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13342. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13343. }
  13344. }
  13345. };
  13346. FreeCameraTouchInput.prototype.getTypeName = function () {
  13347. return "FreeCameraTouchInput";
  13348. };
  13349. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13350. return "touch";
  13351. };
  13352. __decorate([
  13353. BABYLON.serialize()
  13354. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13355. __decorate([
  13356. BABYLON.serialize()
  13357. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13358. return FreeCameraTouchInput;
  13359. })();
  13360. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13361. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13362. })(BABYLON || (BABYLON = {}));
  13363. var BABYLON;
  13364. (function (BABYLON) {
  13365. var FreeCameraDeviceOrientationInput = (function () {
  13366. function FreeCameraDeviceOrientationInput() {
  13367. var _this = this;
  13368. this._screenOrientationAngle = 0;
  13369. this._screenQuaternion = new BABYLON.Quaternion();
  13370. this._alpha = 0;
  13371. this._beta = 0;
  13372. this._gamma = 0;
  13373. this._orientationChanged = function () {
  13374. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13375. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13376. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13377. };
  13378. this._deviceOrientation = function (evt) {
  13379. _this._alpha = evt.alpha;
  13380. _this._beta = evt.beta;
  13381. _this._gamma = evt.gamma;
  13382. };
  13383. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13384. this._orientationChanged();
  13385. }
  13386. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13387. get: function () {
  13388. return this._camera;
  13389. },
  13390. set: function (camera) {
  13391. this._camera = camera;
  13392. if (!this._camera.rotationQuaternion)
  13393. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13394. },
  13395. enumerable: true,
  13396. configurable: true
  13397. });
  13398. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13399. window.addEventListener("orientationchange", this._orientationChanged);
  13400. window.addEventListener("deviceorientation", this._deviceOrientation);
  13401. //In certain cases, the attach control is called AFTER orientation was changed,
  13402. //So this is needed.
  13403. this._orientationChanged();
  13404. };
  13405. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13406. window.removeEventListener("orientationchange", this._orientationChanged);
  13407. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13408. };
  13409. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13410. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13411. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13412. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13413. //Mirror on XY Plane
  13414. this._camera.rotationQuaternion.z *= -1;
  13415. this._camera.rotationQuaternion.w *= -1;
  13416. };
  13417. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13418. return "FreeCameraDeviceOrientationInput";
  13419. };
  13420. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13421. return "deviceOrientation";
  13422. };
  13423. return FreeCameraDeviceOrientationInput;
  13424. })();
  13425. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13426. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13427. })(BABYLON || (BABYLON = {}));
  13428. var BABYLON;
  13429. (function (BABYLON) {
  13430. var FreeCameraGamepadInput = (function () {
  13431. function FreeCameraGamepadInput() {
  13432. this.gamepadAngularSensibility = 200;
  13433. this.gamepadMoveSensibility = 40;
  13434. }
  13435. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13436. var _this = this;
  13437. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13438. };
  13439. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13440. if (this._gamepads) {
  13441. this._gamepads.dispose();
  13442. }
  13443. this.gamepad = null;
  13444. };
  13445. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13446. if (this.gamepad) {
  13447. var camera = this.camera;
  13448. var LSValues = this.gamepad.leftStick;
  13449. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13450. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13451. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13452. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13453. var RSValues = this.gamepad.rightStick;
  13454. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13455. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13456. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13457. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13458. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13459. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13460. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13461. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13462. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13463. }
  13464. };
  13465. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13466. // Only the first gamepad can control the camera
  13467. if (gamepad.index === 0) {
  13468. this.gamepad = gamepad;
  13469. }
  13470. };
  13471. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13472. return "FreeCameraGamepadInput";
  13473. };
  13474. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13475. return "gamepad";
  13476. };
  13477. __decorate([
  13478. BABYLON.serialize()
  13479. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13480. __decorate([
  13481. BABYLON.serialize()
  13482. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13483. return FreeCameraGamepadInput;
  13484. })();
  13485. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13486. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13487. })(BABYLON || (BABYLON = {}));
  13488. var BABYLON;
  13489. (function (BABYLON) {
  13490. var ArcRotateCameraKeyboardMoveInput = (function () {
  13491. function ArcRotateCameraKeyboardMoveInput() {
  13492. this._keys = [];
  13493. this.keysUp = [38];
  13494. this.keysDown = [40];
  13495. this.keysLeft = [37];
  13496. this.keysRight = [39];
  13497. }
  13498. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13499. var _this = this;
  13500. element.tabIndex = 1;
  13501. this._onKeyDown = function (evt) {
  13502. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13503. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13504. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13505. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13506. var index = _this._keys.indexOf(evt.keyCode);
  13507. if (index === -1) {
  13508. _this._keys.push(evt.keyCode);
  13509. }
  13510. if (evt.preventDefault) {
  13511. if (!noPreventDefault) {
  13512. evt.preventDefault();
  13513. }
  13514. }
  13515. }
  13516. };
  13517. this._onKeyUp = function (evt) {
  13518. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13519. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13520. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13521. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13522. var index = _this._keys.indexOf(evt.keyCode);
  13523. if (index >= 0) {
  13524. _this._keys.splice(index, 1);
  13525. }
  13526. if (evt.preventDefault) {
  13527. if (!noPreventDefault) {
  13528. evt.preventDefault();
  13529. }
  13530. }
  13531. }
  13532. };
  13533. this._onLostFocus = function () {
  13534. _this._keys = [];
  13535. };
  13536. element.addEventListener("keydown", this._onKeyDown, false);
  13537. element.addEventListener("keyup", this._onKeyUp, false);
  13538. BABYLON.Tools.RegisterTopRootEvents([
  13539. { name: "blur", handler: this._onLostFocus }
  13540. ]);
  13541. };
  13542. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13543. if (element) {
  13544. element.removeEventListener("keydown", this._onKeyDown);
  13545. element.removeEventListener("keyup", this._onKeyUp);
  13546. }
  13547. BABYLON.Tools.UnregisterTopRootEvents([
  13548. { name: "blur", handler: this._onLostFocus }
  13549. ]);
  13550. this._keys = [];
  13551. this._onKeyDown = null;
  13552. this._onKeyUp = null;
  13553. this._onLostFocus = null;
  13554. };
  13555. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13556. if (this._onKeyDown) {
  13557. var camera = this.camera;
  13558. for (var index = 0; index < this._keys.length; index++) {
  13559. var keyCode = this._keys[index];
  13560. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13561. camera.inertialAlphaOffset -= 0.01;
  13562. }
  13563. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13564. camera.inertialBetaOffset -= 0.01;
  13565. }
  13566. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13567. camera.inertialAlphaOffset += 0.01;
  13568. }
  13569. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13570. camera.inertialBetaOffset += 0.01;
  13571. }
  13572. }
  13573. }
  13574. };
  13575. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13576. return "ArcRotateCameraKeyboardMoveInput";
  13577. };
  13578. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13579. return "keyboard";
  13580. };
  13581. __decorate([
  13582. BABYLON.serialize()
  13583. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13584. __decorate([
  13585. BABYLON.serialize()
  13586. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13587. __decorate([
  13588. BABYLON.serialize()
  13589. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13590. __decorate([
  13591. BABYLON.serialize()
  13592. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13593. return ArcRotateCameraKeyboardMoveInput;
  13594. })();
  13595. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13596. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13597. })(BABYLON || (BABYLON = {}));
  13598. var BABYLON;
  13599. (function (BABYLON) {
  13600. var ArcRotateCameraMouseWheelInput = (function () {
  13601. function ArcRotateCameraMouseWheelInput() {
  13602. this.wheelPrecision = 3.0;
  13603. }
  13604. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13605. var _this = this;
  13606. this._wheel = function (p, s) {
  13607. //sanity check - this should be a PointerWheel event.
  13608. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13609. return;
  13610. var event = p.event;
  13611. var delta = 0;
  13612. if (event.wheelDelta) {
  13613. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13614. }
  13615. else if (event.detail) {
  13616. delta = -event.detail / _this.wheelPrecision;
  13617. }
  13618. if (delta)
  13619. _this.camera.inertialRadiusOffset += delta;
  13620. if (event.preventDefault) {
  13621. if (!noPreventDefault) {
  13622. event.preventDefault();
  13623. }
  13624. }
  13625. };
  13626. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13627. };
  13628. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13629. if (this._observer && element) {
  13630. this.camera.getScene().onPointerObservable.remove(this._observer);
  13631. this._observer = null;
  13632. this._wheel = null;
  13633. }
  13634. };
  13635. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13636. return "ArcRotateCameraMouseWheelInput";
  13637. };
  13638. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13639. return "mousewheel";
  13640. };
  13641. __decorate([
  13642. BABYLON.serialize()
  13643. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13644. return ArcRotateCameraMouseWheelInput;
  13645. })();
  13646. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13647. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13648. })(BABYLON || (BABYLON = {}));
  13649. var BABYLON;
  13650. (function (BABYLON) {
  13651. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13652. var ArcRotateCameraPointersInput = (function () {
  13653. function ArcRotateCameraPointersInput() {
  13654. this.angularSensibilityX = 1000.0;
  13655. this.angularSensibilityY = 1000.0;
  13656. this.pinchPrecision = 6.0;
  13657. this.panningSensibility = 50.0;
  13658. this._isPanClick = false;
  13659. this.pinchInwards = true;
  13660. }
  13661. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  13662. var _this = this;
  13663. var engine = this.camera.getEngine();
  13664. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  13665. var pointA, pointB;
  13666. var previousPinchDistance = 0;
  13667. this._pointerInput = function (p, s) {
  13668. var evt = p.event;
  13669. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13670. try {
  13671. evt.srcElement.setPointerCapture(evt.pointerId);
  13672. }
  13673. catch (e) {
  13674. }
  13675. // Manage panning with pan button click
  13676. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  13677. // manage pointers
  13678. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  13679. if (pointA === undefined) {
  13680. pointA = cacheSoloPointer;
  13681. }
  13682. else if (pointB === undefined) {
  13683. pointB = cacheSoloPointer;
  13684. }
  13685. if (!noPreventDefault) {
  13686. evt.preventDefault();
  13687. element.focus();
  13688. }
  13689. }
  13690. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13691. try {
  13692. evt.srcElement.releasePointerCapture(evt.pointerId);
  13693. }
  13694. catch (e) {
  13695. }
  13696. cacheSoloPointer = null;
  13697. previousPinchDistance = 0;
  13698. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  13699. //but emptying completly pointers collection is required to fix a bug on iPhone :
  13700. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  13701. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  13702. pointA = pointB = undefined;
  13703. if (!noPreventDefault) {
  13704. evt.preventDefault();
  13705. }
  13706. }
  13707. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13708. if (!noPreventDefault) {
  13709. evt.preventDefault();
  13710. }
  13711. // One button down
  13712. if (pointA && pointB === undefined) {
  13713. if (_this.panningSensibility !== 0 &&
  13714. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  13715. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  13716. _this.camera
  13717. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  13718. _this.camera
  13719. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  13720. }
  13721. else {
  13722. var offsetX = evt.clientX - cacheSoloPointer.x;
  13723. var offsetY = evt.clientY - cacheSoloPointer.y;
  13724. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13725. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13726. }
  13727. cacheSoloPointer.x = evt.clientX;
  13728. cacheSoloPointer.y = evt.clientY;
  13729. }
  13730. else if (pointA && pointB) {
  13731. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  13732. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  13733. ed.x = evt.clientX;
  13734. ed.y = evt.clientY;
  13735. var direction = _this.pinchInwards ? 1 : -1;
  13736. var distX = pointA.x - pointB.x;
  13737. var distY = pointA.y - pointB.y;
  13738. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  13739. if (previousPinchDistance === 0) {
  13740. previousPinchDistance = pinchSquaredDistance;
  13741. return;
  13742. }
  13743. if (pinchSquaredDistance !== previousPinchDistance) {
  13744. _this.camera
  13745. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  13746. (_this.pinchPrecision *
  13747. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  13748. direction);
  13749. previousPinchDistance = pinchSquaredDistance;
  13750. }
  13751. }
  13752. }
  13753. };
  13754. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13755. this._onContextMenu = function (evt) {
  13756. evt.preventDefault();
  13757. };
  13758. if (!this.camera._useCtrlForPanning) {
  13759. element.addEventListener("contextmenu", this._onContextMenu, false);
  13760. }
  13761. this._onLostFocus = function () {
  13762. //this._keys = [];
  13763. pointA = pointB = undefined;
  13764. previousPinchDistance = 0;
  13765. cacheSoloPointer = null;
  13766. };
  13767. this._onMouseMove = function (evt) {
  13768. if (!engine.isPointerLock) {
  13769. return;
  13770. }
  13771. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13772. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13773. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13774. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13775. if (!noPreventDefault) {
  13776. evt.preventDefault();
  13777. }
  13778. };
  13779. this._onGestureStart = function (e) {
  13780. if (window.MSGesture === undefined) {
  13781. return;
  13782. }
  13783. if (!_this._MSGestureHandler) {
  13784. _this._MSGestureHandler = new MSGesture();
  13785. _this._MSGestureHandler.target = element;
  13786. }
  13787. _this._MSGestureHandler.addPointer(e.pointerId);
  13788. };
  13789. this._onGesture = function (e) {
  13790. _this.camera.radius *= e.scale;
  13791. if (e.preventDefault) {
  13792. if (!noPreventDefault) {
  13793. e.stopPropagation();
  13794. e.preventDefault();
  13795. }
  13796. }
  13797. };
  13798. element.addEventListener("mousemove", this._onMouseMove, false);
  13799. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  13800. element.addEventListener("MSGestureChange", this._onGesture, false);
  13801. element.addEventListener("keydown", this._onKeyDown, false);
  13802. element.addEventListener("keyup", this._onKeyUp, false);
  13803. BABYLON.Tools.RegisterTopRootEvents([
  13804. { name: "blur", handler: this._onLostFocus }
  13805. ]);
  13806. };
  13807. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  13808. if (element && this._observer) {
  13809. this.camera.getScene().onPointerObservable.remove(this._observer);
  13810. this._observer = null;
  13811. element.removeEventListener("contextmenu", this._onContextMenu);
  13812. element.removeEventListener("mousemove", this._onMouseMove);
  13813. element.removeEventListener("MSPointerDown", this._onGestureStart);
  13814. element.removeEventListener("MSGestureChange", this._onGesture);
  13815. element.removeEventListener("keydown", this._onKeyDown);
  13816. element.removeEventListener("keyup", this._onKeyUp);
  13817. this._isPanClick = false;
  13818. this.pinchInwards = true;
  13819. this._onKeyDown = null;
  13820. this._onKeyUp = null;
  13821. this._onMouseMove = null;
  13822. this._onGestureStart = null;
  13823. this._onGesture = null;
  13824. this._MSGestureHandler = null;
  13825. this._onLostFocus = null;
  13826. this._onContextMenu = null;
  13827. }
  13828. BABYLON.Tools.UnregisterTopRootEvents([
  13829. { name: "blur", handler: this._onLostFocus }
  13830. ]);
  13831. };
  13832. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  13833. return "ArcRotateCameraPointersInput";
  13834. };
  13835. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  13836. return "pointers";
  13837. };
  13838. __decorate([
  13839. BABYLON.serialize()
  13840. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  13841. __decorate([
  13842. BABYLON.serialize()
  13843. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  13844. __decorate([
  13845. BABYLON.serialize()
  13846. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  13847. __decorate([
  13848. BABYLON.serialize()
  13849. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  13850. return ArcRotateCameraPointersInput;
  13851. })();
  13852. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  13853. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  13854. })(BABYLON || (BABYLON = {}));
  13855. var BABYLON;
  13856. (function (BABYLON) {
  13857. var ArcRotateCameraGamepadInput = (function () {
  13858. function ArcRotateCameraGamepadInput() {
  13859. this.gamepadRotationSensibility = 80;
  13860. this.gamepadMoveSensibility = 40;
  13861. }
  13862. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13863. var _this = this;
  13864. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13865. };
  13866. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  13867. if (this._gamepads) {
  13868. this._gamepads.dispose();
  13869. }
  13870. this.gamepad = null;
  13871. };
  13872. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  13873. if (this.gamepad) {
  13874. var camera = this.camera;
  13875. var RSValues = this.gamepad.rightStick;
  13876. if (RSValues.x != 0) {
  13877. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  13878. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  13879. camera.inertialAlphaOffset += normalizedRX;
  13880. }
  13881. }
  13882. if (RSValues.y != 0) {
  13883. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  13884. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  13885. camera.inertialBetaOffset += normalizedRY;
  13886. }
  13887. }
  13888. var LSValues = this.gamepad.leftStick;
  13889. if (LSValues.y != 0) {
  13890. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13891. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  13892. this.camera.inertialRadiusOffset -= normalizedLY;
  13893. }
  13894. }
  13895. }
  13896. };
  13897. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13898. // Only the first gamepad can control the camera
  13899. if (gamepad.index === 0) {
  13900. this.gamepad = gamepad;
  13901. }
  13902. };
  13903. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  13904. return "ArcRotateCameraGamepadInput";
  13905. };
  13906. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  13907. return "gamepad";
  13908. };
  13909. __decorate([
  13910. BABYLON.serialize()
  13911. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  13912. __decorate([
  13913. BABYLON.serialize()
  13914. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13915. return ArcRotateCameraGamepadInput;
  13916. })();
  13917. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13918. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13919. })(BABYLON || (BABYLON = {}));
  13920. var BABYLON;
  13921. (function (BABYLON) {
  13922. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13923. function ArcRotateCameraVRDeviceOrientationInput() {
  13924. this.alphaCorrection = 1;
  13925. this.betaCorrection = 1;
  13926. this.gammaCorrection = 1;
  13927. this._alpha = 0;
  13928. this._beta = 0;
  13929. this._gamma = 0;
  13930. this._dirty = false;
  13931. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13932. }
  13933. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13934. this.camera.attachControl(element, noPreventDefault);
  13935. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13936. };
  13937. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13938. var camera = this.camera;
  13939. this._alpha = +evt.alpha | 0;
  13940. this._beta = +evt.beta | 0;
  13941. this._gamma = +evt.gamma | 0;
  13942. this._dirty = true;
  13943. };
  13944. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13945. if (this._dirty) {
  13946. this._dirty = false;
  13947. if (this._gamma < 0) {
  13948. this._gamma = 180 + this._gamma;
  13949. }
  13950. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13951. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13952. }
  13953. };
  13954. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13955. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13956. };
  13957. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13958. return "ArcRotateCameraVRDeviceOrientationInput";
  13959. };
  13960. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13961. return "VRDeviceOrientation";
  13962. };
  13963. return ArcRotateCameraVRDeviceOrientationInput;
  13964. })();
  13965. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13966. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13967. })(BABYLON || (BABYLON = {}));
  13968. var BABYLON;
  13969. (function (BABYLON) {
  13970. var TargetCamera = (function (_super) {
  13971. __extends(TargetCamera, _super);
  13972. function TargetCamera(name, position, scene) {
  13973. _super.call(this, name, position, scene);
  13974. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13975. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13976. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13977. this.speed = 2.0;
  13978. this.noRotationConstraint = false;
  13979. this.lockedTarget = null;
  13980. this._currentTarget = BABYLON.Vector3.Zero();
  13981. this._viewMatrix = BABYLON.Matrix.Zero();
  13982. this._camMatrix = BABYLON.Matrix.Zero();
  13983. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13984. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13985. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13986. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13987. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13988. this._lookAtTemp = BABYLON.Matrix.Zero();
  13989. this._tempMatrix = BABYLON.Matrix.Zero();
  13990. }
  13991. TargetCamera.prototype.getFrontPosition = function (distance) {
  13992. var direction = this.getTarget().subtract(this.position);
  13993. direction.normalize();
  13994. direction.scaleInPlace(distance);
  13995. return this.globalPosition.add(direction);
  13996. };
  13997. TargetCamera.prototype._getLockedTargetPosition = function () {
  13998. if (!this.lockedTarget) {
  13999. return null;
  14000. }
  14001. return this.lockedTarget.position || this.lockedTarget;
  14002. };
  14003. // Cache
  14004. TargetCamera.prototype._initCache = function () {
  14005. _super.prototype._initCache.call(this);
  14006. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14007. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14008. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14009. };
  14010. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14011. if (!ignoreParentClass) {
  14012. _super.prototype._updateCache.call(this);
  14013. }
  14014. var lockedTargetPosition = this._getLockedTargetPosition();
  14015. if (!lockedTargetPosition) {
  14016. this._cache.lockedTarget = null;
  14017. }
  14018. else {
  14019. if (!this._cache.lockedTarget) {
  14020. this._cache.lockedTarget = lockedTargetPosition.clone();
  14021. }
  14022. else {
  14023. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14024. }
  14025. }
  14026. this._cache.rotation.copyFrom(this.rotation);
  14027. if (this.rotationQuaternion)
  14028. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14029. };
  14030. // Synchronized
  14031. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14032. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14033. return false;
  14034. }
  14035. var lockedTargetPosition = this._getLockedTargetPosition();
  14036. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14037. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14038. };
  14039. // Methods
  14040. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14041. var engine = this.getEngine();
  14042. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14043. };
  14044. // Target
  14045. TargetCamera.prototype.setTarget = function (target) {
  14046. this.upVector.normalize();
  14047. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14048. this._camMatrix.invert();
  14049. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14050. var vDir = target.subtract(this.position);
  14051. if (vDir.x >= 0.0) {
  14052. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14053. }
  14054. else {
  14055. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14056. }
  14057. this.rotation.z = 0;
  14058. if (isNaN(this.rotation.x)) {
  14059. this.rotation.x = 0;
  14060. }
  14061. if (isNaN(this.rotation.y)) {
  14062. this.rotation.y = 0;
  14063. }
  14064. if (isNaN(this.rotation.z)) {
  14065. this.rotation.z = 0;
  14066. }
  14067. if (this.rotationQuaternion) {
  14068. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14069. }
  14070. };
  14071. TargetCamera.prototype.getTarget = function () {
  14072. return this._currentTarget;
  14073. };
  14074. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14075. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14076. };
  14077. TargetCamera.prototype._updatePosition = function () {
  14078. this.position.addInPlace(this.cameraDirection);
  14079. };
  14080. TargetCamera.prototype._checkInputs = function () {
  14081. var needToMove = this._decideIfNeedsToMove();
  14082. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14083. // Move
  14084. if (needToMove) {
  14085. this._updatePosition();
  14086. }
  14087. // Rotate
  14088. if (needToRotate) {
  14089. this.rotation.x += this.cameraRotation.x;
  14090. this.rotation.y += this.cameraRotation.y;
  14091. if (!this.noRotationConstraint) {
  14092. var limit = (Math.PI / 2) * 0.95;
  14093. if (this.rotation.x > limit)
  14094. this.rotation.x = limit;
  14095. if (this.rotation.x < -limit)
  14096. this.rotation.x = -limit;
  14097. }
  14098. }
  14099. // Inertia
  14100. if (needToMove) {
  14101. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14102. this.cameraDirection.x = 0;
  14103. }
  14104. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14105. this.cameraDirection.y = 0;
  14106. }
  14107. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14108. this.cameraDirection.z = 0;
  14109. }
  14110. this.cameraDirection.scaleInPlace(this.inertia);
  14111. }
  14112. if (needToRotate) {
  14113. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14114. this.cameraRotation.x = 0;
  14115. }
  14116. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14117. this.cameraRotation.y = 0;
  14118. }
  14119. this.cameraRotation.scaleInPlace(this.inertia);
  14120. }
  14121. _super.prototype._checkInputs.call(this);
  14122. };
  14123. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14124. if (this.rotationQuaternion) {
  14125. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14126. //update the up vector!
  14127. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14128. }
  14129. else {
  14130. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14131. }
  14132. };
  14133. TargetCamera.prototype._getViewMatrix = function () {
  14134. if (!this.lockedTarget) {
  14135. // Compute
  14136. this._updateCameraRotationMatrix();
  14137. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14138. // Computing target and final matrix
  14139. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14140. }
  14141. else {
  14142. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14143. }
  14144. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14145. return this._viewMatrix;
  14146. };
  14147. /**
  14148. * @override
  14149. * Override Camera.createRigCamera
  14150. */
  14151. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14152. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14153. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14154. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14155. if (!this.rotationQuaternion) {
  14156. this.rotationQuaternion = new BABYLON.Quaternion();
  14157. }
  14158. rigCamera._cameraRigParams = {};
  14159. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14160. }
  14161. return rigCamera;
  14162. }
  14163. return null;
  14164. };
  14165. /**
  14166. * @override
  14167. * Override Camera._updateRigCameras
  14168. */
  14169. TargetCamera.prototype._updateRigCameras = function () {
  14170. var camLeft = this._rigCameras[0];
  14171. var camRight = this._rigCameras[1];
  14172. switch (this.cameraRigMode) {
  14173. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14174. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14175. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14176. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14177. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14178. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14179. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14180. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14181. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14182. camLeft.setTarget(this.getTarget());
  14183. camRight.setTarget(this.getTarget());
  14184. break;
  14185. case BABYLON.Camera.RIG_MODE_VR:
  14186. case BABYLON.Camera.RIG_MODE_WEBVR:
  14187. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14188. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14189. camLeft.position.copyFrom(this.position);
  14190. camRight.position.copyFrom(this.position);
  14191. break;
  14192. }
  14193. _super.prototype._updateRigCameras.call(this);
  14194. };
  14195. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14196. if (!this._rigCamTransformMatrix) {
  14197. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14198. }
  14199. var target = this.getTarget();
  14200. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14201. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14202. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14203. };
  14204. TargetCamera.prototype.getTypeName = function () {
  14205. return "TargetCamera";
  14206. };
  14207. __decorate([
  14208. BABYLON.serializeAsVector3()
  14209. ], TargetCamera.prototype, "rotation", void 0);
  14210. __decorate([
  14211. BABYLON.serialize()
  14212. ], TargetCamera.prototype, "speed", void 0);
  14213. __decorate([
  14214. BABYLON.serializeAsMeshReference("lockedTargetId")
  14215. ], TargetCamera.prototype, "lockedTarget", void 0);
  14216. return TargetCamera;
  14217. })(BABYLON.Camera);
  14218. BABYLON.TargetCamera = TargetCamera;
  14219. })(BABYLON || (BABYLON = {}));
  14220. var BABYLON;
  14221. (function (BABYLON) {
  14222. var FreeCamera = (function (_super) {
  14223. __extends(FreeCamera, _super);
  14224. function FreeCamera(name, position, scene) {
  14225. var _this = this;
  14226. _super.call(this, name, position, scene);
  14227. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14228. this.checkCollisions = false;
  14229. this.applyGravity = false;
  14230. this._collider = new BABYLON.Collider();
  14231. this._needMoveForGravity = false;
  14232. this._oldPosition = BABYLON.Vector3.Zero();
  14233. this._diffPosition = BABYLON.Vector3.Zero();
  14234. this._newPosition = BABYLON.Vector3.Zero();
  14235. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14236. if (collidedMesh === void 0) { collidedMesh = null; }
  14237. //TODO move this to the collision coordinator!
  14238. if (_this.getScene().workerCollisions)
  14239. newPosition.multiplyInPlace(_this._collider.radius);
  14240. var updatePosition = function (newPos) {
  14241. _this._newPosition.copyFrom(newPos);
  14242. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14243. var oldPosition = _this.position.clone();
  14244. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14245. _this.position.addInPlace(_this._diffPosition);
  14246. if (_this.onCollide && collidedMesh) {
  14247. _this.onCollide(collidedMesh);
  14248. }
  14249. }
  14250. };
  14251. updatePosition(newPosition);
  14252. };
  14253. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14254. this.inputs.addKeyboard().addMouse();
  14255. }
  14256. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14257. //-- begin properties for backward compatibility for inputs
  14258. get: function () {
  14259. var mouse = this.inputs.attached["mouse"];
  14260. if (mouse)
  14261. return mouse.angularSensibility;
  14262. },
  14263. set: function (value) {
  14264. var mouse = this.inputs.attached["mouse"];
  14265. if (mouse)
  14266. mouse.angularSensibility = value;
  14267. },
  14268. enumerable: true,
  14269. configurable: true
  14270. });
  14271. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14272. get: function () {
  14273. var keyboard = this.inputs.attached["keyboard"];
  14274. if (keyboard)
  14275. return keyboard.keysUp;
  14276. },
  14277. set: function (value) {
  14278. var keyboard = this.inputs.attached["keyboard"];
  14279. if (keyboard)
  14280. keyboard.keysUp = value;
  14281. },
  14282. enumerable: true,
  14283. configurable: true
  14284. });
  14285. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14286. get: function () {
  14287. var keyboard = this.inputs.attached["keyboard"];
  14288. if (keyboard)
  14289. return keyboard.keysDown;
  14290. },
  14291. set: function (value) {
  14292. var keyboard = this.inputs.attached["keyboard"];
  14293. if (keyboard)
  14294. keyboard.keysDown = value;
  14295. },
  14296. enumerable: true,
  14297. configurable: true
  14298. });
  14299. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14300. get: function () {
  14301. var keyboard = this.inputs.attached["keyboard"];
  14302. if (keyboard)
  14303. return keyboard.keysLeft;
  14304. },
  14305. set: function (value) {
  14306. var keyboard = this.inputs.attached["keyboard"];
  14307. if (keyboard)
  14308. keyboard.keysLeft = value;
  14309. },
  14310. enumerable: true,
  14311. configurable: true
  14312. });
  14313. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14314. get: function () {
  14315. var keyboard = this.inputs.attached["keyboard"];
  14316. if (keyboard)
  14317. return keyboard.keysRight;
  14318. },
  14319. set: function (value) {
  14320. var keyboard = this.inputs.attached["keyboard"];
  14321. if (keyboard)
  14322. keyboard.keysRight = value;
  14323. },
  14324. enumerable: true,
  14325. configurable: true
  14326. });
  14327. // Controls
  14328. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14329. this.inputs.attachElement(element, noPreventDefault);
  14330. };
  14331. FreeCamera.prototype.detachControl = function (element) {
  14332. this.inputs.detachElement(element);
  14333. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14334. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14335. };
  14336. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14337. var globalPosition;
  14338. if (this.parent) {
  14339. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14340. }
  14341. else {
  14342. globalPosition = this.position;
  14343. }
  14344. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14345. this._collider.radius = this.ellipsoid;
  14346. //no need for clone, as long as gravity is not on.
  14347. var actualVelocity = velocity;
  14348. //add gravity to the velocity to prevent the dual-collision checking
  14349. if (this.applyGravity) {
  14350. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14351. actualVelocity = velocity.add(this.getScene().gravity);
  14352. }
  14353. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14354. };
  14355. FreeCamera.prototype._checkInputs = function () {
  14356. if (!this._localDirection) {
  14357. this._localDirection = BABYLON.Vector3.Zero();
  14358. this._transformedDirection = BABYLON.Vector3.Zero();
  14359. }
  14360. this.inputs.checkInputs();
  14361. _super.prototype._checkInputs.call(this);
  14362. };
  14363. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14364. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14365. };
  14366. FreeCamera.prototype._updatePosition = function () {
  14367. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14368. this._collideWithWorld(this.cameraDirection);
  14369. }
  14370. else {
  14371. this.position.addInPlace(this.cameraDirection);
  14372. }
  14373. };
  14374. FreeCamera.prototype.dispose = function () {
  14375. this.inputs.clear();
  14376. _super.prototype.dispose.call(this);
  14377. };
  14378. FreeCamera.prototype.getTypeName = function () {
  14379. return "FreeCamera";
  14380. };
  14381. __decorate([
  14382. BABYLON.serializeAsVector3()
  14383. ], FreeCamera.prototype, "ellipsoid", void 0);
  14384. __decorate([
  14385. BABYLON.serialize()
  14386. ], FreeCamera.prototype, "checkCollisions", void 0);
  14387. __decorate([
  14388. BABYLON.serialize()
  14389. ], FreeCamera.prototype, "applyGravity", void 0);
  14390. return FreeCamera;
  14391. })(BABYLON.TargetCamera);
  14392. BABYLON.FreeCamera = FreeCamera;
  14393. })(BABYLON || (BABYLON = {}));
  14394. var BABYLON;
  14395. (function (BABYLON) {
  14396. var FreeCameraInputsManager = (function (_super) {
  14397. __extends(FreeCameraInputsManager, _super);
  14398. function FreeCameraInputsManager(camera) {
  14399. _super.call(this, camera);
  14400. }
  14401. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14402. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14403. return this;
  14404. };
  14405. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14406. if (touchEnabled === void 0) { touchEnabled = true; }
  14407. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14408. return this;
  14409. };
  14410. FreeCameraInputsManager.prototype.addGamepad = function () {
  14411. this.add(new BABYLON.FreeCameraGamepadInput());
  14412. return this;
  14413. };
  14414. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14415. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14416. return this;
  14417. };
  14418. FreeCameraInputsManager.prototype.addTouch = function () {
  14419. this.add(new BABYLON.FreeCameraTouchInput());
  14420. return this;
  14421. };
  14422. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14423. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14424. return this;
  14425. };
  14426. return FreeCameraInputsManager;
  14427. })(BABYLON.CameraInputsManager);
  14428. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14429. })(BABYLON || (BABYLON = {}));
  14430. var BABYLON;
  14431. (function (BABYLON) {
  14432. var FollowCamera = (function (_super) {
  14433. __extends(FollowCamera, _super);
  14434. function FollowCamera(name, position, scene, target) {
  14435. _super.call(this, name, position, scene);
  14436. this.radius = 12;
  14437. this.rotationOffset = 0;
  14438. this.heightOffset = 4;
  14439. this.cameraAcceleration = 0.05;
  14440. this.maxCameraSpeed = 20;
  14441. this.target = target;
  14442. }
  14443. FollowCamera.prototype.getRadians = function (degrees) {
  14444. return degrees * Math.PI / 180;
  14445. };
  14446. FollowCamera.prototype.follow = function (cameraTarget) {
  14447. if (!cameraTarget)
  14448. return;
  14449. var yRotation;
  14450. if (cameraTarget.rotationQuaternion) {
  14451. var rotMatrix = new BABYLON.Matrix();
  14452. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14453. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14454. }
  14455. else {
  14456. yRotation = cameraTarget.rotation.y;
  14457. }
  14458. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14459. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14460. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14461. var dx = targetX - this.position.x;
  14462. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14463. var dz = (targetZ) - this.position.z;
  14464. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14465. var vy = dy * this.cameraAcceleration;
  14466. var vz = dz * this.cameraAcceleration * 2;
  14467. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14468. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14469. }
  14470. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14471. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14472. }
  14473. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14474. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14475. }
  14476. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14477. this.setTarget(cameraTarget.position);
  14478. };
  14479. FollowCamera.prototype._checkInputs = function () {
  14480. _super.prototype._checkInputs.call(this);
  14481. this.follow(this.target);
  14482. };
  14483. FollowCamera.prototype.getTypeName = function () {
  14484. return "FollowCamera";
  14485. };
  14486. __decorate([
  14487. BABYLON.serialize()
  14488. ], FollowCamera.prototype, "radius", void 0);
  14489. __decorate([
  14490. BABYLON.serialize()
  14491. ], FollowCamera.prototype, "rotationOffset", void 0);
  14492. __decorate([
  14493. BABYLON.serialize()
  14494. ], FollowCamera.prototype, "heightOffset", void 0);
  14495. __decorate([
  14496. BABYLON.serialize()
  14497. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14498. __decorate([
  14499. BABYLON.serialize()
  14500. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14501. __decorate([
  14502. BABYLON.serializeAsMeshReference("lockedTargetId")
  14503. ], FollowCamera.prototype, "target", void 0);
  14504. return FollowCamera;
  14505. })(BABYLON.TargetCamera);
  14506. BABYLON.FollowCamera = FollowCamera;
  14507. var ArcFollowCamera = (function (_super) {
  14508. __extends(ArcFollowCamera, _super);
  14509. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14510. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14511. this.alpha = alpha;
  14512. this.beta = beta;
  14513. this.radius = radius;
  14514. this.target = target;
  14515. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14516. this.follow();
  14517. }
  14518. ArcFollowCamera.prototype.follow = function () {
  14519. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14520. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14521. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14522. this.position = this.target.position.add(this._cartesianCoordinates);
  14523. this.setTarget(this.target.position);
  14524. };
  14525. ArcFollowCamera.prototype._checkInputs = function () {
  14526. _super.prototype._checkInputs.call(this);
  14527. this.follow();
  14528. };
  14529. ArcFollowCamera.prototype.getTypeName = function () {
  14530. return "ArcFollowCamera";
  14531. };
  14532. return ArcFollowCamera;
  14533. })(BABYLON.TargetCamera);
  14534. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14535. })(BABYLON || (BABYLON = {}));
  14536. var BABYLON;
  14537. (function (BABYLON) {
  14538. // We're mainly based on the logic defined into the FreeCamera code
  14539. var TouchCamera = (function (_super) {
  14540. __extends(TouchCamera, _super);
  14541. //-- end properties for backward compatibility for inputs
  14542. function TouchCamera(name, position, scene) {
  14543. _super.call(this, name, position, scene);
  14544. this.inputs.addTouch();
  14545. this._setupInputs();
  14546. }
  14547. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14548. //-- Begin properties for backward compatibility for inputs
  14549. get: function () {
  14550. var touch = this.inputs.attached["touch"];
  14551. if (touch)
  14552. return touch.touchAngularSensibility;
  14553. },
  14554. set: function (value) {
  14555. var touch = this.inputs.attached["touch"];
  14556. if (touch)
  14557. touch.touchAngularSensibility = value;
  14558. },
  14559. enumerable: true,
  14560. configurable: true
  14561. });
  14562. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14563. get: function () {
  14564. var touch = this.inputs.attached["touch"];
  14565. if (touch)
  14566. return touch.touchMoveSensibility;
  14567. },
  14568. set: function (value) {
  14569. var touch = this.inputs.attached["touch"];
  14570. if (touch)
  14571. touch.touchMoveSensibility = value;
  14572. },
  14573. enumerable: true,
  14574. configurable: true
  14575. });
  14576. TouchCamera.prototype.getTypeName = function () {
  14577. return "TouchCamera";
  14578. };
  14579. TouchCamera.prototype._setupInputs = function () {
  14580. var mouse = this.inputs.attached["mouse"];
  14581. if (mouse) {
  14582. mouse.touchEnabled = false;
  14583. }
  14584. };
  14585. return TouchCamera;
  14586. })(BABYLON.FreeCamera);
  14587. BABYLON.TouchCamera = TouchCamera;
  14588. })(BABYLON || (BABYLON = {}));
  14589. var BABYLON;
  14590. (function (BABYLON) {
  14591. var ArcRotateCamera = (function (_super) {
  14592. __extends(ArcRotateCamera, _super);
  14593. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14594. var _this = this;
  14595. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14596. this.inertialAlphaOffset = 0;
  14597. this.inertialBetaOffset = 0;
  14598. this.inertialRadiusOffset = 0;
  14599. this.lowerAlphaLimit = null;
  14600. this.upperAlphaLimit = null;
  14601. this.lowerBetaLimit = 0.01;
  14602. this.upperBetaLimit = Math.PI;
  14603. this.lowerRadiusLimit = null;
  14604. this.upperRadiusLimit = null;
  14605. this.inertialPanningX = 0;
  14606. this.inertialPanningY = 0;
  14607. //-- end properties for backward compatibility for inputs
  14608. this.zoomOnFactor = 1;
  14609. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14610. this.allowUpsideDown = true;
  14611. this._viewMatrix = new BABYLON.Matrix();
  14612. // Panning
  14613. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14614. this.checkCollisions = false;
  14615. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14616. this._collider = new BABYLON.Collider();
  14617. this._previousPosition = BABYLON.Vector3.Zero();
  14618. this._collisionVelocity = BABYLON.Vector3.Zero();
  14619. this._newPosition = BABYLON.Vector3.Zero();
  14620. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14621. if (collidedMesh === void 0) { collidedMesh = null; }
  14622. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14623. newPosition.multiplyInPlace(_this._collider.radius);
  14624. }
  14625. if (!collidedMesh) {
  14626. _this._previousPosition.copyFrom(_this.position);
  14627. }
  14628. else {
  14629. _this.setPosition(newPosition);
  14630. if (_this.onCollide) {
  14631. _this.onCollide(collidedMesh);
  14632. }
  14633. }
  14634. // Recompute because of constraints
  14635. var cosa = Math.cos(_this.alpha);
  14636. var sina = Math.sin(_this.alpha);
  14637. var cosb = Math.cos(_this.beta);
  14638. var sinb = Math.sin(_this.beta);
  14639. if (sinb === 0) {
  14640. sinb = 0.0001;
  14641. }
  14642. var target = _this._getTargetPosition();
  14643. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  14644. _this.position.copyFrom(_this._newPosition);
  14645. var up = _this.upVector;
  14646. if (_this.allowUpsideDown && _this.beta < 0) {
  14647. up = up.clone();
  14648. up = up.negate();
  14649. }
  14650. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  14651. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  14652. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  14653. _this._collisionTriggered = false;
  14654. };
  14655. if (!target) {
  14656. this.target = BABYLON.Vector3.Zero();
  14657. }
  14658. else {
  14659. this.target = target;
  14660. }
  14661. this.alpha = alpha;
  14662. this.beta = beta;
  14663. this.radius = radius;
  14664. this.getViewMatrix();
  14665. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  14666. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  14667. }
  14668. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  14669. //-- begin properties for backward compatibility for inputs
  14670. get: function () {
  14671. var pointers = this.inputs.attached["pointers"];
  14672. if (pointers)
  14673. return pointers.angularSensibilityX;
  14674. },
  14675. set: function (value) {
  14676. var pointers = this.inputs.attached["pointers"];
  14677. if (pointers) {
  14678. pointers.angularSensibilityX = value;
  14679. }
  14680. },
  14681. enumerable: true,
  14682. configurable: true
  14683. });
  14684. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  14685. get: function () {
  14686. var pointers = this.inputs.attached["pointers"];
  14687. if (pointers)
  14688. return pointers.angularSensibilityY;
  14689. },
  14690. set: function (value) {
  14691. var pointers = this.inputs.attached["pointers"];
  14692. if (pointers) {
  14693. pointers.angularSensibilityY = value;
  14694. }
  14695. },
  14696. enumerable: true,
  14697. configurable: true
  14698. });
  14699. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  14700. get: function () {
  14701. var pointers = this.inputs.attached["pointers"];
  14702. if (pointers)
  14703. return pointers.pinchPrecision;
  14704. },
  14705. set: function (value) {
  14706. var pointers = this.inputs.attached["pointers"];
  14707. if (pointers) {
  14708. pointers.pinchPrecision = value;
  14709. }
  14710. },
  14711. enumerable: true,
  14712. configurable: true
  14713. });
  14714. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  14715. get: function () {
  14716. var pointers = this.inputs.attached["pointers"];
  14717. if (pointers)
  14718. return pointers.panningSensibility;
  14719. },
  14720. set: function (value) {
  14721. var pointers = this.inputs.attached["pointers"];
  14722. if (pointers) {
  14723. pointers.panningSensibility = value;
  14724. }
  14725. },
  14726. enumerable: true,
  14727. configurable: true
  14728. });
  14729. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  14730. get: function () {
  14731. var keyboard = this.inputs.attached["keyboard"];
  14732. if (keyboard)
  14733. return keyboard.keysUp;
  14734. },
  14735. set: function (value) {
  14736. var keyboard = this.inputs.attached["keyboard"];
  14737. if (keyboard)
  14738. keyboard.keysUp = value;
  14739. },
  14740. enumerable: true,
  14741. configurable: true
  14742. });
  14743. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  14744. get: function () {
  14745. var keyboard = this.inputs.attached["keyboard"];
  14746. if (keyboard)
  14747. return keyboard.keysDown;
  14748. },
  14749. set: function (value) {
  14750. var keyboard = this.inputs.attached["keyboard"];
  14751. if (keyboard)
  14752. keyboard.keysDown = value;
  14753. },
  14754. enumerable: true,
  14755. configurable: true
  14756. });
  14757. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  14758. get: function () {
  14759. var keyboard = this.inputs.attached["keyboard"];
  14760. if (keyboard)
  14761. return keyboard.keysLeft;
  14762. },
  14763. set: function (value) {
  14764. var keyboard = this.inputs.attached["keyboard"];
  14765. if (keyboard)
  14766. keyboard.keysLeft = value;
  14767. },
  14768. enumerable: true,
  14769. configurable: true
  14770. });
  14771. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  14772. get: function () {
  14773. var keyboard = this.inputs.attached["keyboard"];
  14774. if (keyboard)
  14775. return keyboard.keysRight;
  14776. },
  14777. set: function (value) {
  14778. var keyboard = this.inputs.attached["keyboard"];
  14779. if (keyboard)
  14780. keyboard.keysRight = value;
  14781. },
  14782. enumerable: true,
  14783. configurable: true
  14784. });
  14785. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  14786. get: function () {
  14787. var mousewheel = this.inputs.attached["mousewheel"];
  14788. if (mousewheel)
  14789. return mousewheel.wheelPrecision;
  14790. },
  14791. set: function (value) {
  14792. var mousewheel = this.inputs.attached["mousewheel"];
  14793. if (mousewheel)
  14794. mousewheel.wheelPrecision = value;
  14795. },
  14796. enumerable: true,
  14797. configurable: true
  14798. });
  14799. // Cache
  14800. ArcRotateCamera.prototype._initCache = function () {
  14801. _super.prototype._initCache.call(this);
  14802. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14803. this._cache.alpha = undefined;
  14804. this._cache.beta = undefined;
  14805. this._cache.radius = undefined;
  14806. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  14807. };
  14808. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  14809. if (!ignoreParentClass) {
  14810. _super.prototype._updateCache.call(this);
  14811. }
  14812. this._cache.target.copyFrom(this._getTargetPosition());
  14813. this._cache.alpha = this.alpha;
  14814. this._cache.beta = this.beta;
  14815. this._cache.radius = this.radius;
  14816. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  14817. };
  14818. ArcRotateCamera.prototype._getTargetPosition = function () {
  14819. if (this.target.getAbsolutePosition) {
  14820. return this.target.getAbsolutePosition();
  14821. }
  14822. return this.target;
  14823. };
  14824. // Synchronized
  14825. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  14826. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  14827. return false;
  14828. return this._cache.target.equals(this.target)
  14829. && this._cache.alpha === this.alpha
  14830. && this._cache.beta === this.beta
  14831. && this._cache.radius === this.radius
  14832. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  14833. };
  14834. // Methods
  14835. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  14836. var _this = this;
  14837. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  14838. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  14839. this._useCtrlForPanning = useCtrlForPanning;
  14840. this._panningMouseButton = panningMouseButton;
  14841. this.inputs.attachElement(element, noPreventDefault);
  14842. this._reset = function () {
  14843. _this.inertialAlphaOffset = 0;
  14844. _this.inertialBetaOffset = 0;
  14845. _this.inertialRadiusOffset = 0;
  14846. };
  14847. };
  14848. ArcRotateCamera.prototype.detachControl = function (element) {
  14849. this.inputs.detachElement(element);
  14850. if (this._reset) {
  14851. this._reset();
  14852. }
  14853. };
  14854. ArcRotateCamera.prototype._checkInputs = function () {
  14855. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  14856. if (this._collisionTriggered) {
  14857. return;
  14858. }
  14859. this.inputs.checkInputs();
  14860. // Inertia
  14861. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  14862. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  14863. this.beta += this.inertialBetaOffset;
  14864. this.radius -= this.inertialRadiusOffset;
  14865. this.inertialAlphaOffset *= this.inertia;
  14866. this.inertialBetaOffset *= this.inertia;
  14867. this.inertialRadiusOffset *= this.inertia;
  14868. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  14869. this.inertialAlphaOffset = 0;
  14870. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  14871. this.inertialBetaOffset = 0;
  14872. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  14873. this.inertialRadiusOffset = 0;
  14874. }
  14875. // Panning inertia
  14876. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  14877. if (!this._localDirection) {
  14878. this._localDirection = BABYLON.Vector3.Zero();
  14879. this._transformedDirection = BABYLON.Vector3.Zero();
  14880. }
  14881. this.inertialPanningX *= this.inertia;
  14882. this.inertialPanningY *= this.inertia;
  14883. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  14884. this.inertialPanningX = 0;
  14885. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  14886. this.inertialPanningY = 0;
  14887. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  14888. this._localDirection.multiplyInPlace(this.panningAxis);
  14889. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  14890. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  14891. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  14892. if (!this.panningAxis.y) {
  14893. this._transformedDirection.y = 0;
  14894. }
  14895. if (!this.target.getAbsolutePosition) {
  14896. this.target.addInPlace(this._transformedDirection);
  14897. }
  14898. }
  14899. // Limits
  14900. this._checkLimits();
  14901. _super.prototype._checkInputs.call(this);
  14902. };
  14903. ArcRotateCamera.prototype._checkLimits = function () {
  14904. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14905. if (this.allowUpsideDown && this.beta > Math.PI) {
  14906. this.beta = this.beta - (2 * Math.PI);
  14907. }
  14908. }
  14909. else {
  14910. if (this.beta < this.lowerBetaLimit) {
  14911. this.beta = this.lowerBetaLimit;
  14912. }
  14913. }
  14914. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14915. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14916. this.beta = this.beta + (2 * Math.PI);
  14917. }
  14918. }
  14919. else {
  14920. if (this.beta > this.upperBetaLimit) {
  14921. this.beta = this.upperBetaLimit;
  14922. }
  14923. }
  14924. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14925. this.alpha = this.lowerAlphaLimit;
  14926. }
  14927. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14928. this.alpha = this.upperAlphaLimit;
  14929. }
  14930. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14931. this.radius = this.lowerRadiusLimit;
  14932. }
  14933. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14934. this.radius = this.upperRadiusLimit;
  14935. }
  14936. };
  14937. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14938. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14939. this.radius = radiusv3.length();
  14940. // Alpha
  14941. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14942. if (radiusv3.z < 0) {
  14943. this.alpha = 2 * Math.PI - this.alpha;
  14944. }
  14945. // Beta
  14946. this.beta = Math.acos(radiusv3.y / this.radius);
  14947. this._checkLimits();
  14948. };
  14949. ArcRotateCamera.prototype.setPosition = function (position) {
  14950. if (this.position.equals(position)) {
  14951. return;
  14952. }
  14953. this.position.copyFrom(position);
  14954. this.rebuildAnglesAndRadius();
  14955. };
  14956. ArcRotateCamera.prototype.setTarget = function (target) {
  14957. if (this._getTargetPosition().equals(target)) {
  14958. return;
  14959. }
  14960. this.target = target;
  14961. this.rebuildAnglesAndRadius();
  14962. };
  14963. ArcRotateCamera.prototype._getViewMatrix = function () {
  14964. // Compute
  14965. var cosa = Math.cos(this.alpha);
  14966. var sina = Math.sin(this.alpha);
  14967. var cosb = Math.cos(this.beta);
  14968. var sinb = Math.sin(this.beta);
  14969. if (sinb === 0) {
  14970. sinb = 0.0001;
  14971. }
  14972. var target = this._getTargetPosition();
  14973. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14974. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14975. this._collider.radius = this.collisionRadius;
  14976. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14977. this._collisionTriggered = true;
  14978. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14979. }
  14980. else {
  14981. this.position.copyFrom(this._newPosition);
  14982. var up = this.upVector;
  14983. if (this.allowUpsideDown && this.beta < 0) {
  14984. up = up.clone();
  14985. up = up.negate();
  14986. }
  14987. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14988. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14989. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14990. }
  14991. return this._viewMatrix;
  14992. };
  14993. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14994. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14995. meshes = meshes || this.getScene().meshes;
  14996. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14997. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14998. this.radius = distance * this.zoomOnFactor;
  14999. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15000. };
  15001. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15002. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15003. var meshesOrMinMaxVector;
  15004. var distance;
  15005. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15006. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15007. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15008. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15009. }
  15010. else {
  15011. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15012. distance = meshesOrMinMaxVectorAndDistance.distance;
  15013. }
  15014. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15015. if (!doNotUpdateMaxZ) {
  15016. this.maxZ = distance * 2;
  15017. }
  15018. };
  15019. /**
  15020. * @override
  15021. * Override Camera.createRigCamera
  15022. */
  15023. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15024. var alphaShift;
  15025. switch (this.cameraRigMode) {
  15026. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15027. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15028. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15029. case BABYLON.Camera.RIG_MODE_VR:
  15030. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15031. break;
  15032. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15033. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15034. break;
  15035. }
  15036. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15037. rigCam._cameraRigParams = {};
  15038. return rigCam;
  15039. };
  15040. /**
  15041. * @override
  15042. * Override Camera._updateRigCameras
  15043. */
  15044. ArcRotateCamera.prototype._updateRigCameras = function () {
  15045. var camLeft = this._rigCameras[0];
  15046. var camRight = this._rigCameras[1];
  15047. camLeft.beta = camRight.beta = this.beta;
  15048. camLeft.radius = camRight.radius = this.radius;
  15049. switch (this.cameraRigMode) {
  15050. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15051. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15052. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15053. case BABYLON.Camera.RIG_MODE_VR:
  15054. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15055. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15056. break;
  15057. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15058. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15059. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15060. break;
  15061. }
  15062. _super.prototype._updateRigCameras.call(this);
  15063. };
  15064. ArcRotateCamera.prototype.dispose = function () {
  15065. this.inputs.clear();
  15066. _super.prototype.dispose.call(this);
  15067. };
  15068. ArcRotateCamera.prototype.getTypeName = function () {
  15069. return "ArcRotateCamera";
  15070. };
  15071. __decorate([
  15072. BABYLON.serialize()
  15073. ], ArcRotateCamera.prototype, "alpha", void 0);
  15074. __decorate([
  15075. BABYLON.serialize()
  15076. ], ArcRotateCamera.prototype, "beta", void 0);
  15077. __decorate([
  15078. BABYLON.serialize()
  15079. ], ArcRotateCamera.prototype, "radius", void 0);
  15080. __decorate([
  15081. BABYLON.serializeAsVector3()
  15082. ], ArcRotateCamera.prototype, "target", void 0);
  15083. __decorate([
  15084. BABYLON.serialize()
  15085. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15086. __decorate([
  15087. BABYLON.serialize()
  15088. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15089. __decorate([
  15090. BABYLON.serialize()
  15091. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15092. __decorate([
  15093. BABYLON.serialize()
  15094. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15095. __decorate([
  15096. BABYLON.serialize()
  15097. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15098. __decorate([
  15099. BABYLON.serialize()
  15100. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15101. __decorate([
  15102. BABYLON.serialize()
  15103. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15104. __decorate([
  15105. BABYLON.serialize()
  15106. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15107. __decorate([
  15108. BABYLON.serialize()
  15109. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15110. __decorate([
  15111. BABYLON.serialize()
  15112. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15113. __decorate([
  15114. BABYLON.serialize()
  15115. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15116. __decorate([
  15117. BABYLON.serialize()
  15118. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15119. __decorate([
  15120. BABYLON.serialize()
  15121. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15122. return ArcRotateCamera;
  15123. })(BABYLON.TargetCamera);
  15124. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15125. })(BABYLON || (BABYLON = {}));
  15126. var BABYLON;
  15127. (function (BABYLON) {
  15128. var ArcRotateCameraInputsManager = (function (_super) {
  15129. __extends(ArcRotateCameraInputsManager, _super);
  15130. function ArcRotateCameraInputsManager(camera) {
  15131. _super.call(this, camera);
  15132. }
  15133. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15134. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15135. return this;
  15136. };
  15137. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15138. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15139. return this;
  15140. };
  15141. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15142. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15143. return this;
  15144. };
  15145. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15146. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15147. return this;
  15148. };
  15149. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15150. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15151. return this;
  15152. };
  15153. return ArcRotateCameraInputsManager;
  15154. })(BABYLON.CameraInputsManager);
  15155. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15156. })(BABYLON || (BABYLON = {}));
  15157. var BABYLON;
  15158. (function (BABYLON) {
  15159. var RenderingManager = (function () {
  15160. function RenderingManager(scene) {
  15161. this._renderingGroups = new Array();
  15162. this._autoClearDepthStencil = {};
  15163. this._customOpaqueSortCompareFn = {};
  15164. this._customAlphaTestSortCompareFn = {};
  15165. this._customTransparentSortCompareFn = {};
  15166. this._scene = scene;
  15167. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15168. this._autoClearDepthStencil[i] = true;
  15169. }
  15170. }
  15171. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15172. if (this._scene._activeParticleSystems.length === 0) {
  15173. return;
  15174. }
  15175. // Particles
  15176. var activeCamera = this._scene.activeCamera;
  15177. this._scene._particlesDuration.beginMonitoring();
  15178. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15179. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15180. if (particleSystem.renderingGroupId !== index) {
  15181. continue;
  15182. }
  15183. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15184. continue;
  15185. }
  15186. this._clearDepthStencilBuffer();
  15187. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15188. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15189. }
  15190. }
  15191. this._scene._particlesDuration.endMonitoring(false);
  15192. };
  15193. RenderingManager.prototype._renderSprites = function (index) {
  15194. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15195. return;
  15196. }
  15197. // Sprites
  15198. var activeCamera = this._scene.activeCamera;
  15199. this._scene._spritesDuration.beginMonitoring();
  15200. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15201. var spriteManager = this._scene.spriteManagers[id];
  15202. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15203. this._clearDepthStencilBuffer();
  15204. spriteManager.render();
  15205. }
  15206. }
  15207. this._scene._spritesDuration.endMonitoring(false);
  15208. };
  15209. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15210. if (this._depthStencilBufferAlreadyCleaned) {
  15211. return;
  15212. }
  15213. this._scene.getEngine().clear(0, false, true, true);
  15214. this._depthStencilBufferAlreadyCleaned = true;
  15215. };
  15216. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15217. if (this._currentRenderSprites) {
  15218. this._renderSprites(this._currentIndex);
  15219. }
  15220. if (this._currentRenderParticles) {
  15221. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15222. }
  15223. };
  15224. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15225. this._currentActiveMeshes = activeMeshes;
  15226. this._currentRenderParticles = renderParticles;
  15227. this._currentRenderSprites = renderSprites;
  15228. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15229. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15230. var renderingGroup = this._renderingGroups[index];
  15231. var needToStepBack = false;
  15232. this._currentIndex = index;
  15233. if (renderingGroup) {
  15234. if (this._autoClearDepthStencil[index]) {
  15235. this._clearDepthStencilBuffer();
  15236. }
  15237. if (!renderingGroup.onBeforeTransparentRendering) {
  15238. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15239. }
  15240. if (!renderingGroup.render(customRenderFunction)) {
  15241. this._renderingGroups.splice(index, 1);
  15242. needToStepBack = true;
  15243. this._renderSpritesAndParticles();
  15244. }
  15245. }
  15246. else {
  15247. this._renderSpritesAndParticles();
  15248. }
  15249. if (needToStepBack) {
  15250. index--;
  15251. }
  15252. }
  15253. };
  15254. RenderingManager.prototype.reset = function () {
  15255. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15256. var renderingGroup = this._renderingGroups[index];
  15257. if (renderingGroup) {
  15258. renderingGroup.prepare();
  15259. }
  15260. }
  15261. };
  15262. RenderingManager.prototype.dispatch = function (subMesh) {
  15263. var mesh = subMesh.getMesh();
  15264. var renderingGroupId = mesh.renderingGroupId || 0;
  15265. if (!this._renderingGroups[renderingGroupId]) {
  15266. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15267. }
  15268. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15269. };
  15270. /**
  15271. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15272. * This allowed control for front to back rendering or reversly depending of the special needs.
  15273. *
  15274. * @param renderingGroupId The rendering group id corresponding to its index
  15275. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15276. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15277. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15278. */
  15279. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15280. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15281. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15282. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15283. if (this._renderingGroups[renderingGroupId]) {
  15284. var group = this._renderingGroups[renderingGroupId];
  15285. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15286. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15287. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15288. }
  15289. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15290. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15291. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15292. };
  15293. /**
  15294. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15295. *
  15296. * @param renderingGroupId The rendering group id corresponding to its index
  15297. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15298. */
  15299. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15300. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15301. };
  15302. /**
  15303. * The max id used for rendering groups (not included)
  15304. */
  15305. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15306. /**
  15307. * The min id used for rendering groups (included)
  15308. */
  15309. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15310. return RenderingManager;
  15311. })();
  15312. BABYLON.RenderingManager = RenderingManager;
  15313. })(BABYLON || (BABYLON = {}));
  15314. var BABYLON;
  15315. (function (BABYLON) {
  15316. var RenderingGroup = (function () {
  15317. /**
  15318. * Creates a new rendering group.
  15319. * @param index The rendering group index
  15320. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15321. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15322. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15323. */
  15324. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15325. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15326. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15327. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15328. this.index = index;
  15329. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15330. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15331. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15332. this._scene = scene;
  15333. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15334. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15335. this.transparentSortCompareFn = transparentSortCompareFn;
  15336. }
  15337. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15338. /**
  15339. * Set the opaque sort comparison function.
  15340. * If null the sub meshes will be render in the order they were created
  15341. */
  15342. set: function (value) {
  15343. this._opaqueSortCompareFn = value;
  15344. if (value) {
  15345. this._renderOpaque = this.renderOpaqueSorted;
  15346. }
  15347. else {
  15348. this._renderOpaque = RenderingGroup.renderUnsorted;
  15349. }
  15350. },
  15351. enumerable: true,
  15352. configurable: true
  15353. });
  15354. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15355. /**
  15356. * Set the alpha test sort comparison function.
  15357. * If null the sub meshes will be render in the order they were created
  15358. */
  15359. set: function (value) {
  15360. this._alphaTestSortCompareFn = value;
  15361. if (value) {
  15362. this._renderAlphaTest = this.renderAlphaTestSorted;
  15363. }
  15364. else {
  15365. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15366. }
  15367. },
  15368. enumerable: true,
  15369. configurable: true
  15370. });
  15371. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15372. /**
  15373. * Set the transparent sort comparison function.
  15374. * If null the sub meshes will be render in the order they were created
  15375. */
  15376. set: function (value) {
  15377. if (value) {
  15378. this._transparentSortCompareFn = value;
  15379. }
  15380. else {
  15381. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15382. }
  15383. this._renderTransparent = this.renderTransparentSorted;
  15384. },
  15385. enumerable: true,
  15386. configurable: true
  15387. });
  15388. /**
  15389. * Render all the sub meshes contained in the group.
  15390. * @param customRenderFunction Used to override the default render behaviour of the group.
  15391. * @returns true if rendered some submeshes.
  15392. */
  15393. RenderingGroup.prototype.render = function (customRenderFunction) {
  15394. if (customRenderFunction) {
  15395. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15396. return true;
  15397. }
  15398. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15399. if (this.onBeforeTransparentRendering) {
  15400. this.onBeforeTransparentRendering();
  15401. }
  15402. return false;
  15403. }
  15404. var engine = this._scene.getEngine();
  15405. // Opaque
  15406. this._renderOpaque(this._opaqueSubMeshes);
  15407. // Alpha test
  15408. engine.setAlphaTesting(true);
  15409. this._renderAlphaTest(this._alphaTestSubMeshes);
  15410. engine.setAlphaTesting(false);
  15411. if (this.onBeforeTransparentRendering) {
  15412. this.onBeforeTransparentRendering();
  15413. }
  15414. // Transparent
  15415. this._renderTransparent(this._transparentSubMeshes);
  15416. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15417. return true;
  15418. };
  15419. /**
  15420. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15421. * @param subMeshes The submeshes to render
  15422. */
  15423. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15424. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15425. };
  15426. /**
  15427. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15428. * @param subMeshes The submeshes to render
  15429. */
  15430. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15431. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15432. };
  15433. /**
  15434. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15435. * @param subMeshes The submeshes to render
  15436. */
  15437. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15438. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15439. };
  15440. /**
  15441. * Renders the submeshes in a specified order.
  15442. * @param subMeshes The submeshes to sort before render
  15443. * @param sortCompareFn The comparison function use to sort
  15444. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15445. * @param transparent Specifies to activate blending if true
  15446. */
  15447. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15448. var subIndex = 0;
  15449. var subMesh;
  15450. for (; subIndex < subMeshes.length; subIndex++) {
  15451. subMesh = subMeshes.data[subIndex];
  15452. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15453. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15454. }
  15455. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15456. sortedArray.sort(sortCompareFn);
  15457. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15458. subMesh = sortedArray[subIndex];
  15459. subMesh.render(transparent);
  15460. }
  15461. };
  15462. /**
  15463. * Renders the submeshes in the order they were dispatched (no sort applied).
  15464. * @param subMeshes The submeshes to render
  15465. */
  15466. RenderingGroup.renderUnsorted = function (subMeshes) {
  15467. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15468. var submesh = subMeshes.data[subIndex];
  15469. submesh.render(false);
  15470. }
  15471. };
  15472. /**
  15473. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15474. * are rendered back to front if in the same alpha index.
  15475. *
  15476. * @param a The first submesh
  15477. * @param b The second submesh
  15478. * @returns The result of the comparison
  15479. */
  15480. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15481. // Alpha index first
  15482. if (a._alphaIndex > b._alphaIndex) {
  15483. return 1;
  15484. }
  15485. if (a._alphaIndex < b._alphaIndex) {
  15486. return -1;
  15487. }
  15488. // Then distance to camera
  15489. return RenderingGroup.backToFrontSortCompare(a, b);
  15490. };
  15491. /**
  15492. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15493. * are rendered back to front.
  15494. *
  15495. * @param a The first submesh
  15496. * @param b The second submesh
  15497. * @returns The result of the comparison
  15498. */
  15499. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15500. // Then distance to camera
  15501. if (a._distanceToCamera < b._distanceToCamera) {
  15502. return 1;
  15503. }
  15504. if (a._distanceToCamera > b._distanceToCamera) {
  15505. return -1;
  15506. }
  15507. return 0;
  15508. };
  15509. /**
  15510. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15511. * are rendered front to back (prevent overdraw).
  15512. *
  15513. * @param a The first submesh
  15514. * @param b The second submesh
  15515. * @returns The result of the comparison
  15516. */
  15517. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15518. // Then distance to camera
  15519. if (a._distanceToCamera < b._distanceToCamera) {
  15520. return -1;
  15521. }
  15522. if (a._distanceToCamera > b._distanceToCamera) {
  15523. return 1;
  15524. }
  15525. return 0;
  15526. };
  15527. /**
  15528. * Resets the different lists of submeshes to prepare a new frame.
  15529. */
  15530. RenderingGroup.prototype.prepare = function () {
  15531. this._opaqueSubMeshes.reset();
  15532. this._transparentSubMeshes.reset();
  15533. this._alphaTestSubMeshes.reset();
  15534. };
  15535. /**
  15536. * Inserts the submesh in its correct queue depending on its material.
  15537. * @param subMesh The submesh to dispatch
  15538. */
  15539. RenderingGroup.prototype.dispatch = function (subMesh) {
  15540. var material = subMesh.getMaterial();
  15541. var mesh = subMesh.getMesh();
  15542. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15543. this._transparentSubMeshes.push(subMesh);
  15544. }
  15545. else if (material.needAlphaTesting()) {
  15546. this._alphaTestSubMeshes.push(subMesh);
  15547. }
  15548. else {
  15549. this._opaqueSubMeshes.push(subMesh); // Opaque
  15550. }
  15551. };
  15552. return RenderingGroup;
  15553. })();
  15554. BABYLON.RenderingGroup = RenderingGroup;
  15555. })(BABYLON || (BABYLON = {}));
  15556. var BABYLON;
  15557. (function (BABYLON) {
  15558. var PointerEventTypes = (function () {
  15559. function PointerEventTypes() {
  15560. }
  15561. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15562. get: function () {
  15563. return PointerEventTypes._POINTERDOWN;
  15564. },
  15565. enumerable: true,
  15566. configurable: true
  15567. });
  15568. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15569. get: function () {
  15570. return PointerEventTypes._POINTERUP;
  15571. },
  15572. enumerable: true,
  15573. configurable: true
  15574. });
  15575. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15576. get: function () {
  15577. return PointerEventTypes._POINTERMOVE;
  15578. },
  15579. enumerable: true,
  15580. configurable: true
  15581. });
  15582. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15583. get: function () {
  15584. return PointerEventTypes._POINTERWHEEL;
  15585. },
  15586. enumerable: true,
  15587. configurable: true
  15588. });
  15589. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15590. get: function () {
  15591. return PointerEventTypes._POINTERPICK;
  15592. },
  15593. enumerable: true,
  15594. configurable: true
  15595. });
  15596. PointerEventTypes._POINTERDOWN = 0x01;
  15597. PointerEventTypes._POINTERUP = 0x02;
  15598. PointerEventTypes._POINTERMOVE = 0x04;
  15599. PointerEventTypes._POINTERWHEEL = 0x08;
  15600. PointerEventTypes._POINTERPICK = 0x10;
  15601. return PointerEventTypes;
  15602. })();
  15603. BABYLON.PointerEventTypes = PointerEventTypes;
  15604. var PointerInfoBase = (function () {
  15605. function PointerInfoBase(type, event) {
  15606. this.type = type;
  15607. this.event = event;
  15608. }
  15609. return PointerInfoBase;
  15610. })();
  15611. BABYLON.PointerInfoBase = PointerInfoBase;
  15612. /**
  15613. * This class is used to store pointer related info for the onPrePointerObservable event.
  15614. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15615. */
  15616. var PointerInfoPre = (function (_super) {
  15617. __extends(PointerInfoPre, _super);
  15618. function PointerInfoPre(type, event, localX, localY) {
  15619. _super.call(this, type, event);
  15620. this.skipOnPointerObservable = false;
  15621. this.localPosition = new BABYLON.Vector2(localX, localY);
  15622. }
  15623. return PointerInfoPre;
  15624. })(PointerInfoBase);
  15625. BABYLON.PointerInfoPre = PointerInfoPre;
  15626. /**
  15627. * This type contains all the data related to a pointer event in Babylon.js.
  15628. * 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.
  15629. */
  15630. var PointerInfo = (function (_super) {
  15631. __extends(PointerInfo, _super);
  15632. function PointerInfo(type, event, pickInfo) {
  15633. _super.call(this, type, event);
  15634. this.pickInfo = pickInfo;
  15635. }
  15636. return PointerInfo;
  15637. })(PointerInfoBase);
  15638. BABYLON.PointerInfo = PointerInfo;
  15639. /**
  15640. * Represents a scene to be rendered by the engine.
  15641. * @see http://doc.babylonjs.com/page.php?p=21911
  15642. */
  15643. var Scene = (function () {
  15644. /**
  15645. * @constructor
  15646. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15647. */
  15648. function Scene(engine) {
  15649. // Members
  15650. this.autoClear = true;
  15651. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15652. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15653. this.forceWireframe = false;
  15654. this.forcePointsCloud = false;
  15655. this.forceShowBoundingBoxes = false;
  15656. this.animationsEnabled = true;
  15657. this.constantlyUpdateMeshUnderPointer = false;
  15658. this.hoverCursor = "pointer";
  15659. // Events
  15660. /**
  15661. * An event triggered when the scene is disposed.
  15662. * @type {BABYLON.Observable}
  15663. */
  15664. this.onDisposeObservable = new BABYLON.Observable();
  15665. /**
  15666. * An event triggered before rendering the scene
  15667. * @type {BABYLON.Observable}
  15668. */
  15669. this.onBeforeRenderObservable = new BABYLON.Observable();
  15670. /**
  15671. * An event triggered after rendering the scene
  15672. * @type {BABYLON.Observable}
  15673. */
  15674. this.onAfterRenderObservable = new BABYLON.Observable();
  15675. /**
  15676. * An event triggered when the scene is ready
  15677. * @type {BABYLON.Observable}
  15678. */
  15679. this.onReadyObservable = new BABYLON.Observable();
  15680. /**
  15681. * An event triggered before rendering a camera
  15682. * @type {BABYLON.Observable}
  15683. */
  15684. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15685. /**
  15686. * An event triggered after rendering a camera
  15687. * @type {BABYLON.Observable}
  15688. */
  15689. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15690. /**
  15691. * An event triggered when a camera is created
  15692. * @type {BABYLON.Observable}
  15693. */
  15694. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15695. /**
  15696. * An event triggered when a camera is removed
  15697. * @type {BABYLON.Observable}
  15698. */
  15699. this.onCameraRemovedObservable = new BABYLON.Observable();
  15700. /**
  15701. * An event triggered when a light is created
  15702. * @type {BABYLON.Observable}
  15703. */
  15704. this.onNewLightAddedObservable = new BABYLON.Observable();
  15705. /**
  15706. * An event triggered when a light is removed
  15707. * @type {BABYLON.Observable}
  15708. */
  15709. this.onLightRemovedObservable = new BABYLON.Observable();
  15710. /**
  15711. * An event triggered when a geometry is created
  15712. * @type {BABYLON.Observable}
  15713. */
  15714. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15715. /**
  15716. * An event triggered when a geometry is removed
  15717. * @type {BABYLON.Observable}
  15718. */
  15719. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15720. /**
  15721. * An event triggered when a mesh is created
  15722. * @type {BABYLON.Observable}
  15723. */
  15724. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15725. /**
  15726. * An event triggered when a mesh is removed
  15727. * @type {BABYLON.Observable}
  15728. */
  15729. this.onMeshRemovedObservable = new BABYLON.Observable();
  15730. // Animations
  15731. this.animations = [];
  15732. /**
  15733. * 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).
  15734. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15735. */
  15736. this.onPrePointerObservable = new BABYLON.Observable();
  15737. /**
  15738. * Observable event triggered each time an input event is received from the rendering canvas
  15739. */
  15740. this.onPointerObservable = new BABYLON.Observable();
  15741. 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
  15742. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15743. this._startingPointerTime = 0;
  15744. // Fog
  15745. /**
  15746. * is fog enabled on this scene.
  15747. * @type {boolean}
  15748. */
  15749. this.fogEnabled = true;
  15750. this.fogMode = Scene.FOGMODE_NONE;
  15751. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15752. this.fogDensity = 0.1;
  15753. this.fogStart = 0;
  15754. this.fogEnd = 1000.0;
  15755. // Lights
  15756. /**
  15757. * is shadow enabled on this scene.
  15758. * @type {boolean}
  15759. */
  15760. this.shadowsEnabled = true;
  15761. /**
  15762. * is light enabled on this scene.
  15763. * @type {boolean}
  15764. */
  15765. this.lightsEnabled = true;
  15766. /**
  15767. * All of the lights added to this scene.
  15768. * @see BABYLON.Light
  15769. * @type {BABYLON.Light[]}
  15770. */
  15771. this.lights = new Array();
  15772. // Cameras
  15773. /**
  15774. * All of the cameras added to this scene.
  15775. * @see BABYLON.Camera
  15776. * @type {BABYLON.Camera[]}
  15777. */
  15778. this.cameras = new Array();
  15779. this.activeCameras = new Array();
  15780. // Meshes
  15781. /**
  15782. * All of the (abstract) meshes added to this scene.
  15783. * @see BABYLON.AbstractMesh
  15784. * @type {BABYLON.AbstractMesh[]}
  15785. */
  15786. this.meshes = new Array();
  15787. // Geometries
  15788. this._geometries = new Array();
  15789. this.materials = new Array();
  15790. this.multiMaterials = new Array();
  15791. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15792. // Textures
  15793. this.texturesEnabled = true;
  15794. this.textures = new Array();
  15795. // Particles
  15796. this.particlesEnabled = true;
  15797. this.particleSystems = new Array();
  15798. // Sprites
  15799. this.spritesEnabled = true;
  15800. this.spriteManagers = new Array();
  15801. // Layers
  15802. this.layers = new Array();
  15803. // Skeletons
  15804. this.skeletonsEnabled = true;
  15805. this.skeletons = new Array();
  15806. // Lens flares
  15807. this.lensFlaresEnabled = true;
  15808. this.lensFlareSystems = new Array();
  15809. // Collisions
  15810. this.collisionsEnabled = true;
  15811. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15812. // Postprocesses
  15813. this.postProcessesEnabled = true;
  15814. // Customs render targets
  15815. this.renderTargetsEnabled = true;
  15816. this.dumpNextRenderTargets = false;
  15817. this.customRenderTargets = new Array();
  15818. // Imported meshes
  15819. this.importedMeshesFiles = new Array();
  15820. // Probes
  15821. this.probesEnabled = true;
  15822. this.reflectionProbes = new Array();
  15823. this._actionManagers = new Array();
  15824. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15825. // Procedural textures
  15826. this.proceduralTexturesEnabled = true;
  15827. this._proceduralTextures = new Array();
  15828. this.soundTracks = new Array();
  15829. this._audioEnabled = true;
  15830. this._headphone = false;
  15831. // Performance counters
  15832. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15833. this._totalLightsCounter = new BABYLON.PerfCounter();
  15834. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15835. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15836. this._totalVertices = new BABYLON.PerfCounter();
  15837. this._activeIndices = new BABYLON.PerfCounter();
  15838. this._activeParticles = new BABYLON.PerfCounter();
  15839. this._lastFrameDuration = new BABYLON.PerfCounter();
  15840. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15841. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15842. this._particlesDuration = new BABYLON.PerfCounter();
  15843. this._renderDuration = new BABYLON.PerfCounter();
  15844. this._spritesDuration = new BABYLON.PerfCounter();
  15845. this._activeBones = new BABYLON.PerfCounter();
  15846. this._renderId = 0;
  15847. this._executeWhenReadyTimeoutId = -1;
  15848. this._intermediateRendering = false;
  15849. this._toBeDisposed = new BABYLON.SmartArray(256);
  15850. this._pendingData = []; //ANY
  15851. this._activeMeshes = new BABYLON.SmartArray(256);
  15852. this._processedMaterials = new BABYLON.SmartArray(256);
  15853. this._renderTargets = new BABYLON.SmartArray(256);
  15854. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15855. this._activeSkeletons = new BABYLON.SmartArray(32);
  15856. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15857. this._activeAnimatables = new Array();
  15858. this._transformMatrix = BABYLON.Matrix.Zero();
  15859. this._edgesRenderers = new BABYLON.SmartArray(16);
  15860. this._uniqueIdCounter = 0;
  15861. this._engine = engine;
  15862. engine.scenes.push(this);
  15863. this._renderingManager = new BABYLON.RenderingManager(this);
  15864. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15865. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15866. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15867. if (BABYLON.OutlineRenderer) {
  15868. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15869. }
  15870. this.attachControl();
  15871. if (BABYLON.SoundTrack) {
  15872. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15873. }
  15874. //simplification queue
  15875. if (BABYLON.SimplificationQueue) {
  15876. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15877. }
  15878. //collision coordinator initialization. For now legacy per default.
  15879. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15880. }
  15881. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15882. get: function () {
  15883. return Scene._FOGMODE_NONE;
  15884. },
  15885. enumerable: true,
  15886. configurable: true
  15887. });
  15888. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15889. get: function () {
  15890. return Scene._FOGMODE_EXP;
  15891. },
  15892. enumerable: true,
  15893. configurable: true
  15894. });
  15895. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15896. get: function () {
  15897. return Scene._FOGMODE_EXP2;
  15898. },
  15899. enumerable: true,
  15900. configurable: true
  15901. });
  15902. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15903. get: function () {
  15904. return Scene._FOGMODE_LINEAR;
  15905. },
  15906. enumerable: true,
  15907. configurable: true
  15908. });
  15909. Object.defineProperty(Scene.prototype, "onDispose", {
  15910. set: function (callback) {
  15911. if (this._onDisposeObserver) {
  15912. this.onDisposeObservable.remove(this._onDisposeObserver);
  15913. }
  15914. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15915. },
  15916. enumerable: true,
  15917. configurable: true
  15918. });
  15919. Object.defineProperty(Scene.prototype, "beforeRender", {
  15920. set: function (callback) {
  15921. if (this._onBeforeRenderObserver) {
  15922. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15923. }
  15924. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15925. },
  15926. enumerable: true,
  15927. configurable: true
  15928. });
  15929. Object.defineProperty(Scene.prototype, "afterRender", {
  15930. set: function (callback) {
  15931. if (this._onAfterRenderObserver) {
  15932. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15933. }
  15934. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15935. },
  15936. enumerable: true,
  15937. configurable: true
  15938. });
  15939. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15940. set: function (callback) {
  15941. if (this._onBeforeCameraRenderObserver) {
  15942. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15943. }
  15944. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15945. },
  15946. enumerable: true,
  15947. configurable: true
  15948. });
  15949. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15950. set: function (callback) {
  15951. if (this._onAfterCameraRenderObserver) {
  15952. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15953. }
  15954. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15955. },
  15956. enumerable: true,
  15957. configurable: true
  15958. });
  15959. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15960. get: function () {
  15961. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15962. },
  15963. enumerable: true,
  15964. configurable: true
  15965. });
  15966. Object.defineProperty(Scene.prototype, "debugLayer", {
  15967. // Properties
  15968. get: function () {
  15969. if (!this._debugLayer) {
  15970. this._debugLayer = new BABYLON.DebugLayer(this);
  15971. }
  15972. return this._debugLayer;
  15973. },
  15974. enumerable: true,
  15975. configurable: true
  15976. });
  15977. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15978. get: function () {
  15979. return this._workerCollisions;
  15980. },
  15981. set: function (enabled) {
  15982. enabled = (enabled && !!Worker);
  15983. this._workerCollisions = enabled;
  15984. if (this.collisionCoordinator) {
  15985. this.collisionCoordinator.destroy();
  15986. }
  15987. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15988. this.collisionCoordinator.init(this);
  15989. },
  15990. enumerable: true,
  15991. configurable: true
  15992. });
  15993. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  15994. get: function () {
  15995. return this._selectionOctree;
  15996. },
  15997. enumerable: true,
  15998. configurable: true
  15999. });
  16000. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16001. /**
  16002. * The mesh that is currently under the pointer.
  16003. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16004. */
  16005. get: function () {
  16006. return this._pointerOverMesh;
  16007. },
  16008. enumerable: true,
  16009. configurable: true
  16010. });
  16011. Object.defineProperty(Scene.prototype, "pointerX", {
  16012. /**
  16013. * Current on-screen X position of the pointer
  16014. * @return {number} X position of the pointer
  16015. */
  16016. get: function () {
  16017. return this._pointerX;
  16018. },
  16019. enumerable: true,
  16020. configurable: true
  16021. });
  16022. Object.defineProperty(Scene.prototype, "pointerY", {
  16023. /**
  16024. * Current on-screen Y position of the pointer
  16025. * @return {number} Y position of the pointer
  16026. */
  16027. get: function () {
  16028. return this._pointerY;
  16029. },
  16030. enumerable: true,
  16031. configurable: true
  16032. });
  16033. Scene.prototype.getCachedMaterial = function () {
  16034. return this._cachedMaterial;
  16035. };
  16036. Scene.prototype.getBoundingBoxRenderer = function () {
  16037. return this._boundingBoxRenderer;
  16038. };
  16039. Scene.prototype.getOutlineRenderer = function () {
  16040. return this._outlineRenderer;
  16041. };
  16042. Scene.prototype.getEngine = function () {
  16043. return this._engine;
  16044. };
  16045. Scene.prototype.getTotalVertices = function () {
  16046. return this._totalVertices.current;
  16047. };
  16048. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16049. get: function () {
  16050. return this._totalVertices;
  16051. },
  16052. enumerable: true,
  16053. configurable: true
  16054. });
  16055. Scene.prototype.getActiveIndices = function () {
  16056. return this._activeIndices.current;
  16057. };
  16058. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16059. get: function () {
  16060. return this._activeIndices;
  16061. },
  16062. enumerable: true,
  16063. configurable: true
  16064. });
  16065. Scene.prototype.getActiveParticles = function () {
  16066. return this._activeParticles.current;
  16067. };
  16068. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16069. get: function () {
  16070. return this._activeParticles;
  16071. },
  16072. enumerable: true,
  16073. configurable: true
  16074. });
  16075. Scene.prototype.getActiveBones = function () {
  16076. return this._activeBones.current;
  16077. };
  16078. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16079. get: function () {
  16080. return this._activeBones;
  16081. },
  16082. enumerable: true,
  16083. configurable: true
  16084. });
  16085. // Stats
  16086. Scene.prototype.getLastFrameDuration = function () {
  16087. return this._lastFrameDuration.current;
  16088. };
  16089. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16090. get: function () {
  16091. return this._lastFrameDuration;
  16092. },
  16093. enumerable: true,
  16094. configurable: true
  16095. });
  16096. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16097. return this._evaluateActiveMeshesDuration.current;
  16098. };
  16099. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16100. get: function () {
  16101. return this._evaluateActiveMeshesDuration;
  16102. },
  16103. enumerable: true,
  16104. configurable: true
  16105. });
  16106. Scene.prototype.getActiveMeshes = function () {
  16107. return this._activeMeshes;
  16108. };
  16109. Scene.prototype.getRenderTargetsDuration = function () {
  16110. return this._renderTargetsDuration.current;
  16111. };
  16112. Scene.prototype.getRenderDuration = function () {
  16113. return this._renderDuration.current;
  16114. };
  16115. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16116. get: function () {
  16117. return this._renderDuration;
  16118. },
  16119. enumerable: true,
  16120. configurable: true
  16121. });
  16122. Scene.prototype.getParticlesDuration = function () {
  16123. return this._particlesDuration.current;
  16124. };
  16125. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16126. get: function () {
  16127. return this._particlesDuration;
  16128. },
  16129. enumerable: true,
  16130. configurable: true
  16131. });
  16132. Scene.prototype.getSpritesDuration = function () {
  16133. return this._spritesDuration.current;
  16134. };
  16135. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16136. get: function () {
  16137. return this._spritesDuration;
  16138. },
  16139. enumerable: true,
  16140. configurable: true
  16141. });
  16142. Scene.prototype.getAnimationRatio = function () {
  16143. return this._animationRatio;
  16144. };
  16145. Scene.prototype.getRenderId = function () {
  16146. return this._renderId;
  16147. };
  16148. Scene.prototype.incrementRenderId = function () {
  16149. this._renderId++;
  16150. };
  16151. Scene.prototype._updatePointerPosition = function (evt) {
  16152. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16153. this._pointerX = evt.clientX - canvasRect.left;
  16154. this._pointerY = evt.clientY - canvasRect.top;
  16155. this._unTranslatedPointerX = this._pointerX;
  16156. this._unTranslatedPointerY = this._pointerY;
  16157. if (this.cameraToUseForPointers) {
  16158. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16159. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16160. }
  16161. };
  16162. // Pointers handling
  16163. /**
  16164. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16165. * @param attachUp defines if you want to attach events to pointerup
  16166. * @param attachDown defines if you want to attach events to pointerdown
  16167. * @param attachMove defines if you want to attach events to pointermove
  16168. */
  16169. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16170. var _this = this;
  16171. if (attachUp === void 0) { attachUp = true; }
  16172. if (attachDown === void 0) { attachDown = true; }
  16173. if (attachMove === void 0) { attachMove = true; }
  16174. var spritePredicate = function (sprite) {
  16175. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16176. };
  16177. this._onPointerMove = function (evt) {
  16178. _this._updatePointerPosition(evt);
  16179. // PreObservable support
  16180. if (_this.onPrePointerObservable.hasObservers()) {
  16181. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16182. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16183. _this.onPrePointerObservable.notifyObservers(pi, type);
  16184. if (pi.skipOnPointerObservable) {
  16185. return;
  16186. }
  16187. }
  16188. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16189. return;
  16190. }
  16191. var canvas = _this._engine.getRenderingCanvas();
  16192. if (!_this.pointerMovePredicate) {
  16193. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16194. }
  16195. // Meshes
  16196. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16197. if (pickResult.hit && pickResult.pickedMesh) {
  16198. _this.setPointerOverSprite(null);
  16199. _this.setPointerOverMesh(pickResult.pickedMesh);
  16200. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16201. canvas.style.cursor = _this.hoverCursor;
  16202. }
  16203. else {
  16204. canvas.style.cursor = "";
  16205. }
  16206. }
  16207. else {
  16208. _this.setPointerOverMesh(null);
  16209. // Sprites
  16210. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16211. if (pickResult.hit && pickResult.pickedSprite) {
  16212. canvas.style.cursor = _this.hoverCursor;
  16213. _this.setPointerOverSprite(pickResult.pickedSprite);
  16214. }
  16215. else {
  16216. _this.setPointerOverSprite(null);
  16217. // Restore pointer
  16218. canvas.style.cursor = "";
  16219. }
  16220. }
  16221. if (_this.onPointerMove) {
  16222. _this.onPointerMove(evt, pickResult);
  16223. }
  16224. if (_this.onPointerObservable.hasObservers()) {
  16225. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16226. var pi = new PointerInfo(type, evt, pickResult);
  16227. _this.onPointerObservable.notifyObservers(pi, type);
  16228. }
  16229. };
  16230. this._onPointerDown = function (evt) {
  16231. _this._updatePointerPosition(evt);
  16232. // PreObservable support
  16233. if (_this.onPrePointerObservable.hasObservers()) {
  16234. var type = PointerEventTypes.POINTERDOWN;
  16235. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16236. _this.onPrePointerObservable.notifyObservers(pi, type);
  16237. if (pi.skipOnPointerObservable) {
  16238. return;
  16239. }
  16240. }
  16241. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16242. return;
  16243. }
  16244. _this._startingPointerPosition.x = _this._pointerX;
  16245. _this._startingPointerPosition.y = _this._pointerY;
  16246. _this._startingPointerTime = new Date().getTime();
  16247. if (!_this.pointerDownPredicate) {
  16248. _this.pointerDownPredicate = function (mesh) {
  16249. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16250. };
  16251. }
  16252. // Meshes
  16253. _this._pickedDownMesh = null;
  16254. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16255. if (pickResult.hit && pickResult.pickedMesh) {
  16256. if (pickResult.pickedMesh.actionManager) {
  16257. _this._pickedDownMesh = pickResult.pickedMesh;
  16258. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16259. switch (evt.button) {
  16260. case 0:
  16261. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16262. break;
  16263. case 1:
  16264. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16265. break;
  16266. case 2:
  16267. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16268. break;
  16269. }
  16270. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16271. }
  16272. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16273. var that = _this;
  16274. window.setTimeout(function () {
  16275. 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);
  16276. if (pickResult.hit && pickResult.pickedMesh) {
  16277. if (pickResult.pickedMesh.actionManager) {
  16278. 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)) {
  16279. that._startingPointerTime = 0;
  16280. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16281. }
  16282. }
  16283. }
  16284. }, BABYLON.ActionManager.LongPressDelay);
  16285. }
  16286. }
  16287. }
  16288. if (_this.onPointerDown) {
  16289. _this.onPointerDown(evt, pickResult);
  16290. }
  16291. if (_this.onPointerObservable.hasObservers()) {
  16292. var type = PointerEventTypes.POINTERDOWN;
  16293. var pi = new PointerInfo(type, evt, pickResult);
  16294. _this.onPointerObservable.notifyObservers(pi, type);
  16295. }
  16296. // Sprites
  16297. _this._pickedDownSprite = null;
  16298. if (_this.spriteManagers.length > 0) {
  16299. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16300. if (pickResult.hit && pickResult.pickedSprite) {
  16301. if (pickResult.pickedSprite.actionManager) {
  16302. _this._pickedDownSprite = pickResult.pickedSprite;
  16303. switch (evt.button) {
  16304. case 0:
  16305. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16306. break;
  16307. case 1:
  16308. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16309. break;
  16310. case 2:
  16311. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16312. break;
  16313. }
  16314. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16315. }
  16316. }
  16317. }
  16318. };
  16319. this._onPointerUp = function (evt) {
  16320. _this._updatePointerPosition(evt);
  16321. // PreObservable support
  16322. if (_this.onPrePointerObservable.hasObservers()) {
  16323. var type = PointerEventTypes.POINTERUP;
  16324. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16325. _this.onPrePointerObservable.notifyObservers(pi, type);
  16326. if (pi.skipOnPointerObservable) {
  16327. return;
  16328. }
  16329. }
  16330. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16331. return;
  16332. }
  16333. if (!_this.pointerUpPredicate) {
  16334. _this.pointerUpPredicate = function (mesh) {
  16335. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16336. };
  16337. }
  16338. // Meshes
  16339. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16340. if (pickResult.hit && pickResult.pickedMesh) {
  16341. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16342. if (_this.onPointerPick) {
  16343. _this.onPointerPick(evt, pickResult);
  16344. }
  16345. if (_this.onPointerObservable.hasObservers()) {
  16346. var type = PointerEventTypes.POINTERPICK;
  16347. var pi = new PointerInfo(type, evt, pickResult);
  16348. _this.onPointerObservable.notifyObservers(pi, type);
  16349. }
  16350. }
  16351. if (pickResult.pickedMesh.actionManager) {
  16352. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16353. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16354. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16355. }
  16356. }
  16357. }
  16358. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16359. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16360. }
  16361. if (_this.onPointerUp) {
  16362. _this.onPointerUp(evt, pickResult);
  16363. }
  16364. if (_this.onPointerObservable.hasObservers()) {
  16365. var type = PointerEventTypes.POINTERUP;
  16366. var pi = new PointerInfo(type, evt, pickResult);
  16367. _this.onPointerObservable.notifyObservers(pi, type);
  16368. }
  16369. _this._startingPointerTime = 0;
  16370. // Sprites
  16371. if (_this.spriteManagers.length > 0) {
  16372. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16373. if (pickResult.hit && pickResult.pickedSprite) {
  16374. if (pickResult.pickedSprite.actionManager) {
  16375. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16376. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16377. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16378. }
  16379. }
  16380. }
  16381. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  16382. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  16383. }
  16384. }
  16385. };
  16386. this._onKeyDown = function (evt) {
  16387. if (_this.actionManager) {
  16388. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16389. }
  16390. };
  16391. this._onKeyUp = function (evt) {
  16392. if (_this.actionManager) {
  16393. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16394. }
  16395. };
  16396. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16397. var canvas = this._engine.getRenderingCanvas();
  16398. if (attachMove) {
  16399. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16400. // Wheel
  16401. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16402. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16403. }
  16404. if (attachDown) {
  16405. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16406. }
  16407. if (attachUp) {
  16408. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16409. }
  16410. canvas.tabIndex = 1;
  16411. canvas.addEventListener("keydown", this._onKeyDown, false);
  16412. canvas.addEventListener("keyup", this._onKeyUp, false);
  16413. };
  16414. Scene.prototype.detachControl = function () {
  16415. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16416. var canvas = this._engine.getRenderingCanvas();
  16417. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16418. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16419. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16420. // Wheel
  16421. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16422. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16423. canvas.removeEventListener("keydown", this._onKeyDown);
  16424. canvas.removeEventListener("keyup", this._onKeyUp);
  16425. };
  16426. // Ready
  16427. Scene.prototype.isReady = function () {
  16428. if (this._pendingData.length > 0) {
  16429. return false;
  16430. }
  16431. var index;
  16432. for (index = 0; index < this._geometries.length; index++) {
  16433. var geometry = this._geometries[index];
  16434. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16435. return false;
  16436. }
  16437. }
  16438. for (index = 0; index < this.meshes.length; index++) {
  16439. var mesh = this.meshes[index];
  16440. if (!mesh.isReady()) {
  16441. return false;
  16442. }
  16443. var mat = mesh.material;
  16444. if (mat) {
  16445. if (!mat.isReady(mesh)) {
  16446. return false;
  16447. }
  16448. }
  16449. }
  16450. return true;
  16451. };
  16452. Scene.prototype.resetCachedMaterial = function () {
  16453. this._cachedMaterial = null;
  16454. };
  16455. Scene.prototype.registerBeforeRender = function (func) {
  16456. this.onBeforeRenderObservable.add(func);
  16457. };
  16458. Scene.prototype.unregisterBeforeRender = function (func) {
  16459. this.onBeforeRenderObservable.removeCallback(func);
  16460. };
  16461. Scene.prototype.registerAfterRender = function (func) {
  16462. this.onAfterRenderObservable.add(func);
  16463. };
  16464. Scene.prototype.unregisterAfterRender = function (func) {
  16465. this.onAfterRenderObservable.removeCallback(func);
  16466. };
  16467. Scene.prototype._addPendingData = function (data) {
  16468. this._pendingData.push(data);
  16469. };
  16470. Scene.prototype._removePendingData = function (data) {
  16471. var index = this._pendingData.indexOf(data);
  16472. if (index !== -1) {
  16473. this._pendingData.splice(index, 1);
  16474. }
  16475. };
  16476. Scene.prototype.getWaitingItemsCount = function () {
  16477. return this._pendingData.length;
  16478. };
  16479. /**
  16480. * Registers a function to be executed when the scene is ready.
  16481. * @param {Function} func - the function to be executed.
  16482. */
  16483. Scene.prototype.executeWhenReady = function (func) {
  16484. var _this = this;
  16485. this.onReadyObservable.add(func);
  16486. if (this._executeWhenReadyTimeoutId !== -1) {
  16487. return;
  16488. }
  16489. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16490. _this._checkIsReady();
  16491. }, 150);
  16492. };
  16493. Scene.prototype._checkIsReady = function () {
  16494. var _this = this;
  16495. if (this.isReady()) {
  16496. this.onReadyObservable.notifyObservers(this);
  16497. this.onReadyObservable.clear();
  16498. this._executeWhenReadyTimeoutId = -1;
  16499. return;
  16500. }
  16501. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16502. _this._checkIsReady();
  16503. }, 150);
  16504. };
  16505. // Animations
  16506. /**
  16507. * Will start the animation sequence of a given target
  16508. * @param target - the target
  16509. * @param {number} from - from which frame should animation start
  16510. * @param {number} to - till which frame should animation run.
  16511. * @param {boolean} [loop] - should the animation loop
  16512. * @param {number} [speedRatio] - the speed in which to run the animation
  16513. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16514. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16515. * @return {BABYLON.Animatable} the animatable object created for this animation
  16516. * @see BABYLON.Animatable
  16517. * @see http://doc.babylonjs.com/page.php?p=22081
  16518. */
  16519. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16520. if (speedRatio === void 0) { speedRatio = 1.0; }
  16521. this.stopAnimation(target);
  16522. if (!animatable) {
  16523. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16524. }
  16525. // Local animations
  16526. if (target.animations) {
  16527. animatable.appendAnimations(target, target.animations);
  16528. }
  16529. // Children animations
  16530. if (target.getAnimatables) {
  16531. var animatables = target.getAnimatables();
  16532. for (var index = 0; index < animatables.length; index++) {
  16533. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16534. }
  16535. }
  16536. animatable.reset();
  16537. return animatable;
  16538. };
  16539. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16540. if (speedRatio === undefined) {
  16541. speedRatio = 1.0;
  16542. }
  16543. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16544. return animatable;
  16545. };
  16546. Scene.prototype.getAnimatableByTarget = function (target) {
  16547. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16548. if (this._activeAnimatables[index].target === target) {
  16549. return this._activeAnimatables[index];
  16550. }
  16551. }
  16552. return null;
  16553. };
  16554. Object.defineProperty(Scene.prototype, "Animatables", {
  16555. get: function () {
  16556. return this._activeAnimatables;
  16557. },
  16558. enumerable: true,
  16559. configurable: true
  16560. });
  16561. /**
  16562. * Will stop the animation of the given target
  16563. * @param target - the target
  16564. * @see beginAnimation
  16565. */
  16566. Scene.prototype.stopAnimation = function (target) {
  16567. var animatable = this.getAnimatableByTarget(target);
  16568. if (animatable) {
  16569. animatable.stop();
  16570. }
  16571. };
  16572. Scene.prototype._animate = function () {
  16573. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16574. return;
  16575. }
  16576. if (!this._animationStartDate) {
  16577. if (this._pendingData.length > 0) {
  16578. return;
  16579. }
  16580. this._animationStartDate = BABYLON.Tools.Now;
  16581. }
  16582. // Getting time
  16583. var now = BABYLON.Tools.Now;
  16584. var delay = now - this._animationStartDate;
  16585. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16586. this._activeAnimatables[index]._animate(delay);
  16587. }
  16588. };
  16589. // Matrix
  16590. Scene.prototype.getViewMatrix = function () {
  16591. return this._viewMatrix;
  16592. };
  16593. Scene.prototype.getProjectionMatrix = function () {
  16594. return this._projectionMatrix;
  16595. };
  16596. Scene.prototype.getTransformMatrix = function () {
  16597. return this._transformMatrix;
  16598. };
  16599. Scene.prototype.setTransformMatrix = function (view, projection) {
  16600. this._viewMatrix = view;
  16601. this._projectionMatrix = projection;
  16602. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16603. // Update frustum
  16604. if (!this._frustumPlanes) {
  16605. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16606. }
  16607. else {
  16608. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16609. }
  16610. };
  16611. // Methods
  16612. Scene.prototype.addMesh = function (newMesh) {
  16613. newMesh.uniqueId = this._uniqueIdCounter++;
  16614. var position = this.meshes.push(newMesh);
  16615. //notify the collision coordinator
  16616. this.collisionCoordinator.onMeshAdded(newMesh);
  16617. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16618. };
  16619. Scene.prototype.removeMesh = function (toRemove) {
  16620. var index = this.meshes.indexOf(toRemove);
  16621. if (index !== -1) {
  16622. // Remove from the scene if mesh found
  16623. this.meshes.splice(index, 1);
  16624. }
  16625. //notify the collision coordinator
  16626. this.collisionCoordinator.onMeshRemoved(toRemove);
  16627. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16628. return index;
  16629. };
  16630. Scene.prototype.removeSkeleton = function (toRemove) {
  16631. var index = this.skeletons.indexOf(toRemove);
  16632. if (index !== -1) {
  16633. // Remove from the scene if mesh found
  16634. this.skeletons.splice(index, 1);
  16635. }
  16636. return index;
  16637. };
  16638. Scene.prototype.removeLight = function (toRemove) {
  16639. var index = this.lights.indexOf(toRemove);
  16640. if (index !== -1) {
  16641. // Remove from the scene if mesh found
  16642. this.lights.splice(index, 1);
  16643. }
  16644. this.onLightRemovedObservable.notifyObservers(toRemove);
  16645. return index;
  16646. };
  16647. Scene.prototype.removeCamera = function (toRemove) {
  16648. var index = this.cameras.indexOf(toRemove);
  16649. if (index !== -1) {
  16650. // Remove from the scene if mesh found
  16651. this.cameras.splice(index, 1);
  16652. }
  16653. // Remove from activeCameras
  16654. var index2 = this.activeCameras.indexOf(toRemove);
  16655. if (index2 !== -1) {
  16656. // Remove from the scene if mesh found
  16657. this.activeCameras.splice(index2, 1);
  16658. }
  16659. // Reset the activeCamera
  16660. if (this.activeCamera === toRemove) {
  16661. if (this.cameras.length > 0) {
  16662. this.activeCamera = this.cameras[0];
  16663. }
  16664. else {
  16665. this.activeCamera = null;
  16666. }
  16667. }
  16668. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16669. return index;
  16670. };
  16671. Scene.prototype.addLight = function (newLight) {
  16672. newLight.uniqueId = this._uniqueIdCounter++;
  16673. var position = this.lights.push(newLight);
  16674. this.onNewLightAddedObservable.notifyObservers(newLight);
  16675. };
  16676. Scene.prototype.addCamera = function (newCamera) {
  16677. newCamera.uniqueId = this._uniqueIdCounter++;
  16678. var position = this.cameras.push(newCamera);
  16679. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16680. };
  16681. /**
  16682. * Switch active camera
  16683. * @param {Camera} newCamera - new active camera
  16684. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16685. */
  16686. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16687. if (attachControl === void 0) { attachControl = true; }
  16688. var canvas = this._engine.getRenderingCanvas();
  16689. this.activeCamera.detachControl(canvas);
  16690. this.activeCamera = newCamera;
  16691. if (attachControl) {
  16692. newCamera.attachControl(canvas);
  16693. }
  16694. };
  16695. /**
  16696. * sets the active camera of the scene using its ID
  16697. * @param {string} id - the camera's ID
  16698. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16699. * @see activeCamera
  16700. */
  16701. Scene.prototype.setActiveCameraByID = function (id) {
  16702. var camera = this.getCameraByID(id);
  16703. if (camera) {
  16704. this.activeCamera = camera;
  16705. return camera;
  16706. }
  16707. return null;
  16708. };
  16709. /**
  16710. * sets the active camera of the scene using its name
  16711. * @param {string} name - the camera's name
  16712. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16713. * @see activeCamera
  16714. */
  16715. Scene.prototype.setActiveCameraByName = function (name) {
  16716. var camera = this.getCameraByName(name);
  16717. if (camera) {
  16718. this.activeCamera = camera;
  16719. return camera;
  16720. }
  16721. return null;
  16722. };
  16723. /**
  16724. * get a material using its id
  16725. * @param {string} the material's ID
  16726. * @return {BABYLON.Material|null} the material or null if none found.
  16727. */
  16728. Scene.prototype.getMaterialByID = function (id) {
  16729. for (var index = 0; index < this.materials.length; index++) {
  16730. if (this.materials[index].id === id) {
  16731. return this.materials[index];
  16732. }
  16733. }
  16734. return null;
  16735. };
  16736. /**
  16737. * get a material using its name
  16738. * @param {string} the material's name
  16739. * @return {BABYLON.Material|null} the material or null if none found.
  16740. */
  16741. Scene.prototype.getMaterialByName = function (name) {
  16742. for (var index = 0; index < this.materials.length; index++) {
  16743. if (this.materials[index].name === name) {
  16744. return this.materials[index];
  16745. }
  16746. }
  16747. return null;
  16748. };
  16749. Scene.prototype.getLensFlareSystemByName = function (name) {
  16750. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16751. if (this.lensFlareSystems[index].name === name) {
  16752. return this.lensFlareSystems[index];
  16753. }
  16754. }
  16755. return null;
  16756. };
  16757. Scene.prototype.getLensFlareSystemByID = function (id) {
  16758. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16759. if (this.lensFlareSystems[index].id === id) {
  16760. return this.lensFlareSystems[index];
  16761. }
  16762. }
  16763. return null;
  16764. };
  16765. Scene.prototype.getCameraByID = function (id) {
  16766. for (var index = 0; index < this.cameras.length; index++) {
  16767. if (this.cameras[index].id === id) {
  16768. return this.cameras[index];
  16769. }
  16770. }
  16771. return null;
  16772. };
  16773. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16774. for (var index = 0; index < this.cameras.length; index++) {
  16775. if (this.cameras[index].uniqueId === uniqueId) {
  16776. return this.cameras[index];
  16777. }
  16778. }
  16779. return null;
  16780. };
  16781. /**
  16782. * get a camera using its name
  16783. * @param {string} the camera's name
  16784. * @return {BABYLON.Camera|null} the camera or null if none found.
  16785. */
  16786. Scene.prototype.getCameraByName = function (name) {
  16787. for (var index = 0; index < this.cameras.length; index++) {
  16788. if (this.cameras[index].name === name) {
  16789. return this.cameras[index];
  16790. }
  16791. }
  16792. return null;
  16793. };
  16794. /**
  16795. * get a bone using its id
  16796. * @param {string} the bone's id
  16797. * @return {BABYLON.Bone|null} the bone or null if not found
  16798. */
  16799. Scene.prototype.getBoneByID = function (id) {
  16800. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16801. var skeleton = this.skeletons[skeletonIndex];
  16802. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16803. if (skeleton.bones[boneIndex].id === id) {
  16804. return skeleton.bones[boneIndex];
  16805. }
  16806. }
  16807. }
  16808. return null;
  16809. };
  16810. /**
  16811. * get a bone using its id
  16812. * @param {string} the bone's name
  16813. * @return {BABYLON.Bone|null} the bone or null if not found
  16814. */
  16815. Scene.prototype.getBoneByName = function (name) {
  16816. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16817. var skeleton = this.skeletons[skeletonIndex];
  16818. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16819. if (skeleton.bones[boneIndex].name === name) {
  16820. return skeleton.bones[boneIndex];
  16821. }
  16822. }
  16823. }
  16824. return null;
  16825. };
  16826. /**
  16827. * get a light node using its name
  16828. * @param {string} the light's name
  16829. * @return {BABYLON.Light|null} the light or null if none found.
  16830. */
  16831. Scene.prototype.getLightByName = function (name) {
  16832. for (var index = 0; index < this.lights.length; index++) {
  16833. if (this.lights[index].name === name) {
  16834. return this.lights[index];
  16835. }
  16836. }
  16837. return null;
  16838. };
  16839. /**
  16840. * get a light node using its ID
  16841. * @param {string} the light's id
  16842. * @return {BABYLON.Light|null} the light or null if none found.
  16843. */
  16844. Scene.prototype.getLightByID = function (id) {
  16845. for (var index = 0; index < this.lights.length; index++) {
  16846. if (this.lights[index].id === id) {
  16847. return this.lights[index];
  16848. }
  16849. }
  16850. return null;
  16851. };
  16852. /**
  16853. * get a light node using its scene-generated unique ID
  16854. * @param {number} the light's unique id
  16855. * @return {BABYLON.Light|null} the light or null if none found.
  16856. */
  16857. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16858. for (var index = 0; index < this.lights.length; index++) {
  16859. if (this.lights[index].uniqueId === uniqueId) {
  16860. return this.lights[index];
  16861. }
  16862. }
  16863. return null;
  16864. };
  16865. /**
  16866. * get a particle system by id
  16867. * @param id {number} the particle system id
  16868. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16869. */
  16870. Scene.prototype.getParticleSystemByID = function (id) {
  16871. for (var index = 0; index < this.particleSystems.length; index++) {
  16872. if (this.particleSystems[index].id === id) {
  16873. return this.particleSystems[index];
  16874. }
  16875. }
  16876. return null;
  16877. };
  16878. /**
  16879. * get a geometry using its ID
  16880. * @param {string} the geometry's id
  16881. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16882. */
  16883. Scene.prototype.getGeometryByID = function (id) {
  16884. for (var index = 0; index < this._geometries.length; index++) {
  16885. if (this._geometries[index].id === id) {
  16886. return this._geometries[index];
  16887. }
  16888. }
  16889. return null;
  16890. };
  16891. /**
  16892. * add a new geometry to this scene.
  16893. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16894. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16895. * @return {boolean} was the geometry added or not
  16896. */
  16897. Scene.prototype.pushGeometry = function (geometry, force) {
  16898. if (!force && this.getGeometryByID(geometry.id)) {
  16899. return false;
  16900. }
  16901. this._geometries.push(geometry);
  16902. //notify the collision coordinator
  16903. this.collisionCoordinator.onGeometryAdded(geometry);
  16904. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16905. return true;
  16906. };
  16907. /**
  16908. * Removes an existing geometry
  16909. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16910. * @return {boolean} was the geometry removed or not
  16911. */
  16912. Scene.prototype.removeGeometry = function (geometry) {
  16913. var index = this._geometries.indexOf(geometry);
  16914. if (index > -1) {
  16915. this._geometries.splice(index, 1);
  16916. //notify the collision coordinator
  16917. this.collisionCoordinator.onGeometryDeleted(geometry);
  16918. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16919. return true;
  16920. }
  16921. return false;
  16922. };
  16923. Scene.prototype.getGeometries = function () {
  16924. return this._geometries;
  16925. };
  16926. /**
  16927. * Get the first added mesh found of a given ID
  16928. * @param {string} id - the id to search for
  16929. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16930. */
  16931. Scene.prototype.getMeshByID = function (id) {
  16932. for (var index = 0; index < this.meshes.length; index++) {
  16933. if (this.meshes[index].id === id) {
  16934. return this.meshes[index];
  16935. }
  16936. }
  16937. return null;
  16938. };
  16939. Scene.prototype.getMeshesByID = function (id) {
  16940. return this.meshes.filter(function (m) {
  16941. return m.id === id;
  16942. });
  16943. };
  16944. /**
  16945. * Get a mesh with its auto-generated unique id
  16946. * @param {number} uniqueId - the unique id to search for
  16947. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16948. */
  16949. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16950. for (var index = 0; index < this.meshes.length; index++) {
  16951. if (this.meshes[index].uniqueId === uniqueId) {
  16952. return this.meshes[index];
  16953. }
  16954. }
  16955. return null;
  16956. };
  16957. /**
  16958. * Get a the last added mesh found of a given ID
  16959. * @param {string} id - the id to search for
  16960. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16961. */
  16962. Scene.prototype.getLastMeshByID = function (id) {
  16963. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16964. if (this.meshes[index].id === id) {
  16965. return this.meshes[index];
  16966. }
  16967. }
  16968. return null;
  16969. };
  16970. /**
  16971. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16972. * @param {string} id - the id to search for
  16973. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16974. */
  16975. Scene.prototype.getLastEntryByID = function (id) {
  16976. var index;
  16977. for (index = this.meshes.length - 1; index >= 0; index--) {
  16978. if (this.meshes[index].id === id) {
  16979. return this.meshes[index];
  16980. }
  16981. }
  16982. for (index = this.cameras.length - 1; index >= 0; index--) {
  16983. if (this.cameras[index].id === id) {
  16984. return this.cameras[index];
  16985. }
  16986. }
  16987. for (index = this.lights.length - 1; index >= 0; index--) {
  16988. if (this.lights[index].id === id) {
  16989. return this.lights[index];
  16990. }
  16991. }
  16992. return null;
  16993. };
  16994. Scene.prototype.getNodeByID = function (id) {
  16995. var mesh = this.getMeshByID(id);
  16996. if (mesh) {
  16997. return mesh;
  16998. }
  16999. var light = this.getLightByID(id);
  17000. if (light) {
  17001. return light;
  17002. }
  17003. var camera = this.getCameraByID(id);
  17004. if (camera) {
  17005. return camera;
  17006. }
  17007. var bone = this.getBoneByID(id);
  17008. return bone;
  17009. };
  17010. Scene.prototype.getNodeByName = function (name) {
  17011. var mesh = this.getMeshByName(name);
  17012. if (mesh) {
  17013. return mesh;
  17014. }
  17015. var light = this.getLightByName(name);
  17016. if (light) {
  17017. return light;
  17018. }
  17019. var camera = this.getCameraByName(name);
  17020. if (camera) {
  17021. return camera;
  17022. }
  17023. var bone = this.getBoneByName(name);
  17024. return bone;
  17025. };
  17026. Scene.prototype.getMeshByName = function (name) {
  17027. for (var index = 0; index < this.meshes.length; index++) {
  17028. if (this.meshes[index].name === name) {
  17029. return this.meshes[index];
  17030. }
  17031. }
  17032. return null;
  17033. };
  17034. Scene.prototype.getSoundByName = function (name) {
  17035. var index;
  17036. if (BABYLON.AudioEngine) {
  17037. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17038. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17039. return this.mainSoundTrack.soundCollection[index];
  17040. }
  17041. }
  17042. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17043. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17044. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17045. return this.soundTracks[sdIndex].soundCollection[index];
  17046. }
  17047. }
  17048. }
  17049. }
  17050. return null;
  17051. };
  17052. Scene.prototype.getLastSkeletonByID = function (id) {
  17053. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17054. if (this.skeletons[index].id === id) {
  17055. return this.skeletons[index];
  17056. }
  17057. }
  17058. return null;
  17059. };
  17060. Scene.prototype.getSkeletonById = function (id) {
  17061. for (var index = 0; index < this.skeletons.length; index++) {
  17062. if (this.skeletons[index].id === id) {
  17063. return this.skeletons[index];
  17064. }
  17065. }
  17066. return null;
  17067. };
  17068. Scene.prototype.getSkeletonByName = function (name) {
  17069. for (var index = 0; index < this.skeletons.length; index++) {
  17070. if (this.skeletons[index].name === name) {
  17071. return this.skeletons[index];
  17072. }
  17073. }
  17074. return null;
  17075. };
  17076. Scene.prototype.isActiveMesh = function (mesh) {
  17077. return (this._activeMeshes.indexOf(mesh) !== -1);
  17078. };
  17079. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17080. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17081. var material = subMesh.getMaterial();
  17082. if (mesh.showSubMeshesBoundingBox) {
  17083. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  17084. }
  17085. if (material) {
  17086. // Render targets
  17087. if (material.getRenderTargetTextures) {
  17088. if (this._processedMaterials.indexOf(material) === -1) {
  17089. this._processedMaterials.push(material);
  17090. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17091. }
  17092. }
  17093. // Dispatch
  17094. this._activeIndices.addCount(subMesh.indexCount, false);
  17095. this._renderingManager.dispatch(subMesh);
  17096. }
  17097. }
  17098. };
  17099. Scene.prototype._isInIntermediateRendering = function () {
  17100. return this._intermediateRendering;
  17101. };
  17102. Scene.prototype._evaluateActiveMeshes = function () {
  17103. this.activeCamera._activeMeshes.reset();
  17104. this._activeMeshes.reset();
  17105. this._renderingManager.reset();
  17106. this._processedMaterials.reset();
  17107. this._activeParticleSystems.reset();
  17108. this._activeSkeletons.reset();
  17109. this._softwareSkinnedMeshes.reset();
  17110. this._boundingBoxRenderer.reset();
  17111. this._edgesRenderers.reset();
  17112. // Meshes
  17113. var meshes;
  17114. var len;
  17115. if (this._selectionOctree) {
  17116. var selection = this._selectionOctree.select(this._frustumPlanes);
  17117. meshes = selection.data;
  17118. len = selection.length;
  17119. }
  17120. else {
  17121. len = this.meshes.length;
  17122. meshes = this.meshes;
  17123. }
  17124. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17125. var mesh = meshes[meshIndex];
  17126. if (mesh.isBlocked) {
  17127. continue;
  17128. }
  17129. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17130. if (!mesh.isReady() || !mesh.isEnabled()) {
  17131. continue;
  17132. }
  17133. mesh.computeWorldMatrix();
  17134. // Intersections
  17135. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17136. this._meshesForIntersections.pushNoDuplicate(mesh);
  17137. }
  17138. // Switch to current LOD
  17139. var meshLOD = mesh.getLOD(this.activeCamera);
  17140. if (!meshLOD) {
  17141. continue;
  17142. }
  17143. mesh._preActivate();
  17144. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17145. this._activeMeshes.push(mesh);
  17146. this.activeCamera._activeMeshes.push(mesh);
  17147. mesh._activate(this._renderId);
  17148. this._activeMesh(mesh, meshLOD);
  17149. }
  17150. }
  17151. // Particle systems
  17152. this._particlesDuration.beginMonitoring();
  17153. var beforeParticlesDate = BABYLON.Tools.Now;
  17154. if (this.particlesEnabled) {
  17155. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17156. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17157. var particleSystem = this.particleSystems[particleIndex];
  17158. if (!particleSystem.isStarted()) {
  17159. continue;
  17160. }
  17161. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17162. this._activeParticleSystems.push(particleSystem);
  17163. particleSystem.animate();
  17164. }
  17165. }
  17166. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17167. }
  17168. this._particlesDuration.endMonitoring(false);
  17169. };
  17170. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17171. if (mesh.skeleton && this.skeletonsEnabled) {
  17172. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17173. mesh.skeleton.prepare();
  17174. }
  17175. if (!mesh.computeBonesUsingShaders) {
  17176. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17177. }
  17178. }
  17179. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17180. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17181. }
  17182. if (sourceMesh._edgesRenderer) {
  17183. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17184. }
  17185. if (mesh && mesh.subMeshes) {
  17186. // Submeshes Octrees
  17187. var len;
  17188. var subMeshes;
  17189. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17190. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17191. len = intersections.length;
  17192. subMeshes = intersections.data;
  17193. }
  17194. else {
  17195. subMeshes = mesh.subMeshes;
  17196. len = subMeshes.length;
  17197. }
  17198. for (var subIndex = 0; subIndex < len; subIndex++) {
  17199. var subMesh = subMeshes[subIndex];
  17200. this._evaluateSubMesh(subMesh, mesh);
  17201. }
  17202. }
  17203. };
  17204. Scene.prototype.updateTransformMatrix = function (force) {
  17205. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17206. };
  17207. Scene.prototype._renderForCamera = function (camera) {
  17208. var engine = this._engine;
  17209. var startTime = BABYLON.Tools.Now;
  17210. this.activeCamera = camera;
  17211. if (!this.activeCamera)
  17212. throw new Error("Active camera not set");
  17213. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17214. // Viewport
  17215. engine.setViewport(this.activeCamera.viewport);
  17216. // Camera
  17217. this.resetCachedMaterial();
  17218. this._renderId++;
  17219. this.updateTransformMatrix();
  17220. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17221. // Meshes
  17222. this._evaluateActiveMeshesDuration.beginMonitoring();
  17223. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17224. this._evaluateActiveMeshes();
  17225. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17226. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17227. // Software skinning
  17228. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17229. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17230. mesh.applySkeleton(mesh.skeleton);
  17231. }
  17232. // Render targets
  17233. this._renderTargetsDuration.beginMonitoring();
  17234. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17235. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17236. this._intermediateRendering = true;
  17237. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17238. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17239. var renderTarget = this._renderTargets.data[renderIndex];
  17240. if (renderTarget._shouldRender()) {
  17241. this._renderId++;
  17242. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17243. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17244. }
  17245. }
  17246. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17247. this._intermediateRendering = false;
  17248. this._renderId++;
  17249. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17250. }
  17251. this._renderTargetsDuration.endMonitoring(false);
  17252. // Prepare Frame
  17253. this.postProcessManager._prepareFrame();
  17254. this._renderDuration.beginMonitoring();
  17255. // Backgrounds
  17256. var layerIndex;
  17257. var layer;
  17258. if (this.layers.length) {
  17259. engine.setDepthBuffer(false);
  17260. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17261. layer = this.layers[layerIndex];
  17262. if (layer.isBackground) {
  17263. layer.render();
  17264. }
  17265. }
  17266. engine.setDepthBuffer(true);
  17267. }
  17268. // Render
  17269. BABYLON.Tools.StartPerformanceCounter("Main render");
  17270. this._renderingManager.render(null, null, true, true);
  17271. BABYLON.Tools.EndPerformanceCounter("Main render");
  17272. // Bounding boxes
  17273. this._boundingBoxRenderer.render();
  17274. // Edges
  17275. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17276. this._edgesRenderers.data[edgesRendererIndex].render();
  17277. }
  17278. // Lens flares
  17279. if (this.lensFlaresEnabled) {
  17280. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17281. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17282. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17283. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17284. lensFlareSystem.render();
  17285. }
  17286. }
  17287. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17288. }
  17289. // Foregrounds
  17290. if (this.layers.length) {
  17291. engine.setDepthBuffer(false);
  17292. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17293. layer = this.layers[layerIndex];
  17294. if (!layer.isBackground) {
  17295. layer.render();
  17296. }
  17297. }
  17298. engine.setDepthBuffer(true);
  17299. }
  17300. this._renderDuration.endMonitoring(false);
  17301. // Finalize frame
  17302. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17303. // Update camera
  17304. this.activeCamera._updateFromScene();
  17305. // Reset some special arrays
  17306. this._renderTargets.reset();
  17307. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17308. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17309. };
  17310. Scene.prototype._processSubCameras = function (camera) {
  17311. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17312. this._renderForCamera(camera);
  17313. return;
  17314. }
  17315. // rig cameras
  17316. for (var index = 0; index < camera._rigCameras.length; index++) {
  17317. this._renderForCamera(camera._rigCameras[index]);
  17318. }
  17319. this.activeCamera = camera;
  17320. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17321. // Update camera
  17322. this.activeCamera._updateFromScene();
  17323. };
  17324. Scene.prototype._checkIntersections = function () {
  17325. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17326. var sourceMesh = this._meshesForIntersections.data[index];
  17327. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17328. var action = sourceMesh.actionManager.actions[actionIndex];
  17329. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17330. var parameters = action.getTriggerParameter();
  17331. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17332. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17333. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17334. if (areIntersecting && currentIntersectionInProgress === -1) {
  17335. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17336. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17337. sourceMesh._intersectionsInProgress.push(otherMesh);
  17338. }
  17339. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17340. sourceMesh._intersectionsInProgress.push(otherMesh);
  17341. }
  17342. }
  17343. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17344. //They intersected, and now they don't.
  17345. //is this trigger an exit trigger? execute an event.
  17346. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17347. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17348. }
  17349. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17350. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17351. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17352. }
  17353. }
  17354. }
  17355. }
  17356. }
  17357. };
  17358. Scene.prototype.render = function () {
  17359. this._lastFrameDuration.beginMonitoring();
  17360. this._particlesDuration.fetchNewFrame();
  17361. this._spritesDuration.fetchNewFrame();
  17362. this._activeParticles.fetchNewFrame();
  17363. this._renderDuration.fetchNewFrame();
  17364. this._renderTargetsDuration.fetchNewFrame();
  17365. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17366. this._totalVertices.fetchNewFrame();
  17367. this._activeIndices.fetchNewFrame();
  17368. this._activeBones.fetchNewFrame();
  17369. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17370. this._meshesForIntersections.reset();
  17371. this.resetCachedMaterial();
  17372. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17373. // Actions
  17374. if (this.actionManager) {
  17375. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17376. }
  17377. //Simplification Queue
  17378. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17379. this.simplificationQueue.executeNext();
  17380. }
  17381. // Animations
  17382. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17383. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17384. this._animate();
  17385. // Physics
  17386. if (this._physicsEngine) {
  17387. BABYLON.Tools.StartPerformanceCounter("Physics");
  17388. this._physicsEngine._step(deltaTime / 1000.0);
  17389. BABYLON.Tools.EndPerformanceCounter("Physics");
  17390. }
  17391. // Before render
  17392. this.onBeforeRenderObservable.notifyObservers(this);
  17393. // Customs render targets
  17394. this._renderTargetsDuration.beginMonitoring();
  17395. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17396. var engine = this.getEngine();
  17397. var currentActiveCamera = this.activeCamera;
  17398. if (this.renderTargetsEnabled) {
  17399. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17400. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17401. var renderTarget = this.customRenderTargets[customIndex];
  17402. if (renderTarget._shouldRender()) {
  17403. this._renderId++;
  17404. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17405. if (!this.activeCamera)
  17406. throw new Error("Active camera not set");
  17407. // Viewport
  17408. engine.setViewport(this.activeCamera.viewport);
  17409. // Camera
  17410. this.updateTransformMatrix();
  17411. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17412. }
  17413. }
  17414. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17415. this._renderId++;
  17416. }
  17417. if (this.customRenderTargets.length > 0) {
  17418. engine.restoreDefaultFramebuffer();
  17419. }
  17420. this._renderTargetsDuration.endMonitoring();
  17421. this.activeCamera = currentActiveCamera;
  17422. // Procedural textures
  17423. if (this.proceduralTexturesEnabled) {
  17424. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17425. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17426. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17427. if (proceduralTexture._shouldRender()) {
  17428. proceduralTexture.render();
  17429. }
  17430. }
  17431. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17432. }
  17433. // Clear
  17434. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  17435. // Shadows
  17436. if (this.shadowsEnabled) {
  17437. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17438. var light = this.lights[lightIndex];
  17439. var shadowGenerator = light.getShadowGenerator();
  17440. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  17441. this._renderTargets.push(shadowGenerator.getShadowMap());
  17442. }
  17443. }
  17444. }
  17445. // Depth renderer
  17446. if (this._depthRenderer) {
  17447. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17448. }
  17449. // RenderPipeline
  17450. this.postProcessRenderPipelineManager.update();
  17451. // Multi-cameras?
  17452. if (this.activeCameras.length > 0) {
  17453. var currentRenderId = this._renderId;
  17454. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17455. this._renderId = currentRenderId;
  17456. if (cameraIndex > 0) {
  17457. this._engine.clear(0, false, true, true);
  17458. }
  17459. this._processSubCameras(this.activeCameras[cameraIndex]);
  17460. }
  17461. }
  17462. else {
  17463. if (!this.activeCamera) {
  17464. throw new Error("No camera defined");
  17465. }
  17466. this._processSubCameras(this.activeCamera);
  17467. }
  17468. // Intersection checks
  17469. this._checkIntersections();
  17470. // Update the audio listener attached to the camera
  17471. if (BABYLON.AudioEngine) {
  17472. this._updateAudioParameters();
  17473. }
  17474. // After render
  17475. if (this.afterRender) {
  17476. this.afterRender();
  17477. }
  17478. this.onAfterRenderObservable.notifyObservers(this);
  17479. // Cleaning
  17480. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17481. this._toBeDisposed.data[index].dispose();
  17482. this._toBeDisposed[index] = null;
  17483. }
  17484. this._toBeDisposed.reset();
  17485. if (this.dumpNextRenderTargets) {
  17486. this.dumpNextRenderTargets = false;
  17487. }
  17488. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17489. this._lastFrameDuration.endMonitoring();
  17490. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17491. this._totalLightsCounter.addCount(this.lights.length, true);
  17492. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17493. this._totalTexturesCounter.addCount(this.textures.length, true);
  17494. this._activeBones.addCount(0, true);
  17495. this._activeIndices.addCount(0, true);
  17496. this._activeParticles.addCount(0, true);
  17497. };
  17498. Scene.prototype._updateAudioParameters = function () {
  17499. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17500. return;
  17501. }
  17502. var listeningCamera;
  17503. var audioEngine = BABYLON.Engine.audioEngine;
  17504. if (this.activeCameras.length > 0) {
  17505. listeningCamera = this.activeCameras[0];
  17506. }
  17507. else {
  17508. listeningCamera = this.activeCamera;
  17509. }
  17510. if (listeningCamera && audioEngine.canUseWebAudio) {
  17511. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17512. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17513. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17514. cameraDirection.normalize();
  17515. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17516. var i;
  17517. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17518. var sound = this.mainSoundTrack.soundCollection[i];
  17519. if (sound.useCustomAttenuation) {
  17520. sound.updateDistanceFromListener();
  17521. }
  17522. }
  17523. for (i = 0; i < this.soundTracks.length; i++) {
  17524. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17525. sound = this.soundTracks[i].soundCollection[j];
  17526. if (sound.useCustomAttenuation) {
  17527. sound.updateDistanceFromListener();
  17528. }
  17529. }
  17530. }
  17531. }
  17532. };
  17533. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17534. // Audio
  17535. get: function () {
  17536. return this._audioEnabled;
  17537. },
  17538. set: function (value) {
  17539. this._audioEnabled = value;
  17540. if (BABYLON.AudioEngine) {
  17541. if (this._audioEnabled) {
  17542. this._enableAudio();
  17543. }
  17544. else {
  17545. this._disableAudio();
  17546. }
  17547. }
  17548. },
  17549. enumerable: true,
  17550. configurable: true
  17551. });
  17552. Scene.prototype._disableAudio = function () {
  17553. var i;
  17554. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17555. this.mainSoundTrack.soundCollection[i].pause();
  17556. }
  17557. for (i = 0; i < this.soundTracks.length; i++) {
  17558. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17559. this.soundTracks[i].soundCollection[j].pause();
  17560. }
  17561. }
  17562. };
  17563. Scene.prototype._enableAudio = function () {
  17564. var i;
  17565. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17566. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17567. this.mainSoundTrack.soundCollection[i].play();
  17568. }
  17569. }
  17570. for (i = 0; i < this.soundTracks.length; i++) {
  17571. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17572. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17573. this.soundTracks[i].soundCollection[j].play();
  17574. }
  17575. }
  17576. }
  17577. };
  17578. Object.defineProperty(Scene.prototype, "headphone", {
  17579. get: function () {
  17580. return this._headphone;
  17581. },
  17582. set: function (value) {
  17583. this._headphone = value;
  17584. if (BABYLON.AudioEngine) {
  17585. if (this._headphone) {
  17586. this._switchAudioModeForHeadphones();
  17587. }
  17588. else {
  17589. this._switchAudioModeForNormalSpeakers();
  17590. }
  17591. }
  17592. },
  17593. enumerable: true,
  17594. configurable: true
  17595. });
  17596. Scene.prototype._switchAudioModeForHeadphones = function () {
  17597. this.mainSoundTrack.switchPanningModelToHRTF();
  17598. for (var i = 0; i < this.soundTracks.length; i++) {
  17599. this.soundTracks[i].switchPanningModelToHRTF();
  17600. }
  17601. };
  17602. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17603. this.mainSoundTrack.switchPanningModelToEqualPower();
  17604. for (var i = 0; i < this.soundTracks.length; i++) {
  17605. this.soundTracks[i].switchPanningModelToEqualPower();
  17606. }
  17607. };
  17608. Scene.prototype.enableDepthRenderer = function () {
  17609. if (this._depthRenderer) {
  17610. return this._depthRenderer;
  17611. }
  17612. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17613. return this._depthRenderer;
  17614. };
  17615. Scene.prototype.disableDepthRenderer = function () {
  17616. if (!this._depthRenderer) {
  17617. return;
  17618. }
  17619. this._depthRenderer.dispose();
  17620. this._depthRenderer = null;
  17621. };
  17622. Scene.prototype.freezeMaterials = function () {
  17623. for (var i = 0; i < this.materials.length; i++) {
  17624. this.materials[i].freeze();
  17625. }
  17626. };
  17627. Scene.prototype.unfreezeMaterials = function () {
  17628. for (var i = 0; i < this.materials.length; i++) {
  17629. this.materials[i].unfreeze();
  17630. }
  17631. };
  17632. Scene.prototype.dispose = function () {
  17633. this.beforeRender = null;
  17634. this.afterRender = null;
  17635. this.skeletons = [];
  17636. this._boundingBoxRenderer.dispose();
  17637. if (this._depthRenderer) {
  17638. this._depthRenderer.dispose();
  17639. }
  17640. // Debug layer
  17641. if (this._debugLayer) {
  17642. this._debugLayer.hide();
  17643. }
  17644. // Events
  17645. this.onDisposeObservable.notifyObservers(this);
  17646. this.onDisposeObservable.clear();
  17647. this.onBeforeRenderObservable.clear();
  17648. this.onAfterRenderObservable.clear();
  17649. this.detachControl();
  17650. // Release sounds & sounds tracks
  17651. if (BABYLON.AudioEngine) {
  17652. this.disposeSounds();
  17653. }
  17654. // Detach cameras
  17655. var canvas = this._engine.getRenderingCanvas();
  17656. var index;
  17657. for (index = 0; index < this.cameras.length; index++) {
  17658. this.cameras[index].detachControl(canvas);
  17659. }
  17660. // Release lights
  17661. while (this.lights.length) {
  17662. this.lights[0].dispose();
  17663. }
  17664. // Release meshes
  17665. while (this.meshes.length) {
  17666. this.meshes[0].dispose(true);
  17667. }
  17668. // Release cameras
  17669. while (this.cameras.length) {
  17670. this.cameras[0].dispose();
  17671. }
  17672. // Release materials
  17673. while (this.materials.length) {
  17674. this.materials[0].dispose();
  17675. }
  17676. // Release particles
  17677. while (this.particleSystems.length) {
  17678. this.particleSystems[0].dispose();
  17679. }
  17680. // Release sprites
  17681. while (this.spriteManagers.length) {
  17682. this.spriteManagers[0].dispose();
  17683. }
  17684. // Release layers
  17685. while (this.layers.length) {
  17686. this.layers[0].dispose();
  17687. }
  17688. // Release textures
  17689. while (this.textures.length) {
  17690. this.textures[0].dispose();
  17691. }
  17692. // Post-processes
  17693. this.postProcessManager.dispose();
  17694. // Physics
  17695. if (this._physicsEngine) {
  17696. this.disablePhysicsEngine();
  17697. }
  17698. // Remove from engine
  17699. index = this._engine.scenes.indexOf(this);
  17700. if (index > -1) {
  17701. this._engine.scenes.splice(index, 1);
  17702. }
  17703. this._engine.wipeCaches();
  17704. };
  17705. // Release sounds & sounds tracks
  17706. Scene.prototype.disposeSounds = function () {
  17707. this.mainSoundTrack.dispose();
  17708. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17709. this.soundTracks[scIndex].dispose();
  17710. }
  17711. };
  17712. // Octrees
  17713. Scene.prototype.getWorldExtends = function () {
  17714. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17715. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17716. for (var index = 0; index < this.meshes.length; index++) {
  17717. var mesh = this.meshes[index];
  17718. mesh.computeWorldMatrix(true);
  17719. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17720. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17721. BABYLON.Tools.CheckExtends(minBox, min, max);
  17722. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17723. }
  17724. return {
  17725. min: min,
  17726. max: max
  17727. };
  17728. };
  17729. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17730. if (maxCapacity === void 0) { maxCapacity = 64; }
  17731. if (maxDepth === void 0) { maxDepth = 2; }
  17732. if (!this._selectionOctree) {
  17733. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17734. }
  17735. var worldExtends = this.getWorldExtends();
  17736. // Update octree
  17737. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17738. return this._selectionOctree;
  17739. };
  17740. // Picking
  17741. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17742. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17743. var engine = this._engine;
  17744. if (!camera) {
  17745. if (!this.activeCamera)
  17746. throw new Error("Active camera not set");
  17747. camera = this.activeCamera;
  17748. }
  17749. var cameraViewport = camera.viewport;
  17750. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17751. // Moving coordinates to local viewport world
  17752. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17753. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17754. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17755. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17756. };
  17757. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17758. var engine = this._engine;
  17759. if (!camera) {
  17760. if (!this.activeCamera)
  17761. throw new Error("Active camera not set");
  17762. camera = this.activeCamera;
  17763. }
  17764. var cameraViewport = camera.viewport;
  17765. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17766. var identity = BABYLON.Matrix.Identity();
  17767. // Moving coordinates to local viewport world
  17768. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17769. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17770. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17771. };
  17772. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17773. var pickingInfo = null;
  17774. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17775. var mesh = this.meshes[meshIndex];
  17776. if (predicate) {
  17777. if (!predicate(mesh)) {
  17778. continue;
  17779. }
  17780. }
  17781. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17782. continue;
  17783. }
  17784. var world = mesh.getWorldMatrix();
  17785. var ray = rayFunction(world);
  17786. var result = mesh.intersects(ray, fastCheck);
  17787. if (!result || !result.hit)
  17788. continue;
  17789. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17790. continue;
  17791. pickingInfo = result;
  17792. if (fastCheck) {
  17793. break;
  17794. }
  17795. }
  17796. return pickingInfo || new BABYLON.PickingInfo();
  17797. };
  17798. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17799. var pickingInfo = null;
  17800. camera = camera || this.activeCamera;
  17801. if (this.spriteManagers.length > 0) {
  17802. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17803. var spriteManager = this.spriteManagers[spriteIndex];
  17804. if (!spriteManager.isPickable) {
  17805. continue;
  17806. }
  17807. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17808. if (!result || !result.hit)
  17809. continue;
  17810. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17811. continue;
  17812. pickingInfo = result;
  17813. if (fastCheck) {
  17814. break;
  17815. }
  17816. }
  17817. }
  17818. return pickingInfo || new BABYLON.PickingInfo();
  17819. };
  17820. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17821. var _this = this;
  17822. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17823. /// <param name="x">X position on screen</param>
  17824. /// <param name="y">Y position on screen</param>
  17825. /// <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>
  17826. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17827. /// <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>
  17828. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17829. };
  17830. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17831. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17832. /// <param name="x">X position on screen</param>
  17833. /// <param name="y">Y position on screen</param>
  17834. /// <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>
  17835. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17836. /// <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>
  17837. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17838. };
  17839. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17840. var _this = this;
  17841. return this._internalPick(function (world) {
  17842. if (!_this._pickWithRayInverseMatrix) {
  17843. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17844. }
  17845. world.invertToRef(_this._pickWithRayInverseMatrix);
  17846. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17847. }, predicate, fastCheck);
  17848. };
  17849. Scene.prototype.setPointerOverMesh = function (mesh) {
  17850. if (this._pointerOverMesh === mesh) {
  17851. return;
  17852. }
  17853. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17854. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17855. }
  17856. this._pointerOverMesh = mesh;
  17857. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17858. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17859. }
  17860. };
  17861. Scene.prototype.getPointerOverMesh = function () {
  17862. return this._pointerOverMesh;
  17863. };
  17864. Scene.prototype.setPointerOverSprite = function (sprite) {
  17865. if (this._pointerOverSprite === sprite) {
  17866. return;
  17867. }
  17868. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17869. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17870. }
  17871. this._pointerOverSprite = sprite;
  17872. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17873. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17874. }
  17875. };
  17876. Scene.prototype.getPointerOverSprite = function () {
  17877. return this._pointerOverSprite;
  17878. };
  17879. // Physics
  17880. Scene.prototype.getPhysicsEngine = function () {
  17881. return this._physicsEngine;
  17882. };
  17883. /**
  17884. * Enables physics to the current scene
  17885. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17886. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17887. * @return {boolean} was the physics engine initialized
  17888. */
  17889. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17890. if (this._physicsEngine) {
  17891. return true;
  17892. }
  17893. try {
  17894. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17895. return true;
  17896. }
  17897. catch (e) {
  17898. BABYLON.Tools.Error(e.message);
  17899. return false;
  17900. }
  17901. };
  17902. Scene.prototype.disablePhysicsEngine = function () {
  17903. if (!this._physicsEngine) {
  17904. return;
  17905. }
  17906. this._physicsEngine.dispose();
  17907. this._physicsEngine = undefined;
  17908. };
  17909. Scene.prototype.isPhysicsEnabled = function () {
  17910. return this._physicsEngine !== undefined;
  17911. };
  17912. /**
  17913. *
  17914. * Sets the gravity of the physics engine (and NOT of the scene)
  17915. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  17916. */
  17917. Scene.prototype.setGravity = function (gravity) {
  17918. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  17919. if (!this._physicsEngine) {
  17920. return;
  17921. }
  17922. this._physicsEngine.setGravity(gravity);
  17923. };
  17924. /**
  17925. * Legacy support, using the new API
  17926. * @Deprecated
  17927. */
  17928. Scene.prototype.createCompoundImpostor = function (parts, options) {
  17929. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  17930. if (parts.parts) {
  17931. options = parts;
  17932. parts = parts.parts;
  17933. }
  17934. var mainMesh = parts[0].mesh;
  17935. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  17936. for (var index = 1; index < parts.length; index++) {
  17937. var mesh = parts[index].mesh;
  17938. if (mesh.parent !== mainMesh) {
  17939. mesh.position = mesh.position.subtract(mainMesh.position);
  17940. mesh.parent = mainMesh;
  17941. }
  17942. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  17943. }
  17944. mainMesh.physicsImpostor.forceUpdate();
  17945. };
  17946. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17947. var mesh = compound.parts[0].mesh;
  17948. mesh.physicsImpostor.dispose();
  17949. mesh.physicsImpostor = null;
  17950. };
  17951. // Misc.
  17952. Scene.prototype.createDefaultCameraOrLight = function () {
  17953. // Light
  17954. if (this.lights.length === 0) {
  17955. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17956. }
  17957. // Camera
  17958. if (!this.activeCamera) {
  17959. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17960. // Compute position
  17961. var worldExtends = this.getWorldExtends();
  17962. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17963. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17964. camera.setTarget(worldCenter);
  17965. this.activeCamera = camera;
  17966. }
  17967. };
  17968. // Tags
  17969. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17970. if (tagsQuery === undefined) {
  17971. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17972. return list;
  17973. }
  17974. var listByTags = [];
  17975. forEach = forEach || (function (item) { return; });
  17976. for (var i in list) {
  17977. var item = list[i];
  17978. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17979. listByTags.push(item);
  17980. forEach(item);
  17981. }
  17982. }
  17983. return listByTags;
  17984. };
  17985. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17986. return this._getByTags(this.meshes, tagsQuery, forEach);
  17987. };
  17988. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17989. return this._getByTags(this.cameras, tagsQuery, forEach);
  17990. };
  17991. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17992. return this._getByTags(this.lights, tagsQuery, forEach);
  17993. };
  17994. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17995. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17996. };
  17997. /**
  17998. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17999. * This allowed control for front to back rendering or reversly depending of the special needs.
  18000. *
  18001. * @param renderingGroupId The rendering group id corresponding to its index
  18002. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18003. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18004. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18005. */
  18006. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18007. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18008. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18009. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18010. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18011. };
  18012. /**
  18013. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18014. *
  18015. * @param renderingGroupId The rendering group id corresponding to its index
  18016. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18017. */
  18018. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  18019. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  18020. };
  18021. // Statics
  18022. Scene._FOGMODE_NONE = 0;
  18023. Scene._FOGMODE_EXP = 1;
  18024. Scene._FOGMODE_EXP2 = 2;
  18025. Scene._FOGMODE_LINEAR = 3;
  18026. Scene.MinDeltaTime = 1.0;
  18027. Scene.MaxDeltaTime = 1000.0;
  18028. return Scene;
  18029. })();
  18030. BABYLON.Scene = Scene;
  18031. })(BABYLON || (BABYLON = {}));
  18032. var BABYLON;
  18033. (function (BABYLON) {
  18034. var Buffer = (function () {
  18035. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18036. if (engine instanceof BABYLON.Mesh) {
  18037. this._engine = engine.getScene().getEngine();
  18038. }
  18039. else {
  18040. this._engine = engine;
  18041. }
  18042. this._updatable = updatable;
  18043. this._data = data;
  18044. this._strideSize = stride;
  18045. if (!postponeInternalCreation) {
  18046. this.create();
  18047. }
  18048. this._instanced = instanced;
  18049. }
  18050. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18051. // a lot of these parameters are ignored as they are overriden by the buffer
  18052. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18053. };
  18054. // Properties
  18055. Buffer.prototype.isUpdatable = function () {
  18056. return this._updatable;
  18057. };
  18058. Buffer.prototype.getData = function () {
  18059. return this._data;
  18060. };
  18061. Buffer.prototype.getBuffer = function () {
  18062. return this._buffer;
  18063. };
  18064. Buffer.prototype.getStrideSize = function () {
  18065. return this._strideSize;
  18066. };
  18067. Buffer.prototype.getIsInstanced = function () {
  18068. return this._instanced;
  18069. };
  18070. // Methods
  18071. Buffer.prototype.create = function (data) {
  18072. if (!data && this._buffer) {
  18073. return; // nothing to do
  18074. }
  18075. data = data || this._data;
  18076. if (!this._buffer) {
  18077. if (this._updatable) {
  18078. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18079. this._data = data;
  18080. }
  18081. else {
  18082. this._buffer = this._engine.createVertexBuffer(data);
  18083. }
  18084. }
  18085. else if (this._updatable) {
  18086. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18087. this._data = data;
  18088. }
  18089. };
  18090. Buffer.prototype.update = function (data) {
  18091. this.create(data);
  18092. };
  18093. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18094. if (!this._buffer) {
  18095. return;
  18096. }
  18097. if (this._updatable) {
  18098. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18099. this._data = null;
  18100. }
  18101. };
  18102. Buffer.prototype.dispose = function () {
  18103. if (!this._buffer) {
  18104. return;
  18105. }
  18106. if (this._engine._releaseBuffer(this._buffer)) {
  18107. this._buffer = null;
  18108. }
  18109. };
  18110. return Buffer;
  18111. })();
  18112. BABYLON.Buffer = Buffer;
  18113. })(BABYLON || (BABYLON = {}));
  18114. var BABYLON;
  18115. (function (BABYLON) {
  18116. var VertexBuffer = (function () {
  18117. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18118. if (!stride) {
  18119. // Deduce stride from kind
  18120. switch (kind) {
  18121. case VertexBuffer.PositionKind:
  18122. stride = 3;
  18123. break;
  18124. case VertexBuffer.NormalKind:
  18125. stride = 3;
  18126. break;
  18127. case VertexBuffer.UVKind:
  18128. case VertexBuffer.UV2Kind:
  18129. case VertexBuffer.UV3Kind:
  18130. case VertexBuffer.UV4Kind:
  18131. case VertexBuffer.UV5Kind:
  18132. case VertexBuffer.UV6Kind:
  18133. stride = 2;
  18134. break;
  18135. case VertexBuffer.ColorKind:
  18136. stride = 4;
  18137. break;
  18138. case VertexBuffer.MatricesIndicesKind:
  18139. case VertexBuffer.MatricesIndicesExtraKind:
  18140. stride = 4;
  18141. break;
  18142. case VertexBuffer.MatricesWeightsKind:
  18143. case VertexBuffer.MatricesWeightsExtraKind:
  18144. stride = 4;
  18145. break;
  18146. }
  18147. }
  18148. if (data instanceof BABYLON.Buffer) {
  18149. if (!stride) {
  18150. stride = data.getStrideSize();
  18151. }
  18152. this._buffer = data;
  18153. this._ownsBuffer = false;
  18154. }
  18155. else {
  18156. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18157. this._ownsBuffer = true;
  18158. }
  18159. this._stride = stride;
  18160. this._offset = offset ? offset : 0;
  18161. this._size = size ? size : stride;
  18162. this._kind = kind;
  18163. }
  18164. VertexBuffer.prototype.getKind = function () {
  18165. return this._kind;
  18166. };
  18167. // Properties
  18168. VertexBuffer.prototype.isUpdatable = function () {
  18169. return this._buffer.isUpdatable();
  18170. };
  18171. VertexBuffer.prototype.getData = function () {
  18172. return this._buffer.getData();
  18173. };
  18174. VertexBuffer.prototype.getBuffer = function () {
  18175. return this._buffer.getBuffer();
  18176. };
  18177. VertexBuffer.prototype.getStrideSize = function () {
  18178. return this._stride;
  18179. };
  18180. VertexBuffer.prototype.getOffset = function () {
  18181. return this._offset;
  18182. };
  18183. VertexBuffer.prototype.getSize = function () {
  18184. return this._size;
  18185. };
  18186. VertexBuffer.prototype.getIsInstanced = function () {
  18187. return this._buffer.getIsInstanced();
  18188. };
  18189. // Methods
  18190. VertexBuffer.prototype.create = function (data) {
  18191. return this._buffer.create(data);
  18192. };
  18193. VertexBuffer.prototype.update = function (data) {
  18194. return this._buffer.update(data);
  18195. };
  18196. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18197. return this._buffer.updateDirectly(data, offset);
  18198. };
  18199. VertexBuffer.prototype.dispose = function () {
  18200. if (this._ownsBuffer) {
  18201. this._buffer.dispose();
  18202. }
  18203. };
  18204. Object.defineProperty(VertexBuffer, "PositionKind", {
  18205. get: function () {
  18206. return VertexBuffer._PositionKind;
  18207. },
  18208. enumerable: true,
  18209. configurable: true
  18210. });
  18211. Object.defineProperty(VertexBuffer, "NormalKind", {
  18212. get: function () {
  18213. return VertexBuffer._NormalKind;
  18214. },
  18215. enumerable: true,
  18216. configurable: true
  18217. });
  18218. Object.defineProperty(VertexBuffer, "UVKind", {
  18219. get: function () {
  18220. return VertexBuffer._UVKind;
  18221. },
  18222. enumerable: true,
  18223. configurable: true
  18224. });
  18225. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18226. get: function () {
  18227. return VertexBuffer._UV2Kind;
  18228. },
  18229. enumerable: true,
  18230. configurable: true
  18231. });
  18232. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18233. get: function () {
  18234. return VertexBuffer._UV3Kind;
  18235. },
  18236. enumerable: true,
  18237. configurable: true
  18238. });
  18239. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18240. get: function () {
  18241. return VertexBuffer._UV4Kind;
  18242. },
  18243. enumerable: true,
  18244. configurable: true
  18245. });
  18246. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18247. get: function () {
  18248. return VertexBuffer._UV5Kind;
  18249. },
  18250. enumerable: true,
  18251. configurable: true
  18252. });
  18253. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18254. get: function () {
  18255. return VertexBuffer._UV6Kind;
  18256. },
  18257. enumerable: true,
  18258. configurable: true
  18259. });
  18260. Object.defineProperty(VertexBuffer, "ColorKind", {
  18261. get: function () {
  18262. return VertexBuffer._ColorKind;
  18263. },
  18264. enumerable: true,
  18265. configurable: true
  18266. });
  18267. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18268. get: function () {
  18269. return VertexBuffer._MatricesIndicesKind;
  18270. },
  18271. enumerable: true,
  18272. configurable: true
  18273. });
  18274. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18275. get: function () {
  18276. return VertexBuffer._MatricesWeightsKind;
  18277. },
  18278. enumerable: true,
  18279. configurable: true
  18280. });
  18281. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18282. get: function () {
  18283. return VertexBuffer._MatricesIndicesExtraKind;
  18284. },
  18285. enumerable: true,
  18286. configurable: true
  18287. });
  18288. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18289. get: function () {
  18290. return VertexBuffer._MatricesWeightsExtraKind;
  18291. },
  18292. enumerable: true,
  18293. configurable: true
  18294. });
  18295. // Enums
  18296. VertexBuffer._PositionKind = "position";
  18297. VertexBuffer._NormalKind = "normal";
  18298. VertexBuffer._UVKind = "uv";
  18299. VertexBuffer._UV2Kind = "uv2";
  18300. VertexBuffer._UV3Kind = "uv3";
  18301. VertexBuffer._UV4Kind = "uv4";
  18302. VertexBuffer._UV5Kind = "uv5";
  18303. VertexBuffer._UV6Kind = "uv6";
  18304. VertexBuffer._ColorKind = "color";
  18305. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18306. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18307. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18308. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18309. return VertexBuffer;
  18310. })();
  18311. BABYLON.VertexBuffer = VertexBuffer;
  18312. })(BABYLON || (BABYLON = {}));
  18313. var BABYLON;
  18314. (function (BABYLON) {
  18315. /**
  18316. * Creates an instance based on a source mesh.
  18317. */
  18318. var InstancedMesh = (function (_super) {
  18319. __extends(InstancedMesh, _super);
  18320. function InstancedMesh(name, source) {
  18321. _super.call(this, name, source.getScene());
  18322. source.instances.push(this);
  18323. this._sourceMesh = source;
  18324. this.position.copyFrom(source.position);
  18325. this.rotation.copyFrom(source.rotation);
  18326. this.scaling.copyFrom(source.scaling);
  18327. if (source.rotationQuaternion) {
  18328. this.rotationQuaternion = source.rotationQuaternion.clone();
  18329. }
  18330. this.infiniteDistance = source.infiniteDistance;
  18331. this.setPivotMatrix(source.getPivotMatrix());
  18332. this.refreshBoundingInfo();
  18333. this._syncSubMeshes();
  18334. }
  18335. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  18336. // Methods
  18337. get: function () {
  18338. return this._sourceMesh.receiveShadows;
  18339. },
  18340. enumerable: true,
  18341. configurable: true
  18342. });
  18343. Object.defineProperty(InstancedMesh.prototype, "material", {
  18344. get: function () {
  18345. return this._sourceMesh.material;
  18346. },
  18347. enumerable: true,
  18348. configurable: true
  18349. });
  18350. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  18351. get: function () {
  18352. return this._sourceMesh.visibility;
  18353. },
  18354. enumerable: true,
  18355. configurable: true
  18356. });
  18357. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  18358. get: function () {
  18359. return this._sourceMesh.skeleton;
  18360. },
  18361. enumerable: true,
  18362. configurable: true
  18363. });
  18364. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  18365. get: function () {
  18366. return this._sourceMesh.renderingGroupId;
  18367. },
  18368. enumerable: true,
  18369. configurable: true
  18370. });
  18371. InstancedMesh.prototype.getTotalVertices = function () {
  18372. return this._sourceMesh.getTotalVertices();
  18373. };
  18374. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  18375. get: function () {
  18376. return this._sourceMesh;
  18377. },
  18378. enumerable: true,
  18379. configurable: true
  18380. });
  18381. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18382. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  18383. };
  18384. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  18385. return this._sourceMesh.isVerticesDataPresent(kind);
  18386. };
  18387. InstancedMesh.prototype.getIndices = function () {
  18388. return this._sourceMesh.getIndices();
  18389. };
  18390. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  18391. get: function () {
  18392. return this._sourceMesh._positions;
  18393. },
  18394. enumerable: true,
  18395. configurable: true
  18396. });
  18397. InstancedMesh.prototype.refreshBoundingInfo = function () {
  18398. var meshBB = this._sourceMesh.getBoundingInfo();
  18399. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  18400. this._updateBoundingInfo();
  18401. };
  18402. InstancedMesh.prototype._preActivate = function () {
  18403. if (this._currentLOD) {
  18404. this._currentLOD._preActivate();
  18405. }
  18406. };
  18407. InstancedMesh.prototype._activate = function (renderId) {
  18408. if (this._currentLOD) {
  18409. this._currentLOD._registerInstanceForRenderId(this, renderId);
  18410. }
  18411. };
  18412. InstancedMesh.prototype.getLOD = function (camera) {
  18413. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  18414. if (this._currentLOD === this.sourceMesh) {
  18415. return this;
  18416. }
  18417. return this._currentLOD;
  18418. };
  18419. InstancedMesh.prototype._syncSubMeshes = function () {
  18420. this.releaseSubMeshes();
  18421. if (this._sourceMesh.subMeshes) {
  18422. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  18423. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  18424. }
  18425. }
  18426. };
  18427. InstancedMesh.prototype._generatePointsArray = function () {
  18428. return this._sourceMesh._generatePointsArray();
  18429. };
  18430. // Clone
  18431. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18432. var result = this._sourceMesh.createInstance(name);
  18433. // Deep copy
  18434. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  18435. // Bounding info
  18436. this.refreshBoundingInfo();
  18437. // Parent
  18438. if (newParent) {
  18439. result.parent = newParent;
  18440. }
  18441. if (!doNotCloneChildren) {
  18442. // Children
  18443. for (var index = 0; index < this.getScene().meshes.length; index++) {
  18444. var mesh = this.getScene().meshes[index];
  18445. if (mesh.parent === this) {
  18446. mesh.clone(mesh.name, result);
  18447. }
  18448. }
  18449. }
  18450. result.computeWorldMatrix(true);
  18451. return result;
  18452. };
  18453. // Dispoe
  18454. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  18455. // Remove from mesh
  18456. var index = this._sourceMesh.instances.indexOf(this);
  18457. this._sourceMesh.instances.splice(index, 1);
  18458. _super.prototype.dispose.call(this, doNotRecurse);
  18459. };
  18460. return InstancedMesh;
  18461. })(BABYLON.AbstractMesh);
  18462. BABYLON.InstancedMesh = InstancedMesh;
  18463. })(BABYLON || (BABYLON = {}));
  18464. var BABYLON;
  18465. (function (BABYLON) {
  18466. var _InstancesBatch = (function () {
  18467. function _InstancesBatch() {
  18468. this.mustReturn = false;
  18469. this.visibleInstances = new Array();
  18470. this.renderSelf = new Array();
  18471. }
  18472. return _InstancesBatch;
  18473. })();
  18474. BABYLON._InstancesBatch = _InstancesBatch;
  18475. var Mesh = (function (_super) {
  18476. __extends(Mesh, _super);
  18477. /**
  18478. * @constructor
  18479. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18480. * @param {Scene} scene The scene to add this mesh to.
  18481. * @param {Node} parent The parent of this mesh, if it has one
  18482. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18483. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18484. * When false, achieved by calling a clone(), also passing False.
  18485. * This will make creation of children, recursive.
  18486. */
  18487. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18488. if (parent === void 0) { parent = null; }
  18489. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18490. _super.call(this, name, scene);
  18491. // Events
  18492. /**
  18493. * An event triggered before rendering the mesh
  18494. * @type {BABYLON.Observable}
  18495. */
  18496. this.onBeforeRenderObservable = new BABYLON.Observable();
  18497. /**
  18498. * An event triggered after rendering the mesh
  18499. * @type {BABYLON.Observable}
  18500. */
  18501. this.onAfterRenderObservable = new BABYLON.Observable();
  18502. /**
  18503. * An event triggered before drawing the mesh
  18504. * @type {BABYLON.Observable}
  18505. */
  18506. this.onBeforeDrawObservable = new BABYLON.Observable();
  18507. // Members
  18508. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18509. this.instances = new Array();
  18510. this._LODLevels = new Array();
  18511. this._visibleInstances = {};
  18512. this._renderIdForInstances = new Array();
  18513. this._batchCache = new _InstancesBatch();
  18514. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18515. this._sideOrientation = Mesh._DEFAULTSIDE;
  18516. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18517. if (source) {
  18518. // Geometry
  18519. if (source._geometry) {
  18520. source._geometry.applyToMesh(this);
  18521. }
  18522. // Deep copy
  18523. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  18524. // Pivot
  18525. this.setPivotMatrix(source.getPivotMatrix());
  18526. this.id = name + "." + source.id;
  18527. // Material
  18528. this.material = source.material;
  18529. var index;
  18530. if (!doNotCloneChildren) {
  18531. // Children
  18532. for (index = 0; index < scene.meshes.length; index++) {
  18533. var mesh = scene.meshes[index];
  18534. if (mesh.parent === source) {
  18535. // doNotCloneChildren is always going to be False
  18536. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  18537. }
  18538. }
  18539. }
  18540. // Physics clone
  18541. var physicsEngine = this.getScene().getPhysicsEngine();
  18542. if (clonePhysicsImpostor && physicsEngine) {
  18543. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18544. if (impostor) {
  18545. this.physicsImpostor = impostor.clone(this);
  18546. }
  18547. }
  18548. // Particles
  18549. for (index = 0; index < scene.particleSystems.length; index++) {
  18550. var system = scene.particleSystems[index];
  18551. if (system.emitter === source) {
  18552. system.clone(system.name, this);
  18553. }
  18554. }
  18555. this.computeWorldMatrix(true);
  18556. }
  18557. // Parent
  18558. if (parent !== null) {
  18559. this.parent = parent;
  18560. }
  18561. }
  18562. Object.defineProperty(Mesh, "FRONTSIDE", {
  18563. /**
  18564. * Mesh side orientation : usually the external or front surface
  18565. */
  18566. get: function () {
  18567. return Mesh._FRONTSIDE;
  18568. },
  18569. enumerable: true,
  18570. configurable: true
  18571. });
  18572. Object.defineProperty(Mesh, "BACKSIDE", {
  18573. /**
  18574. * Mesh side orientation : usually the internal or back surface
  18575. */
  18576. get: function () {
  18577. return Mesh._BACKSIDE;
  18578. },
  18579. enumerable: true,
  18580. configurable: true
  18581. });
  18582. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18583. /**
  18584. * Mesh side orientation : both internal and external or front and back surfaces
  18585. */
  18586. get: function () {
  18587. return Mesh._DOUBLESIDE;
  18588. },
  18589. enumerable: true,
  18590. configurable: true
  18591. });
  18592. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18593. /**
  18594. * Mesh side orientation : by default, `FRONTSIDE`
  18595. */
  18596. get: function () {
  18597. return Mesh._DEFAULTSIDE;
  18598. },
  18599. enumerable: true,
  18600. configurable: true
  18601. });
  18602. Object.defineProperty(Mesh, "NO_CAP", {
  18603. /**
  18604. * Mesh cap setting : no cap
  18605. */
  18606. get: function () {
  18607. return Mesh._NO_CAP;
  18608. },
  18609. enumerable: true,
  18610. configurable: true
  18611. });
  18612. Object.defineProperty(Mesh, "CAP_START", {
  18613. /**
  18614. * Mesh cap setting : one cap at the beginning of the mesh
  18615. */
  18616. get: function () {
  18617. return Mesh._CAP_START;
  18618. },
  18619. enumerable: true,
  18620. configurable: true
  18621. });
  18622. Object.defineProperty(Mesh, "CAP_END", {
  18623. /**
  18624. * Mesh cap setting : one cap at the end of the mesh
  18625. */
  18626. get: function () {
  18627. return Mesh._CAP_END;
  18628. },
  18629. enumerable: true,
  18630. configurable: true
  18631. });
  18632. Object.defineProperty(Mesh, "CAP_ALL", {
  18633. /**
  18634. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18635. */
  18636. get: function () {
  18637. return Mesh._CAP_ALL;
  18638. },
  18639. enumerable: true,
  18640. configurable: true
  18641. });
  18642. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18643. set: function (callback) {
  18644. if (this._onBeforeDrawObserver) {
  18645. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18646. }
  18647. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18648. },
  18649. enumerable: true,
  18650. configurable: true
  18651. });
  18652. // Methods
  18653. /**
  18654. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18655. */
  18656. Mesh.prototype.toString = function (fullDetails) {
  18657. var ret = _super.prototype.toString.call(this, fullDetails);
  18658. ret += ", n vertices: " + this.getTotalVertices();
  18659. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18660. if (this.animations) {
  18661. for (var i = 0; i < this.animations.length; i++) {
  18662. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18663. }
  18664. }
  18665. if (fullDetails) {
  18666. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18667. }
  18668. return ret;
  18669. };
  18670. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18671. get: function () {
  18672. return this._LODLevels.length > 0;
  18673. },
  18674. enumerable: true,
  18675. configurable: true
  18676. });
  18677. Mesh.prototype._sortLODLevels = function () {
  18678. this._LODLevels.sort(function (a, b) {
  18679. if (a.distance < b.distance) {
  18680. return 1;
  18681. }
  18682. if (a.distance > b.distance) {
  18683. return -1;
  18684. }
  18685. return 0;
  18686. });
  18687. };
  18688. /**
  18689. * Add a mesh as LOD level triggered at the given distance.
  18690. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18691. * @param {number} distance The distance from the center of the object to show this level
  18692. * @param {Mesh} mesh The mesh to be added as LOD level
  18693. * @return {Mesh} This mesh (for chaining)
  18694. */
  18695. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18696. if (mesh && mesh._masterMesh) {
  18697. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18698. return this;
  18699. }
  18700. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18701. this._LODLevels.push(level);
  18702. if (mesh) {
  18703. mesh._masterMesh = this;
  18704. }
  18705. this._sortLODLevels();
  18706. return this;
  18707. };
  18708. /**
  18709. * Returns the LOD level mesh at the passed distance or null if not found.
  18710. * It is related to the method `addLODLevel(distance, mesh)`.
  18711. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18712. */
  18713. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18714. for (var index = 0; index < this._LODLevels.length; index++) {
  18715. var level = this._LODLevels[index];
  18716. if (level.distance === distance) {
  18717. return level.mesh;
  18718. }
  18719. }
  18720. return null;
  18721. };
  18722. /**
  18723. * Remove a mesh from the LOD array
  18724. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18725. * @param {Mesh} mesh The mesh to be removed.
  18726. * @return {Mesh} This mesh (for chaining)
  18727. */
  18728. Mesh.prototype.removeLODLevel = function (mesh) {
  18729. for (var index = 0; index < this._LODLevels.length; index++) {
  18730. if (this._LODLevels[index].mesh === mesh) {
  18731. this._LODLevels.splice(index, 1);
  18732. if (mesh) {
  18733. mesh._masterMesh = null;
  18734. }
  18735. }
  18736. }
  18737. this._sortLODLevels();
  18738. return this;
  18739. };
  18740. /**
  18741. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18742. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18743. */
  18744. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18745. if (!this._LODLevels || this._LODLevels.length === 0) {
  18746. return this;
  18747. }
  18748. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18749. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18750. if (this.onLODLevelSelection) {
  18751. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18752. }
  18753. return this;
  18754. }
  18755. for (var index = 0; index < this._LODLevels.length; index++) {
  18756. var level = this._LODLevels[index];
  18757. if (level.distance < distanceToCamera) {
  18758. if (level.mesh) {
  18759. level.mesh._preActivate();
  18760. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18761. }
  18762. if (this.onLODLevelSelection) {
  18763. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18764. }
  18765. return level.mesh;
  18766. }
  18767. }
  18768. if (this.onLODLevelSelection) {
  18769. this.onLODLevelSelection(distanceToCamera, this, this);
  18770. }
  18771. return this;
  18772. };
  18773. Object.defineProperty(Mesh.prototype, "geometry", {
  18774. /**
  18775. * Returns the mesh internal Geometry object.
  18776. */
  18777. get: function () {
  18778. return this._geometry;
  18779. },
  18780. enumerable: true,
  18781. configurable: true
  18782. });
  18783. /**
  18784. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18785. */
  18786. Mesh.prototype.getTotalVertices = function () {
  18787. if (!this._geometry) {
  18788. return 0;
  18789. }
  18790. return this._geometry.getTotalVertices();
  18791. };
  18792. /**
  18793. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18794. * 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.
  18795. * Returns null if the mesh has no geometry or no vertex buffer.
  18796. * Possible `kind` values :
  18797. * - BABYLON.VertexBuffer.PositionKind
  18798. * - BABYLON.VertexBuffer.UVKind
  18799. * - BABYLON.VertexBuffer.UV2Kind
  18800. * - BABYLON.VertexBuffer.UV3Kind
  18801. * - BABYLON.VertexBuffer.UV4Kind
  18802. * - BABYLON.VertexBuffer.UV5Kind
  18803. * - BABYLON.VertexBuffer.UV6Kind
  18804. * - BABYLON.VertexBuffer.ColorKind
  18805. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18806. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18807. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18808. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18809. */
  18810. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18811. if (!this._geometry) {
  18812. return null;
  18813. }
  18814. return this._geometry.getVerticesData(kind, copyWhenShared);
  18815. };
  18816. /**
  18817. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18818. * Returns `undefined` if the mesh has no geometry.
  18819. * Possible `kind` values :
  18820. * - BABYLON.VertexBuffer.PositionKind
  18821. * - BABYLON.VertexBuffer.UVKind
  18822. * - BABYLON.VertexBuffer.UV2Kind
  18823. * - BABYLON.VertexBuffer.UV3Kind
  18824. * - BABYLON.VertexBuffer.UV4Kind
  18825. * - BABYLON.VertexBuffer.UV5Kind
  18826. * - BABYLON.VertexBuffer.UV6Kind
  18827. * - BABYLON.VertexBuffer.ColorKind
  18828. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18829. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18830. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18831. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18832. */
  18833. Mesh.prototype.getVertexBuffer = function (kind) {
  18834. if (!this._geometry) {
  18835. return undefined;
  18836. }
  18837. return this._geometry.getVertexBuffer(kind);
  18838. };
  18839. /**
  18840. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18841. * Possible `kind` values :
  18842. * - BABYLON.VertexBuffer.PositionKind
  18843. * - BABYLON.VertexBuffer.UVKind
  18844. * - BABYLON.VertexBuffer.UV2Kind
  18845. * - BABYLON.VertexBuffer.UV3Kind
  18846. * - BABYLON.VertexBuffer.UV4Kind
  18847. * - BABYLON.VertexBuffer.UV5Kind
  18848. * - BABYLON.VertexBuffer.UV6Kind
  18849. * - BABYLON.VertexBuffer.ColorKind
  18850. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18851. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18852. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18853. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18854. */
  18855. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18856. if (!this._geometry) {
  18857. if (this._delayInfo) {
  18858. return this._delayInfo.indexOf(kind) !== -1;
  18859. }
  18860. return false;
  18861. }
  18862. return this._geometry.isVerticesDataPresent(kind);
  18863. };
  18864. /**
  18865. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18866. * Possible `kind` values :
  18867. * - BABYLON.VertexBuffer.PositionKind
  18868. * - BABYLON.VertexBuffer.UVKind
  18869. * - BABYLON.VertexBuffer.UV2Kind
  18870. * - BABYLON.VertexBuffer.UV3Kind
  18871. * - BABYLON.VertexBuffer.UV4Kind
  18872. * - BABYLON.VertexBuffer.UV5Kind
  18873. * - BABYLON.VertexBuffer.UV6Kind
  18874. * - BABYLON.VertexBuffer.ColorKind
  18875. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18876. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18877. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18878. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18879. */
  18880. Mesh.prototype.getVerticesDataKinds = function () {
  18881. if (!this._geometry) {
  18882. var result = [];
  18883. if (this._delayInfo) {
  18884. for (var kind in this._delayInfo) {
  18885. result.push(kind);
  18886. }
  18887. }
  18888. return result;
  18889. }
  18890. return this._geometry.getVerticesDataKinds();
  18891. };
  18892. /**
  18893. * Returns a positive integer : the total number of indices in this mesh geometry.
  18894. * Returns zero if the mesh has no geometry.
  18895. */
  18896. Mesh.prototype.getTotalIndices = function () {
  18897. if (!this._geometry) {
  18898. return 0;
  18899. }
  18900. return this._geometry.getTotalIndices();
  18901. };
  18902. /**
  18903. * Returns an array of integers or a Int32Array populated with the mesh indices.
  18904. * 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.
  18905. * Returns an empty array if the mesh has no geometry.
  18906. */
  18907. Mesh.prototype.getIndices = function (copyWhenShared) {
  18908. if (!this._geometry) {
  18909. return [];
  18910. }
  18911. return this._geometry.getIndices(copyWhenShared);
  18912. };
  18913. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18914. get: function () {
  18915. return this._masterMesh !== null && this._masterMesh !== undefined;
  18916. },
  18917. enumerable: true,
  18918. configurable: true
  18919. });
  18920. /**
  18921. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18922. */
  18923. Mesh.prototype.isReady = function () {
  18924. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18925. return false;
  18926. }
  18927. return _super.prototype.isReady.call(this);
  18928. };
  18929. /**
  18930. * Boolean : true if the mesh has been disposed.
  18931. */
  18932. Mesh.prototype.isDisposed = function () {
  18933. return this._isDisposed;
  18934. };
  18935. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18936. get: function () {
  18937. return this._sideOrientation;
  18938. },
  18939. /**
  18940. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18941. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18942. */
  18943. set: function (sideO) {
  18944. this._sideOrientation = sideO;
  18945. },
  18946. enumerable: true,
  18947. configurable: true
  18948. });
  18949. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18950. /**
  18951. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18952. * This property is pertinent only for updatable parametric shapes.
  18953. */
  18954. get: function () {
  18955. return this._areNormalsFrozen;
  18956. },
  18957. enumerable: true,
  18958. configurable: true
  18959. });
  18960. /**
  18961. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18962. * It has no effect at all on other shapes.
  18963. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18964. */
  18965. Mesh.prototype.freezeNormals = function () {
  18966. this._areNormalsFrozen = true;
  18967. };
  18968. /**
  18969. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18970. * It has no effect at all on other shapes.
  18971. * It reactivates the mesh normals computation if it was previously frozen.
  18972. */
  18973. Mesh.prototype.unfreezeNormals = function () {
  18974. this._areNormalsFrozen = false;
  18975. };
  18976. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18977. /**
  18978. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18979. */
  18980. set: function (count) {
  18981. this._overridenInstanceCount = count;
  18982. },
  18983. enumerable: true,
  18984. configurable: true
  18985. });
  18986. // Methods
  18987. Mesh.prototype._preActivate = function () {
  18988. var sceneRenderId = this.getScene().getRenderId();
  18989. if (this._preActivateId === sceneRenderId) {
  18990. return;
  18991. }
  18992. this._preActivateId = sceneRenderId;
  18993. this._visibleInstances = null;
  18994. };
  18995. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18996. if (this._visibleInstances) {
  18997. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18998. }
  18999. };
  19000. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19001. if (!this._visibleInstances) {
  19002. this._visibleInstances = {};
  19003. this._visibleInstances.defaultRenderId = renderId;
  19004. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19005. }
  19006. if (!this._visibleInstances[renderId]) {
  19007. this._visibleInstances[renderId] = new Array();
  19008. }
  19009. this._visibleInstances[renderId].push(instance);
  19010. };
  19011. /**
  19012. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19013. * This means the mesh underlying bounding box and sphere are recomputed.
  19014. */
  19015. Mesh.prototype.refreshBoundingInfo = function () {
  19016. if (this._boundingInfo.isLocked) {
  19017. return;
  19018. }
  19019. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19020. if (data) {
  19021. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19022. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19023. }
  19024. if (this.subMeshes) {
  19025. for (var index = 0; index < this.subMeshes.length; index++) {
  19026. this.subMeshes[index].refreshBoundingInfo();
  19027. }
  19028. }
  19029. this._updateBoundingInfo();
  19030. };
  19031. Mesh.prototype._createGlobalSubMesh = function () {
  19032. var totalVertices = this.getTotalVertices();
  19033. if (!totalVertices || !this.getIndices()) {
  19034. return null;
  19035. }
  19036. this.releaseSubMeshes();
  19037. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19038. };
  19039. Mesh.prototype.subdivide = function (count) {
  19040. if (count < 1) {
  19041. return;
  19042. }
  19043. var totalIndices = this.getTotalIndices();
  19044. var subdivisionSize = (totalIndices / count) | 0;
  19045. var offset = 0;
  19046. // Ensure that subdivisionSize is a multiple of 3
  19047. while (subdivisionSize % 3 !== 0) {
  19048. subdivisionSize++;
  19049. }
  19050. this.releaseSubMeshes();
  19051. for (var index = 0; index < count; index++) {
  19052. if (offset >= totalIndices) {
  19053. break;
  19054. }
  19055. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19056. offset += subdivisionSize;
  19057. }
  19058. this.synchronizeInstances();
  19059. };
  19060. /**
  19061. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19062. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19063. * The `data` are either a numeric array either a Float32Array.
  19064. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19065. * 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).
  19066. * Note that a new underlying VertexBuffer object is created each call.
  19067. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19068. *
  19069. * Possible `kind` values :
  19070. * - BABYLON.VertexBuffer.PositionKind
  19071. * - BABYLON.VertexBuffer.UVKind
  19072. * - BABYLON.VertexBuffer.UV2Kind
  19073. * - BABYLON.VertexBuffer.UV3Kind
  19074. * - BABYLON.VertexBuffer.UV4Kind
  19075. * - BABYLON.VertexBuffer.UV5Kind
  19076. * - BABYLON.VertexBuffer.UV6Kind
  19077. * - BABYLON.VertexBuffer.ColorKind
  19078. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19079. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19080. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19081. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19082. */
  19083. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19084. if (!this._geometry) {
  19085. var vertexData = new BABYLON.VertexData();
  19086. vertexData.set(data, kind);
  19087. var scene = this.getScene();
  19088. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19089. }
  19090. else {
  19091. this._geometry.setVerticesData(kind, data, updatable, stride);
  19092. }
  19093. };
  19094. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19095. if (!this._geometry) {
  19096. var scene = this.getScene();
  19097. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19098. }
  19099. this._geometry.setVerticesBuffer(buffer);
  19100. };
  19101. /**
  19102. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19103. * If the mesh has no geometry, it is simply returned as it is.
  19104. * The `data` are either a numeric array either a Float32Array.
  19105. * No new underlying VertexBuffer object is created.
  19106. * 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.
  19107. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19108. *
  19109. * Possible `kind` values :
  19110. * - BABYLON.VertexBuffer.PositionKind
  19111. * - BABYLON.VertexBuffer.UVKind
  19112. * - BABYLON.VertexBuffer.UV2Kind
  19113. * - BABYLON.VertexBuffer.UV3Kind
  19114. * - BABYLON.VertexBuffer.UV4Kind
  19115. * - BABYLON.VertexBuffer.UV5Kind
  19116. * - BABYLON.VertexBuffer.UV6Kind
  19117. * - BABYLON.VertexBuffer.ColorKind
  19118. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19119. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19120. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19121. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19122. */
  19123. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19124. if (!this._geometry) {
  19125. return;
  19126. }
  19127. if (!makeItUnique) {
  19128. this._geometry.updateVerticesData(kind, data, updateExtends);
  19129. }
  19130. else {
  19131. this.makeGeometryUnique();
  19132. this.updateVerticesData(kind, data, updateExtends, false);
  19133. }
  19134. };
  19135. /**
  19136. * Deprecated since BabylonJS v2.3
  19137. */
  19138. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19139. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19140. if (!this._geometry) {
  19141. return;
  19142. }
  19143. if (!makeItUnique) {
  19144. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19145. }
  19146. else {
  19147. this.makeGeometryUnique();
  19148. this.updateVerticesDataDirectly(kind, data, offset, false);
  19149. }
  19150. };
  19151. /**
  19152. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19153. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19154. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19155. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19156. */
  19157. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19158. if (computeNormals === void 0) { computeNormals = true; }
  19159. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19160. positionFunction(positions);
  19161. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19162. if (computeNormals) {
  19163. var indices = this.getIndices();
  19164. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19165. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19166. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19167. }
  19168. };
  19169. Mesh.prototype.makeGeometryUnique = function () {
  19170. if (!this._geometry) {
  19171. return;
  19172. }
  19173. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19174. geometry.applyToMesh(this);
  19175. };
  19176. /**
  19177. * Sets the mesh indices.
  19178. * Expects an array populated with integers or a Int32Array.
  19179. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19180. * This method creates a new index buffer each call.
  19181. */
  19182. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19183. if (!this._geometry) {
  19184. var vertexData = new BABYLON.VertexData();
  19185. vertexData.indices = indices;
  19186. var scene = this.getScene();
  19187. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19188. }
  19189. else {
  19190. this._geometry.setIndices(indices, totalVertices);
  19191. }
  19192. };
  19193. /**
  19194. * Invert the geometry to move from a right handed system to a left handed one.
  19195. */
  19196. Mesh.prototype.toLeftHanded = function () {
  19197. if (!this._geometry) {
  19198. return;
  19199. }
  19200. this._geometry.toLeftHanded();
  19201. };
  19202. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19203. var engine = this.getScene().getEngine();
  19204. // Wireframe
  19205. var indexToBind;
  19206. if (this._unIndexed) {
  19207. indexToBind = null;
  19208. }
  19209. else {
  19210. switch (fillMode) {
  19211. case BABYLON.Material.PointFillMode:
  19212. indexToBind = null;
  19213. break;
  19214. case BABYLON.Material.WireFrameFillMode:
  19215. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19216. break;
  19217. default:
  19218. case BABYLON.Material.TriangleFillMode:
  19219. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19220. break;
  19221. }
  19222. }
  19223. // VBOs
  19224. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19225. };
  19226. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19227. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19228. return;
  19229. }
  19230. this.onBeforeDrawObservable.notifyObservers(this);
  19231. var engine = this.getScene().getEngine();
  19232. // Draw order
  19233. switch (fillMode) {
  19234. case BABYLON.Material.PointFillMode:
  19235. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19236. break;
  19237. case BABYLON.Material.WireFrameFillMode:
  19238. if (this._unIndexed) {
  19239. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19240. }
  19241. else {
  19242. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19243. }
  19244. break;
  19245. default:
  19246. if (this._unIndexed) {
  19247. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19248. }
  19249. else {
  19250. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19251. }
  19252. }
  19253. };
  19254. /**
  19255. * Registers for this mesh a javascript function called just before the rendering process.
  19256. * This function is passed the current mesh and doesn't return anything.
  19257. */
  19258. Mesh.prototype.registerBeforeRender = function (func) {
  19259. this.onBeforeRenderObservable.add(func);
  19260. };
  19261. /**
  19262. * Disposes a previously registered javascript function called before the rendering.
  19263. * This function is passed the current mesh and doesn't return anything.
  19264. */
  19265. Mesh.prototype.unregisterBeforeRender = function (func) {
  19266. this.onBeforeRenderObservable.removeCallback(func);
  19267. };
  19268. /**
  19269. * Registers for this mesh a javascript function called just after the rendering is complete.
  19270. * This function is passed the current mesh and doesn't return anything.
  19271. */
  19272. Mesh.prototype.registerAfterRender = function (func) {
  19273. this.onAfterRenderObservable.add(func);
  19274. };
  19275. /**
  19276. * Disposes a previously registered javascript function called after the rendering.
  19277. * This function is passed the current mesh and doesn't return anything.
  19278. */
  19279. Mesh.prototype.unregisterAfterRender = function (func) {
  19280. this.onAfterRenderObservable.removeCallback(func);
  19281. };
  19282. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19283. var scene = this.getScene();
  19284. this._batchCache.mustReturn = false;
  19285. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19286. this._batchCache.visibleInstances[subMeshId] = null;
  19287. if (this._visibleInstances) {
  19288. var currentRenderId = scene.getRenderId();
  19289. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19290. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19291. var selfRenderId = this._renderId;
  19292. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19293. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19294. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19295. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19296. }
  19297. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19298. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19299. this._batchCache.mustReturn = true;
  19300. return this._batchCache;
  19301. }
  19302. if (currentRenderId !== selfRenderId) {
  19303. this._batchCache.renderSelf[subMeshId] = false;
  19304. }
  19305. }
  19306. this._renderIdForInstances[subMeshId] = currentRenderId;
  19307. }
  19308. return this._batchCache;
  19309. };
  19310. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19311. var visibleInstances = batch.visibleInstances[subMesh._id];
  19312. var matricesCount = visibleInstances.length + 1;
  19313. var bufferSize = matricesCount * 16 * 4;
  19314. var currentInstancesBufferSize = this._instancesBufferSize;
  19315. var instancesBuffer = this._instancesBuffer;
  19316. while (this._instancesBufferSize < bufferSize) {
  19317. this._instancesBufferSize *= 2;
  19318. }
  19319. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19320. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19321. }
  19322. var offset = 0;
  19323. var instancesCount = 0;
  19324. var world = this.getWorldMatrix();
  19325. if (batch.renderSelf[subMesh._id]) {
  19326. world.copyToArray(this._instancesData, offset);
  19327. offset += 16;
  19328. instancesCount++;
  19329. }
  19330. if (visibleInstances) {
  19331. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19332. var instance = visibleInstances[instanceIndex];
  19333. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19334. offset += 16;
  19335. instancesCount++;
  19336. }
  19337. }
  19338. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19339. if (instancesBuffer) {
  19340. instancesBuffer.dispose();
  19341. }
  19342. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19343. this._instancesBuffer = instancesBuffer;
  19344. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19345. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19346. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19347. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19348. }
  19349. else {
  19350. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19351. }
  19352. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  19353. this._draw(subMesh, fillMode, instancesCount);
  19354. engine.unbindInstanceAttributes();
  19355. };
  19356. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19357. var scene = this.getScene();
  19358. var engine = scene.getEngine();
  19359. if (hardwareInstancedRendering) {
  19360. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19361. }
  19362. else {
  19363. if (batch.renderSelf[subMesh._id]) {
  19364. // Draw
  19365. if (onBeforeDraw) {
  19366. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19367. }
  19368. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19369. }
  19370. if (batch.visibleInstances[subMesh._id]) {
  19371. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19372. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19373. // World
  19374. var world = instance.getWorldMatrix();
  19375. if (onBeforeDraw) {
  19376. onBeforeDraw(true, world, effectiveMaterial);
  19377. }
  19378. // Draw
  19379. this._draw(subMesh, fillMode);
  19380. }
  19381. }
  19382. }
  19383. };
  19384. /**
  19385. * Triggers the draw call for the mesh.
  19386. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19387. */
  19388. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19389. var scene = this.getScene();
  19390. // Managing instances
  19391. var batch = this._getInstancesRenderList(subMesh._id);
  19392. if (batch.mustReturn) {
  19393. return;
  19394. }
  19395. // Checking geometry state
  19396. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19397. return;
  19398. }
  19399. var callbackIndex;
  19400. this.onBeforeRenderObservable.notifyObservers(this);
  19401. var engine = scene.getEngine();
  19402. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19403. // Material
  19404. var effectiveMaterial = subMesh.getMaterial();
  19405. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19406. return;
  19407. }
  19408. // Outline - step 1
  19409. var savedDepthWrite = engine.getDepthWrite();
  19410. if (this.renderOutline) {
  19411. engine.setDepthWrite(false);
  19412. scene.getOutlineRenderer().render(subMesh, batch);
  19413. engine.setDepthWrite(savedDepthWrite);
  19414. }
  19415. effectiveMaterial._preBind();
  19416. var effect = effectiveMaterial.getEffect();
  19417. // Bind
  19418. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19419. this._bind(subMesh, effect, fillMode);
  19420. var world = this.getWorldMatrix();
  19421. effectiveMaterial.bind(world, this);
  19422. // Alpha mode
  19423. if (enableAlphaMode) {
  19424. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19425. }
  19426. // Draw
  19427. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  19428. // Unbind
  19429. effectiveMaterial.unbind();
  19430. // Outline - step 2
  19431. if (this.renderOutline && savedDepthWrite) {
  19432. engine.setDepthWrite(true);
  19433. engine.setColorWrite(false);
  19434. scene.getOutlineRenderer().render(subMesh, batch);
  19435. engine.setColorWrite(true);
  19436. }
  19437. // Overlay
  19438. if (this.renderOverlay) {
  19439. var currentMode = engine.getAlphaMode();
  19440. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19441. scene.getOutlineRenderer().render(subMesh, batch, true);
  19442. engine.setAlphaMode(currentMode);
  19443. }
  19444. this.onAfterRenderObservable.notifyObservers(this);
  19445. };
  19446. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19447. if (isInstance) {
  19448. effectiveMaterial.bindOnlyWorldMatrix(world);
  19449. }
  19450. };
  19451. /**
  19452. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19453. */
  19454. Mesh.prototype.getEmittedParticleSystems = function () {
  19455. var results = new Array();
  19456. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19457. var particleSystem = this.getScene().particleSystems[index];
  19458. if (particleSystem.emitter === this) {
  19459. results.push(particleSystem);
  19460. }
  19461. }
  19462. return results;
  19463. };
  19464. /**
  19465. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19466. */
  19467. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19468. var results = new Array();
  19469. var descendants = this.getDescendants();
  19470. descendants.push(this);
  19471. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19472. var particleSystem = this.getScene().particleSystems[index];
  19473. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19474. results.push(particleSystem);
  19475. }
  19476. }
  19477. return results;
  19478. };
  19479. Mesh.prototype._checkDelayState = function () {
  19480. var scene = this.getScene();
  19481. if (this._geometry) {
  19482. this._geometry.load(scene);
  19483. }
  19484. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19485. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19486. this._queueLoad(this, scene);
  19487. }
  19488. };
  19489. Mesh.prototype._queueLoad = function (mesh, scene) {
  19490. var _this = this;
  19491. scene._addPendingData(mesh);
  19492. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19493. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19494. if (data instanceof ArrayBuffer) {
  19495. _this._delayLoadingFunction(data, _this);
  19496. }
  19497. else {
  19498. _this._delayLoadingFunction(JSON.parse(data), _this);
  19499. }
  19500. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19501. scene._removePendingData(_this);
  19502. }, function () { }, scene.database, getBinaryData);
  19503. };
  19504. /**
  19505. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19506. */
  19507. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19508. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19509. return false;
  19510. }
  19511. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19512. return false;
  19513. }
  19514. this._checkDelayState();
  19515. return true;
  19516. };
  19517. /**
  19518. * Sets the mesh material by the material or multiMaterial `id` property.
  19519. * The material `id` is a string identifying the material or the multiMaterial.
  19520. * This method returns nothing.
  19521. */
  19522. Mesh.prototype.setMaterialByID = function (id) {
  19523. var materials = this.getScene().materials;
  19524. var index;
  19525. for (index = 0; index < materials.length; index++) {
  19526. if (materials[index].id === id) {
  19527. this.material = materials[index];
  19528. return;
  19529. }
  19530. }
  19531. // Multi
  19532. var multiMaterials = this.getScene().multiMaterials;
  19533. for (index = 0; index < multiMaterials.length; index++) {
  19534. if (multiMaterials[index].id === id) {
  19535. this.material = multiMaterials[index];
  19536. return;
  19537. }
  19538. }
  19539. };
  19540. /**
  19541. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19542. */
  19543. Mesh.prototype.getAnimatables = function () {
  19544. var results = [];
  19545. if (this.material) {
  19546. results.push(this.material);
  19547. }
  19548. if (this.skeleton) {
  19549. results.push(this.skeleton);
  19550. }
  19551. return results;
  19552. };
  19553. /**
  19554. * Modifies the mesh geometry according to the passed transformation matrix.
  19555. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19556. * The mesh normals are modified accordingly the same transformation.
  19557. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19558. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19559. */
  19560. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19561. // Position
  19562. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19563. return;
  19564. }
  19565. var submeshes = this.subMeshes.splice(0);
  19566. this._resetPointsArrayCache();
  19567. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19568. var temp = [];
  19569. var index;
  19570. for (index = 0; index < data.length; index += 3) {
  19571. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19572. }
  19573. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19574. // Normals
  19575. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19576. return;
  19577. }
  19578. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19579. temp = [];
  19580. for (index = 0; index < data.length; index += 3) {
  19581. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19582. }
  19583. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19584. // flip faces?
  19585. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19586. this.flipFaces();
  19587. }
  19588. // Restore submeshes
  19589. this.releaseSubMeshes();
  19590. this.subMeshes = submeshes;
  19591. };
  19592. /**
  19593. * Modifies the mesh geometry according to its own current World Matrix.
  19594. * The mesh World Matrix is then reset.
  19595. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19596. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19597. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19598. */
  19599. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19600. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19601. this.scaling.copyFromFloats(1, 1, 1);
  19602. this.position.copyFromFloats(0, 0, 0);
  19603. this.rotation.copyFromFloats(0, 0, 0);
  19604. //only if quaternion is already set
  19605. if (this.rotationQuaternion) {
  19606. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19607. }
  19608. this._worldMatrix = BABYLON.Matrix.Identity();
  19609. };
  19610. // Cache
  19611. Mesh.prototype._resetPointsArrayCache = function () {
  19612. this._positions = null;
  19613. };
  19614. Mesh.prototype._generatePointsArray = function () {
  19615. if (this._positions)
  19616. return true;
  19617. this._positions = [];
  19618. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19619. if (!data) {
  19620. return false;
  19621. }
  19622. for (var index = 0; index < data.length; index += 3) {
  19623. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19624. }
  19625. return true;
  19626. };
  19627. /**
  19628. * Returns a new Mesh object generated from the current mesh properties.
  19629. * This method must not get confused with createInstance().
  19630. * The parameter `name` is a string, the name given to the new mesh.
  19631. * The optional parameter `newParent` can be any Node object (default `null`).
  19632. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19633. * 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.
  19634. */
  19635. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19636. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19637. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19638. };
  19639. /**
  19640. * Disposes the mesh.
  19641. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19642. */
  19643. Mesh.prototype.dispose = function (doNotRecurse) {
  19644. if (this._geometry) {
  19645. this._geometry.releaseForMesh(this, true);
  19646. }
  19647. // Instances
  19648. if (this._instancesBuffer) {
  19649. this._instancesBuffer.dispose();
  19650. this._instancesBuffer = null;
  19651. }
  19652. while (this.instances.length) {
  19653. this.instances[0].dispose();
  19654. }
  19655. _super.prototype.dispose.call(this, doNotRecurse);
  19656. };
  19657. /**
  19658. * Modifies the mesh geometry according to a displacement map.
  19659. * 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.
  19660. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19661. * This method returns nothing.
  19662. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19663. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19664. * 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.
  19665. */
  19666. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  19667. var _this = this;
  19668. var scene = this.getScene();
  19669. var onload = function (img) {
  19670. // Getting height map data
  19671. var canvas = document.createElement("canvas");
  19672. var context = canvas.getContext("2d");
  19673. var heightMapWidth = img.width;
  19674. var heightMapHeight = img.height;
  19675. canvas.width = heightMapWidth;
  19676. canvas.height = heightMapHeight;
  19677. context.drawImage(img, 0, 0);
  19678. // Create VertexData from map data
  19679. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19680. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19681. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  19682. //execute success callback, if set
  19683. if (onSuccess) {
  19684. onSuccess(_this);
  19685. }
  19686. };
  19687. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19688. };
  19689. /**
  19690. * Modifies the mesh geometry according to a displacementMap buffer.
  19691. * 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.
  19692. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19693. * This method returns nothing.
  19694. * 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.
  19695. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19696. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19697. */
  19698. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  19699. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19700. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19701. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19702. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19703. return;
  19704. }
  19705. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19706. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19707. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19708. var position = BABYLON.Vector3.Zero();
  19709. var normal = BABYLON.Vector3.Zero();
  19710. var uv = BABYLON.Vector2.Zero();
  19711. for (var index = 0; index < positions.length; index += 3) {
  19712. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19713. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19714. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19715. // Compute height
  19716. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  19717. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  19718. var pos = (u + v * heightMapWidth) * 4;
  19719. var r = buffer[pos] / 255.0;
  19720. var g = buffer[pos + 1] / 255.0;
  19721. var b = buffer[pos + 2] / 255.0;
  19722. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19723. normal.normalize();
  19724. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19725. position = position.add(normal);
  19726. position.toArray(positions, index);
  19727. }
  19728. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19729. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19730. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19731. };
  19732. /**
  19733. * Modify the mesh to get a flat shading rendering.
  19734. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19735. * This method returns nothing.
  19736. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19737. */
  19738. Mesh.prototype.convertToFlatShadedMesh = function () {
  19739. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19740. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19741. var kinds = this.getVerticesDataKinds();
  19742. var vbs = [];
  19743. var data = [];
  19744. var newdata = [];
  19745. var updatableNormals = false;
  19746. var kindIndex;
  19747. var kind;
  19748. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19749. kind = kinds[kindIndex];
  19750. var vertexBuffer = this.getVertexBuffer(kind);
  19751. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19752. updatableNormals = vertexBuffer.isUpdatable();
  19753. kinds.splice(kindIndex, 1);
  19754. kindIndex--;
  19755. continue;
  19756. }
  19757. vbs[kind] = vertexBuffer;
  19758. data[kind] = vbs[kind].getData();
  19759. newdata[kind] = [];
  19760. }
  19761. // Save previous submeshes
  19762. var previousSubmeshes = this.subMeshes.slice(0);
  19763. var indices = this.getIndices();
  19764. var totalIndices = this.getTotalIndices();
  19765. // Generating unique vertices per face
  19766. var index;
  19767. for (index = 0; index < totalIndices; index++) {
  19768. var vertexIndex = indices[index];
  19769. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19770. kind = kinds[kindIndex];
  19771. var stride = vbs[kind].getStrideSize();
  19772. for (var offset = 0; offset < stride; offset++) {
  19773. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19774. }
  19775. }
  19776. }
  19777. // Updating faces & normal
  19778. var normals = [];
  19779. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19780. for (index = 0; index < totalIndices; index += 3) {
  19781. indices[index] = index;
  19782. indices[index + 1] = index + 1;
  19783. indices[index + 2] = index + 2;
  19784. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19785. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19786. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19787. var p1p2 = p1.subtract(p2);
  19788. var p3p2 = p3.subtract(p2);
  19789. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19790. // Store same normals for every vertex
  19791. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19792. normals.push(normal.x);
  19793. normals.push(normal.y);
  19794. normals.push(normal.z);
  19795. }
  19796. }
  19797. this.setIndices(indices);
  19798. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19799. // Updating vertex buffers
  19800. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19801. kind = kinds[kindIndex];
  19802. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19803. }
  19804. // Updating submeshes
  19805. this.releaseSubMeshes();
  19806. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19807. var previousOne = previousSubmeshes[submeshIndex];
  19808. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19809. }
  19810. this.synchronizeInstances();
  19811. };
  19812. /**
  19813. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19814. * In other words, more vertices, no more indices and a single bigger VBO.
  19815. * This method returns nothing.
  19816. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19817. *
  19818. */
  19819. Mesh.prototype.convertToUnIndexedMesh = function () {
  19820. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19821. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19822. var kinds = this.getVerticesDataKinds();
  19823. var vbs = [];
  19824. var data = [];
  19825. var newdata = [];
  19826. var updatableNormals = false;
  19827. var kindIndex;
  19828. var kind;
  19829. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19830. kind = kinds[kindIndex];
  19831. var vertexBuffer = this.getVertexBuffer(kind);
  19832. vbs[kind] = vertexBuffer;
  19833. data[kind] = vbs[kind].getData();
  19834. newdata[kind] = [];
  19835. }
  19836. // Save previous submeshes
  19837. var previousSubmeshes = this.subMeshes.slice(0);
  19838. var indices = this.getIndices();
  19839. var totalIndices = this.getTotalIndices();
  19840. // Generating unique vertices per face
  19841. var index;
  19842. for (index = 0; index < totalIndices; index++) {
  19843. var vertexIndex = indices[index];
  19844. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19845. kind = kinds[kindIndex];
  19846. var stride = vbs[kind].getStrideSize();
  19847. for (var offset = 0; offset < stride; offset++) {
  19848. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19849. }
  19850. }
  19851. }
  19852. // Updating indices
  19853. for (index = 0; index < totalIndices; index += 3) {
  19854. indices[index] = index;
  19855. indices[index + 1] = index + 1;
  19856. indices[index + 2] = index + 2;
  19857. }
  19858. this.setIndices(indices);
  19859. // Updating vertex buffers
  19860. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19861. kind = kinds[kindIndex];
  19862. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19863. }
  19864. // Updating submeshes
  19865. this.releaseSubMeshes();
  19866. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19867. var previousOne = previousSubmeshes[submeshIndex];
  19868. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19869. }
  19870. this._unIndexed = true;
  19871. this.synchronizeInstances();
  19872. };
  19873. /**
  19874. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19875. * This method returns nothing.
  19876. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19877. */
  19878. Mesh.prototype.flipFaces = function (flipNormals) {
  19879. if (flipNormals === void 0) { flipNormals = false; }
  19880. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19881. var i;
  19882. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19883. for (i = 0; i < vertex_data.normals.length; i++) {
  19884. vertex_data.normals[i] *= -1;
  19885. }
  19886. }
  19887. var temp;
  19888. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19889. // reassign indices
  19890. temp = vertex_data.indices[i + 1];
  19891. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19892. vertex_data.indices[i + 2] = temp;
  19893. }
  19894. vertex_data.applyToMesh(this);
  19895. };
  19896. // Instances
  19897. /**
  19898. * Creates a new InstancedMesh object from the mesh model.
  19899. * An instance shares the same properties and the same material than its model.
  19900. * Only these properties of each instance can then be set individually :
  19901. * - position
  19902. * - rotation
  19903. * - rotationQuaternion
  19904. * - setPivotMatrix
  19905. * - scaling
  19906. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19907. * Warning : this method is not supported for Line mesh and LineSystem
  19908. */
  19909. Mesh.prototype.createInstance = function (name) {
  19910. return new BABYLON.InstancedMesh(name, this);
  19911. };
  19912. /**
  19913. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19914. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19915. * This method returns nothing.
  19916. */
  19917. Mesh.prototype.synchronizeInstances = function () {
  19918. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19919. var instance = this.instances[instanceIndex];
  19920. instance._syncSubMeshes();
  19921. }
  19922. };
  19923. /**
  19924. * Simplify the mesh according to the given array of settings.
  19925. * Function will return immediately and will simplify async. It returns nothing.
  19926. * @param settings a collection of simplification settings.
  19927. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19928. * @param type the type of simplification to run.
  19929. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19930. */
  19931. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19932. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19933. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19934. this.getScene().simplificationQueue.addTask({
  19935. settings: settings,
  19936. parallelProcessing: parallelProcessing,
  19937. mesh: this,
  19938. simplificationType: simplificationType,
  19939. successCallback: successCallback
  19940. });
  19941. };
  19942. /**
  19943. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19944. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19945. * This should be used together with the simplification to avoid disappearing triangles.
  19946. * @param successCallback an optional success callback to be called after the optimization finished.
  19947. */
  19948. Mesh.prototype.optimizeIndices = function (successCallback) {
  19949. var _this = this;
  19950. var indices = this.getIndices();
  19951. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19952. var vectorPositions = [];
  19953. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19954. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19955. }
  19956. var dupes = [];
  19957. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19958. var realPos = vectorPositions.length - 1 - iteration;
  19959. var testedPosition = vectorPositions[realPos];
  19960. for (var j = 0; j < realPos; ++j) {
  19961. var againstPosition = vectorPositions[j];
  19962. if (testedPosition.equals(againstPosition)) {
  19963. dupes[realPos] = j;
  19964. break;
  19965. }
  19966. }
  19967. }, function () {
  19968. for (var i = 0; i < indices.length; ++i) {
  19969. indices[i] = dupes[indices[i]] || indices[i];
  19970. }
  19971. //indices are now reordered
  19972. var originalSubMeshes = _this.subMeshes.slice(0);
  19973. _this.setIndices(indices);
  19974. _this.subMeshes = originalSubMeshes;
  19975. if (successCallback) {
  19976. successCallback(_this);
  19977. }
  19978. });
  19979. };
  19980. // Statics
  19981. /**
  19982. * Returns a new Mesh object what is a deep copy of the passed mesh.
  19983. * The parameter `parsedMesh` is the mesh to be copied.
  19984. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19985. */
  19986. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  19987. var mesh = new Mesh(parsedMesh.name, scene);
  19988. mesh.id = parsedMesh.id;
  19989. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19990. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19991. if (parsedMesh.rotationQuaternion) {
  19992. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19993. }
  19994. else if (parsedMesh.rotation) {
  19995. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19996. }
  19997. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19998. if (parsedMesh.localMatrix) {
  19999. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20000. }
  20001. else if (parsedMesh.pivotMatrix) {
  20002. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20003. }
  20004. mesh.setEnabled(parsedMesh.isEnabled);
  20005. mesh.isVisible = parsedMesh.isVisible;
  20006. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20007. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20008. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20009. if (parsedMesh.applyFog !== undefined) {
  20010. mesh.applyFog = parsedMesh.applyFog;
  20011. }
  20012. if (parsedMesh.pickable !== undefined) {
  20013. mesh.isPickable = parsedMesh.pickable;
  20014. }
  20015. if (parsedMesh.alphaIndex !== undefined) {
  20016. mesh.alphaIndex = parsedMesh.alphaIndex;
  20017. }
  20018. mesh.receiveShadows = parsedMesh.receiveShadows;
  20019. mesh.billboardMode = parsedMesh.billboardMode;
  20020. if (parsedMesh.visibility !== undefined) {
  20021. mesh.visibility = parsedMesh.visibility;
  20022. }
  20023. mesh.checkCollisions = parsedMesh.checkCollisions;
  20024. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20025. // freezeWorldMatrix
  20026. if (parsedMesh.freezeWorldMatrix) {
  20027. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20028. }
  20029. // Parent
  20030. if (parsedMesh.parentId) {
  20031. mesh._waitingParentId = parsedMesh.parentId;
  20032. }
  20033. // Actions
  20034. if (parsedMesh.actions !== undefined) {
  20035. mesh._waitingActions = parsedMesh.actions;
  20036. }
  20037. // Geometry
  20038. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20039. if (parsedMesh.delayLoadingFile) {
  20040. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20041. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20042. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20043. if (parsedMesh._binaryInfo) {
  20044. mesh._binaryInfo = parsedMesh._binaryInfo;
  20045. }
  20046. mesh._delayInfo = [];
  20047. if (parsedMesh.hasUVs) {
  20048. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20049. }
  20050. if (parsedMesh.hasUVs2) {
  20051. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20052. }
  20053. if (parsedMesh.hasUVs3) {
  20054. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20055. }
  20056. if (parsedMesh.hasUVs4) {
  20057. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20058. }
  20059. if (parsedMesh.hasUVs5) {
  20060. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20061. }
  20062. if (parsedMesh.hasUVs6) {
  20063. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20064. }
  20065. if (parsedMesh.hasColors) {
  20066. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20067. }
  20068. if (parsedMesh.hasMatricesIndices) {
  20069. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20070. }
  20071. if (parsedMesh.hasMatricesWeights) {
  20072. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20073. }
  20074. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20075. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20076. mesh._checkDelayState();
  20077. }
  20078. }
  20079. else {
  20080. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20081. }
  20082. // Material
  20083. if (parsedMesh.materialId) {
  20084. mesh.setMaterialByID(parsedMesh.materialId);
  20085. }
  20086. else {
  20087. mesh.material = null;
  20088. }
  20089. // Skeleton
  20090. if (parsedMesh.skeletonId > -1) {
  20091. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20092. if (parsedMesh.numBoneInfluencers) {
  20093. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20094. }
  20095. }
  20096. // Animations
  20097. if (parsedMesh.animations) {
  20098. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20099. var parsedAnimation = parsedMesh.animations[animationIndex];
  20100. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20101. }
  20102. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20103. }
  20104. if (parsedMesh.autoAnimate) {
  20105. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20106. }
  20107. // Layer Mask
  20108. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20109. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20110. }
  20111. else {
  20112. mesh.layerMask = 0x0FFFFFFF;
  20113. }
  20114. //(Deprecated) physics
  20115. if (parsedMesh.physicsImpostor) {
  20116. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20117. mass: parsedMesh.physicsMass,
  20118. friction: parsedMesh.physicsFriction,
  20119. restitution: parsedMesh.physicsRestitution
  20120. }, scene);
  20121. }
  20122. // Instances
  20123. if (parsedMesh.instances) {
  20124. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20125. var parsedInstance = parsedMesh.instances[index];
  20126. var instance = mesh.createInstance(parsedInstance.name);
  20127. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20128. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20129. if (parsedInstance.rotationQuaternion) {
  20130. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20131. }
  20132. else if (parsedInstance.rotation) {
  20133. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20134. }
  20135. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20136. instance.checkCollisions = mesh.checkCollisions;
  20137. if (parsedMesh.animations) {
  20138. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20139. parsedAnimation = parsedMesh.animations[animationIndex];
  20140. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20141. }
  20142. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20143. }
  20144. }
  20145. }
  20146. return mesh;
  20147. };
  20148. /**
  20149. * Creates a ribbon mesh.
  20150. * Please consider using the same method from the MeshBuilder class instead.
  20151. * 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.
  20152. *
  20153. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20154. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20155. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20156. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20157. * 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.
  20158. * 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.
  20159. * 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
  20160. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20161. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20162. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20163. */
  20164. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20165. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20166. pathArray: pathArray,
  20167. closeArray: closeArray,
  20168. closePath: closePath,
  20169. offset: offset,
  20170. updatable: updatable,
  20171. sideOrientation: sideOrientation,
  20172. instance: instance
  20173. }, scene);
  20174. };
  20175. /**
  20176. * Creates a plane polygonal mesh. By default, this is a disc.
  20177. * Please consider using the same method from the MeshBuilder class instead.
  20178. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20179. * 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.
  20180. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20181. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20183. */
  20184. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20185. var options = {
  20186. radius: radius,
  20187. tessellation: tessellation,
  20188. sideOrientation: sideOrientation,
  20189. updatable: updatable
  20190. };
  20191. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20192. };
  20193. /**
  20194. * Creates a box mesh.
  20195. * Please consider using the same method from the MeshBuilder class instead.
  20196. * The parameter `size` sets the size (float) of each box side (default 1).
  20197. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20198. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20199. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20200. */
  20201. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20202. var options = {
  20203. size: size,
  20204. sideOrientation: sideOrientation,
  20205. updatable: updatable
  20206. };
  20207. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20208. };
  20209. /**
  20210. * Creates a sphere mesh.
  20211. * Please consider using the same method from the MeshBuilder class instead.
  20212. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20213. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20214. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20215. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20216. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20217. */
  20218. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20219. var options = {
  20220. segments: segments,
  20221. diameterX: diameter,
  20222. diameterY: diameter,
  20223. diameterZ: diameter,
  20224. sideOrientation: sideOrientation,
  20225. updatable: updatable
  20226. };
  20227. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20228. };
  20229. /**
  20230. * Creates a cylinder or a cone mesh.
  20231. * Please consider using the same method from the MeshBuilder class instead.
  20232. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20233. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20234. * 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.
  20235. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20236. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20237. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20238. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20240. */
  20241. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20242. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20243. if (scene !== undefined) {
  20244. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20245. updatable = scene;
  20246. }
  20247. scene = subdivisions;
  20248. subdivisions = 1;
  20249. }
  20250. var options = {
  20251. height: height,
  20252. diameterTop: diameterTop,
  20253. diameterBottom: diameterBottom,
  20254. tessellation: tessellation,
  20255. subdivisions: subdivisions,
  20256. sideOrientation: sideOrientation,
  20257. updatable: updatable
  20258. };
  20259. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20260. };
  20261. // Torus (Code from SharpDX.org)
  20262. /**
  20263. * Creates a torus mesh.
  20264. * Please consider using the same method from the MeshBuilder class instead.
  20265. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20266. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20267. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20268. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20269. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20270. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20271. */
  20272. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20273. var options = {
  20274. diameter: diameter,
  20275. thickness: thickness,
  20276. tessellation: tessellation,
  20277. sideOrientation: sideOrientation,
  20278. updatable: updatable
  20279. };
  20280. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20281. };
  20282. /**
  20283. * Creates a torus knot mesh.
  20284. * Please consider using the same method from the MeshBuilder class instead.
  20285. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20286. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20287. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20288. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20289. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20290. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20291. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20292. */
  20293. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20294. var options = {
  20295. radius: radius,
  20296. tube: tube,
  20297. radialSegments: radialSegments,
  20298. tubularSegments: tubularSegments,
  20299. p: p,
  20300. q: q,
  20301. sideOrientation: sideOrientation,
  20302. updatable: updatable
  20303. };
  20304. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20305. };
  20306. /**
  20307. * Creates a line mesh.
  20308. * Please consider using the same method from the MeshBuilder class instead.
  20309. * 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.
  20310. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20311. * The parameter `points` is an array successive Vector3.
  20312. * 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
  20313. * When updating an instance, remember that only point positions can change, not the number of points.
  20314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20315. */
  20316. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20317. var options = {
  20318. points: points,
  20319. updatable: updatable,
  20320. instance: instance
  20321. };
  20322. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20323. };
  20324. /**
  20325. * Creates a dashed line mesh.
  20326. * Please consider using the same method from the MeshBuilder class instead.
  20327. * 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.
  20328. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20329. * The parameter `points` is an array successive Vector3.
  20330. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20331. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20332. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20333. * 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
  20334. * When updating an instance, remember that only point positions can change, not the number of points.
  20335. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20336. */
  20337. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20338. var options = {
  20339. points: points,
  20340. dashSize: dashSize,
  20341. gapSize: gapSize,
  20342. dashNb: dashNb,
  20343. updatable: updatable,
  20344. instance: instance
  20345. };
  20346. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20347. };
  20348. /**
  20349. * Creates an extruded shape mesh.
  20350. * 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.
  20351. * Please consider using the same method from the MeshBuilder class instead.
  20352. *
  20353. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20354. * 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
  20355. * extruded along the Z axis.
  20356. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20357. * 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.
  20358. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20359. * 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
  20360. * 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
  20361. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20362. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20363. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20365. */
  20366. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20367. var options = {
  20368. shape: shape,
  20369. path: path,
  20370. scale: scale,
  20371. rotation: rotation,
  20372. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20373. sideOrientation: sideOrientation,
  20374. instance: instance,
  20375. updatable: updatable
  20376. };
  20377. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20378. };
  20379. /**
  20380. * Creates an custom extruded shape mesh.
  20381. * 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.
  20382. * Please consider using the same method from the MeshBuilder class instead.
  20383. *
  20384. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20385. * 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
  20386. * extruded along the Z axis.
  20387. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20388. * 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
  20389. * and the distance of this point from the begining of the path :
  20390. * ```javascript
  20391. * var rotationFunction = function(i, distance) {
  20392. * // do things
  20393. * return rotationValue; }
  20394. * ```
  20395. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20396. * 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
  20397. * and the distance of this point from the begining of the path :
  20398. * ```javascript
  20399. * var scaleFunction = function(i, distance) {
  20400. * // do things
  20401. * return scaleValue;}
  20402. * ```
  20403. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20404. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20405. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20406. * 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
  20407. * 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
  20408. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20409. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20410. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20412. */
  20413. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20414. var options = {
  20415. shape: shape,
  20416. path: path,
  20417. scaleFunction: scaleFunction,
  20418. rotationFunction: rotationFunction,
  20419. ribbonCloseArray: ribbonCloseArray,
  20420. ribbonClosePath: ribbonClosePath,
  20421. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20422. sideOrientation: sideOrientation,
  20423. instance: instance,
  20424. updatable: updatable
  20425. };
  20426. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20427. };
  20428. /**
  20429. * Creates lathe mesh.
  20430. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20431. * Please consider using the same method from the MeshBuilder class instead.
  20432. * 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
  20433. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20434. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20435. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20436. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20437. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20439. */
  20440. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20441. var options = {
  20442. shape: shape,
  20443. radius: radius,
  20444. tessellation: tessellation,
  20445. sideOrientation: sideOrientation,
  20446. updatable: updatable
  20447. };
  20448. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20449. };
  20450. /**
  20451. * Creates a plane mesh.
  20452. * Please consider using the same method from the MeshBuilder class instead.
  20453. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20454. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20455. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20456. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20457. */
  20458. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20459. var options = {
  20460. size: size,
  20461. width: size,
  20462. height: size,
  20463. sideOrientation: sideOrientation,
  20464. updatable: updatable
  20465. };
  20466. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20467. };
  20468. /**
  20469. * Creates a ground mesh.
  20470. * Please consider using the same method from the MeshBuilder class instead.
  20471. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20472. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20474. */
  20475. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20476. var options = {
  20477. width: width,
  20478. height: height,
  20479. subdivisions: subdivisions,
  20480. updatable: updatable
  20481. };
  20482. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20483. };
  20484. /**
  20485. * Creates a tiled ground mesh.
  20486. * Please consider using the same method from the MeshBuilder class instead.
  20487. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20488. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20489. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20490. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20491. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20492. * numbers of subdivisions on the ground width and height of each tile.
  20493. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20494. */
  20495. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20496. var options = {
  20497. xmin: xmin,
  20498. zmin: zmin,
  20499. xmax: xmax,
  20500. zmax: zmax,
  20501. subdivisions: subdivisions,
  20502. precision: precision,
  20503. updatable: updatable
  20504. };
  20505. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20506. };
  20507. /**
  20508. * Creates a ground mesh from a height map.
  20509. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20510. * Please consider using the same method from the MeshBuilder class instead.
  20511. * The parameter `url` sets the URL of the height map image resource.
  20512. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20513. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20514. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20515. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20516. * 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).
  20517. * This function is passed the newly built mesh :
  20518. * ```javascript
  20519. * function(mesh) { // do things
  20520. * return; }
  20521. * ```
  20522. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20523. */
  20524. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20525. var options = {
  20526. width: width,
  20527. height: height,
  20528. subdivisions: subdivisions,
  20529. minHeight: minHeight,
  20530. maxHeight: maxHeight,
  20531. updatable: updatable,
  20532. onReady: onReady
  20533. };
  20534. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20535. };
  20536. /**
  20537. * Creates a tube mesh.
  20538. * 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.
  20539. * Please consider using the same method from the MeshBuilder class instead.
  20540. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20541. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20542. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20543. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20544. * 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.
  20545. * It must return a radius value (positive float) :
  20546. * ```javascript
  20547. * var radiusFunction = function(i, distance) {
  20548. * // do things
  20549. * return radius; }
  20550. * ```
  20551. * 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
  20552. * 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
  20553. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20554. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20556. */
  20557. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20558. var options = {
  20559. path: path,
  20560. radius: radius,
  20561. tessellation: tessellation,
  20562. radiusFunction: radiusFunction,
  20563. arc: 1,
  20564. cap: cap,
  20565. updatable: updatable,
  20566. sideOrientation: sideOrientation,
  20567. instance: instance
  20568. };
  20569. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20570. };
  20571. /**
  20572. * Creates a polyhedron mesh.
  20573. * Please consider using the same method from the MeshBuilder class instead.
  20574. * 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
  20575. * to choose the wanted type.
  20576. * The parameter `size` (positive float, default 1) sets the polygon size.
  20577. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20578. * 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`.
  20579. * 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
  20580. * 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)`).
  20581. * 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
  20582. * 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.
  20583. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20584. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20586. */
  20587. Mesh.CreatePolyhedron = function (name, options, scene) {
  20588. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20589. };
  20590. /**
  20591. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20592. * Please consider using the same method from the MeshBuilder class instead.
  20593. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20594. * 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`).
  20595. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20596. * 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.
  20597. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20598. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20599. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20600. */
  20601. Mesh.CreateIcoSphere = function (name, options, scene) {
  20602. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20603. };
  20604. /**
  20605. * Creates a decal mesh.
  20606. * Please consider using the same method from the MeshBuilder class instead.
  20607. * 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.
  20608. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20609. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20610. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20611. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20612. */
  20613. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20614. var options = {
  20615. position: position,
  20616. normal: normal,
  20617. size: size,
  20618. angle: angle
  20619. };
  20620. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20621. };
  20622. // Skeletons
  20623. /**
  20624. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20625. */
  20626. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20627. var source;
  20628. if (!this._sourcePositions) {
  20629. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20630. this._sourcePositions = new Float32Array(source);
  20631. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20632. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20633. }
  20634. }
  20635. return this._sourcePositions;
  20636. };
  20637. /**
  20638. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20639. */
  20640. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20641. var source;
  20642. if (!this._sourceNormals) {
  20643. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20644. this._sourceNormals = new Float32Array(source);
  20645. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20646. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20647. }
  20648. }
  20649. return this._sourceNormals;
  20650. };
  20651. /**
  20652. * Update the vertex buffers by applying transformation from the bones
  20653. * @param {skeleton} skeleton to apply
  20654. */
  20655. Mesh.prototype.applySkeleton = function (skeleton) {
  20656. if (!this.geometry) {
  20657. return;
  20658. }
  20659. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20660. return;
  20661. }
  20662. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20663. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20664. return this;
  20665. }
  20666. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20667. return this;
  20668. }
  20669. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20670. return this;
  20671. }
  20672. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20673. return this;
  20674. }
  20675. if (!this._sourcePositions) {
  20676. this.setPositionsForCPUSkinning();
  20677. }
  20678. if (!this._sourceNormals) {
  20679. this.setNormalsForCPUSkinning();
  20680. }
  20681. // positionsData checks for not being Float32Array will only pass at most once
  20682. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20683. if (!(positionsData instanceof Float32Array)) {
  20684. positionsData = new Float32Array(positionsData);
  20685. }
  20686. // normalsData checks for not being Float32Array will only pass at most once
  20687. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20688. if (!(normalsData instanceof Float32Array)) {
  20689. normalsData = new Float32Array(normalsData);
  20690. }
  20691. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20692. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20693. var needExtras = this.numBoneInfluencers > 4;
  20694. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20695. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20696. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20697. var tempVector3 = BABYLON.Vector3.Zero();
  20698. var finalMatrix = new BABYLON.Matrix();
  20699. var tempMatrix = new BABYLON.Matrix();
  20700. var matWeightIdx = 0;
  20701. var inf;
  20702. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20703. var weight;
  20704. for (inf = 0; inf < 4; inf++) {
  20705. weight = matricesWeightsData[matWeightIdx + inf];
  20706. if (weight > 0) {
  20707. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20708. finalMatrix.addToSelf(tempMatrix);
  20709. }
  20710. else
  20711. break;
  20712. }
  20713. if (needExtras) {
  20714. for (inf = 0; inf < 4; inf++) {
  20715. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20716. if (weight > 0) {
  20717. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20718. finalMatrix.addToSelf(tempMatrix);
  20719. }
  20720. else
  20721. break;
  20722. }
  20723. }
  20724. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20725. tempVector3.toArray(positionsData, index);
  20726. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20727. tempVector3.toArray(normalsData, index);
  20728. finalMatrix.reset();
  20729. }
  20730. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20731. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20732. return this;
  20733. };
  20734. // Tools
  20735. /**
  20736. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20737. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20738. */
  20739. Mesh.MinMax = function (meshes) {
  20740. var minVector = null;
  20741. var maxVector = null;
  20742. for (var i in meshes) {
  20743. var mesh = meshes[i];
  20744. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20745. if (!minVector) {
  20746. minVector = boundingBox.minimumWorld;
  20747. maxVector = boundingBox.maximumWorld;
  20748. continue;
  20749. }
  20750. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20751. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20752. }
  20753. return {
  20754. min: minVector,
  20755. max: maxVector
  20756. };
  20757. };
  20758. /**
  20759. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20760. */
  20761. Mesh.Center = function (meshesOrMinMaxVector) {
  20762. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  20763. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20764. };
  20765. /**
  20766. * Merge the array of meshes into a single mesh for performance reasons.
  20767. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20768. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20769. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20770. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20771. */
  20772. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  20773. if (disposeSource === void 0) { disposeSource = true; }
  20774. var index;
  20775. if (!allow32BitsIndices) {
  20776. var totalVertices = 0;
  20777. // Counting vertices
  20778. for (index = 0; index < meshes.length; index++) {
  20779. if (meshes[index]) {
  20780. totalVertices += meshes[index].getTotalVertices();
  20781. if (totalVertices > 65536) {
  20782. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20783. return null;
  20784. }
  20785. }
  20786. }
  20787. }
  20788. // Merge
  20789. var vertexData;
  20790. var otherVertexData;
  20791. var source;
  20792. for (index = 0; index < meshes.length; index++) {
  20793. if (meshes[index]) {
  20794. meshes[index].computeWorldMatrix(true);
  20795. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20796. otherVertexData.transform(meshes[index].getWorldMatrix());
  20797. if (vertexData) {
  20798. vertexData.merge(otherVertexData);
  20799. }
  20800. else {
  20801. vertexData = otherVertexData;
  20802. source = meshes[index];
  20803. }
  20804. }
  20805. }
  20806. if (!meshSubclass) {
  20807. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  20808. }
  20809. vertexData.applyToMesh(meshSubclass);
  20810. // Setting properties
  20811. meshSubclass.material = source.material;
  20812. meshSubclass.checkCollisions = source.checkCollisions;
  20813. // Cleaning
  20814. if (disposeSource) {
  20815. for (index = 0; index < meshes.length; index++) {
  20816. if (meshes[index]) {
  20817. meshes[index].dispose();
  20818. }
  20819. }
  20820. }
  20821. return meshSubclass;
  20822. };
  20823. // Consts
  20824. Mesh._FRONTSIDE = 0;
  20825. Mesh._BACKSIDE = 1;
  20826. Mesh._DOUBLESIDE = 2;
  20827. Mesh._DEFAULTSIDE = 0;
  20828. Mesh._NO_CAP = 0;
  20829. Mesh._CAP_START = 1;
  20830. Mesh._CAP_END = 2;
  20831. Mesh._CAP_ALL = 3;
  20832. return Mesh;
  20833. })(BABYLON.AbstractMesh);
  20834. BABYLON.Mesh = Mesh;
  20835. })(BABYLON || (BABYLON = {}));
  20836. var BABYLON;
  20837. (function (BABYLON) {
  20838. var SubMesh = (function () {
  20839. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  20840. if (createBoundingBox === void 0) { createBoundingBox = true; }
  20841. this.materialIndex = materialIndex;
  20842. this.verticesStart = verticesStart;
  20843. this.verticesCount = verticesCount;
  20844. this.indexStart = indexStart;
  20845. this.indexCount = indexCount;
  20846. this._renderId = 0;
  20847. this._mesh = mesh;
  20848. this._renderingMesh = renderingMesh || mesh;
  20849. mesh.subMeshes.push(this);
  20850. this._trianglePlanes = [];
  20851. this._id = mesh.subMeshes.length - 1;
  20852. if (createBoundingBox) {
  20853. this.refreshBoundingInfo();
  20854. mesh.computeWorldMatrix(true);
  20855. }
  20856. }
  20857. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  20858. get: function () {
  20859. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  20860. },
  20861. enumerable: true,
  20862. configurable: true
  20863. });
  20864. SubMesh.prototype.getBoundingInfo = function () {
  20865. if (this.IsGlobal) {
  20866. return this._mesh.getBoundingInfo();
  20867. }
  20868. return this._boundingInfo;
  20869. };
  20870. SubMesh.prototype.getMesh = function () {
  20871. return this._mesh;
  20872. };
  20873. SubMesh.prototype.getRenderingMesh = function () {
  20874. return this._renderingMesh;
  20875. };
  20876. SubMesh.prototype.getMaterial = function () {
  20877. var rootMaterial = this._renderingMesh.material;
  20878. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  20879. var multiMaterial = rootMaterial;
  20880. return multiMaterial.getSubMaterial(this.materialIndex);
  20881. }
  20882. if (!rootMaterial) {
  20883. return this._mesh.getScene().defaultMaterial;
  20884. }
  20885. return rootMaterial;
  20886. };
  20887. // Methods
  20888. SubMesh.prototype.refreshBoundingInfo = function () {
  20889. this._lastColliderWorldVertices = null;
  20890. if (this.IsGlobal) {
  20891. return;
  20892. }
  20893. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20894. if (!data) {
  20895. this._boundingInfo = this._mesh._boundingInfo;
  20896. return;
  20897. }
  20898. var indices = this._renderingMesh.getIndices();
  20899. var extend;
  20900. //is this the only submesh?
  20901. if (this.indexStart === 0 && this.indexCount === indices.length) {
  20902. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  20903. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  20904. }
  20905. else {
  20906. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  20907. }
  20908. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20909. };
  20910. SubMesh.prototype._checkCollision = function (collider) {
  20911. return this.getBoundingInfo()._checkCollision(collider);
  20912. };
  20913. SubMesh.prototype.updateBoundingInfo = function (world) {
  20914. if (!this.getBoundingInfo()) {
  20915. this.refreshBoundingInfo();
  20916. }
  20917. this.getBoundingInfo().update(world);
  20918. };
  20919. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  20920. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  20921. };
  20922. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20923. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  20924. };
  20925. SubMesh.prototype.render = function (enableAlphaMode) {
  20926. this._renderingMesh.render(this, enableAlphaMode);
  20927. };
  20928. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  20929. if (!this._linesIndexBuffer) {
  20930. var linesIndices = [];
  20931. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20932. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  20933. }
  20934. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  20935. this.linesIndexCount = linesIndices.length;
  20936. }
  20937. return this._linesIndexBuffer;
  20938. };
  20939. SubMesh.prototype.canIntersects = function (ray) {
  20940. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  20941. };
  20942. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  20943. var intersectInfo = null;
  20944. // LineMesh first as it's also a Mesh...
  20945. if (this._mesh instanceof BABYLON.LinesMesh) {
  20946. var lineMesh = this._mesh;
  20947. // Line test
  20948. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  20949. var p0 = positions[indices[index]];
  20950. var p1 = positions[indices[index + 1]];
  20951. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  20952. if (length < 0) {
  20953. continue;
  20954. }
  20955. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  20956. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  20957. if (fastCheck) {
  20958. break;
  20959. }
  20960. }
  20961. }
  20962. }
  20963. else {
  20964. // Triangles test
  20965. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20966. var p0 = positions[indices[index]];
  20967. var p1 = positions[indices[index + 1]];
  20968. var p2 = positions[indices[index + 2]];
  20969. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  20970. if (currentIntersectInfo) {
  20971. if (currentIntersectInfo.distance < 0) {
  20972. continue;
  20973. }
  20974. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20975. intersectInfo = currentIntersectInfo;
  20976. intersectInfo.faceId = index / 3;
  20977. if (fastCheck) {
  20978. break;
  20979. }
  20980. }
  20981. }
  20982. }
  20983. }
  20984. return intersectInfo;
  20985. };
  20986. // Clone
  20987. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  20988. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  20989. if (!this.IsGlobal) {
  20990. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  20991. }
  20992. return result;
  20993. };
  20994. // Dispose
  20995. SubMesh.prototype.dispose = function () {
  20996. if (this._linesIndexBuffer) {
  20997. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  20998. this._linesIndexBuffer = null;
  20999. }
  21000. // Remove from mesh
  21001. var index = this._mesh.subMeshes.indexOf(this);
  21002. this._mesh.subMeshes.splice(index, 1);
  21003. };
  21004. // Statics
  21005. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21006. var minVertexIndex = Number.MAX_VALUE;
  21007. var maxVertexIndex = -Number.MAX_VALUE;
  21008. renderingMesh = renderingMesh || mesh;
  21009. var indices = renderingMesh.getIndices();
  21010. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21011. var vertexIndex = indices[index];
  21012. if (vertexIndex < minVertexIndex)
  21013. minVertexIndex = vertexIndex;
  21014. if (vertexIndex > maxVertexIndex)
  21015. maxVertexIndex = vertexIndex;
  21016. }
  21017. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21018. };
  21019. return SubMesh;
  21020. })();
  21021. BABYLON.SubMesh = SubMesh;
  21022. })(BABYLON || (BABYLON = {}));
  21023. var BABYLON;
  21024. (function (BABYLON) {
  21025. var MeshBuilder = (function () {
  21026. function MeshBuilder() {
  21027. }
  21028. /**
  21029. * Creates a box mesh.
  21030. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  21031. * The parameter `size` sets the size (float) of each box side (default 1).
  21032. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  21033. * 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).
  21034. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21035. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21036. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21037. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21038. */
  21039. MeshBuilder.CreateBox = function (name, options, scene) {
  21040. var box = new BABYLON.Mesh(name, scene);
  21041. var vertexData = BABYLON.VertexData.CreateBox(options);
  21042. vertexData.applyToMesh(box, options.updatable);
  21043. return box;
  21044. };
  21045. /**
  21046. * Creates a sphere mesh.
  21047. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  21048. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21049. * 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`).
  21050. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21051. * 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
  21052. * 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).
  21053. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21054. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21056. */
  21057. MeshBuilder.CreateSphere = function (name, options, scene) {
  21058. var sphere = new BABYLON.Mesh(name, scene);
  21059. var vertexData = BABYLON.VertexData.CreateSphere(options);
  21060. vertexData.applyToMesh(sphere, options.updatable);
  21061. return sphere;
  21062. };
  21063. /**
  21064. * Creates a plane polygonal mesh. By default, this is a disc.
  21065. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  21066. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21067. * 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.
  21068. * 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
  21069. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21070. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21071. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21072. */
  21073. MeshBuilder.CreateDisc = function (name, options, scene) {
  21074. var disc = new BABYLON.Mesh(name, scene);
  21075. var vertexData = BABYLON.VertexData.CreateDisc(options);
  21076. vertexData.applyToMesh(disc, options.updatable);
  21077. return disc;
  21078. };
  21079. /**
  21080. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21081. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  21082. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21083. * 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`).
  21084. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21085. * 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.
  21086. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21087. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21089. */
  21090. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  21091. var sphere = new BABYLON.Mesh(name, scene);
  21092. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  21093. vertexData.applyToMesh(sphere, options.updatable);
  21094. return sphere;
  21095. };
  21096. ;
  21097. /**
  21098. * Creates a ribbon mesh.
  21099. * 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.
  21100. *
  21101. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21102. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21103. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21104. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21105. * 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.
  21106. * 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.
  21107. * 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
  21108. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21109. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21110. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21112. */
  21113. MeshBuilder.CreateRibbon = function (name, options, scene) {
  21114. var pathArray = options.pathArray;
  21115. var closeArray = options.closeArray;
  21116. var closePath = options.closePath;
  21117. var offset = options.offset;
  21118. var sideOrientation = options.sideOrientation;
  21119. var instance = options.instance;
  21120. var updatable = options.updatable;
  21121. if (instance) {
  21122. // positionFunction : ribbon case
  21123. // only pathArray and sideOrientation parameters are taken into account for positions update
  21124. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  21125. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  21126. var positionFunction = function (positions) {
  21127. var minlg = pathArray[0].length;
  21128. var i = 0;
  21129. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  21130. for (var si = 1; si <= ns; si++) {
  21131. for (var p = 0; p < pathArray.length; p++) {
  21132. var path = pathArray[p];
  21133. var l = path.length;
  21134. minlg = (minlg < l) ? minlg : l;
  21135. var j = 0;
  21136. while (j < minlg) {
  21137. positions[i] = path[j].x;
  21138. positions[i + 1] = path[j].y;
  21139. positions[i + 2] = path[j].z;
  21140. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21141. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21142. }
  21143. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21144. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21145. }
  21146. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21147. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21148. }
  21149. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21150. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21151. }
  21152. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21153. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21154. }
  21155. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21156. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21157. }
  21158. j++;
  21159. i += 3;
  21160. }
  21161. if (instance._closePath) {
  21162. positions[i] = path[0].x;
  21163. positions[i + 1] = path[0].y;
  21164. positions[i + 2] = path[0].z;
  21165. i += 3;
  21166. }
  21167. }
  21168. }
  21169. };
  21170. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21171. positionFunction(positions);
  21172. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21173. instance._boundingInfo.update(instance._worldMatrix);
  21174. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21175. if (!(instance.areNormalsFrozen)) {
  21176. var indices = instance.getIndices();
  21177. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21178. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21179. if (instance._closePath) {
  21180. var indexFirst = 0;
  21181. var indexLast = 0;
  21182. for (var p = 0; p < pathArray.length; p++) {
  21183. indexFirst = instance._idx[p] * 3;
  21184. if (p + 1 < pathArray.length) {
  21185. indexLast = (instance._idx[p + 1] - 1) * 3;
  21186. }
  21187. else {
  21188. indexLast = normals.length - 3;
  21189. }
  21190. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21191. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21192. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21193. normals[indexLast] = normals[indexFirst];
  21194. normals[indexLast + 1] = normals[indexFirst + 1];
  21195. normals[indexLast + 2] = normals[indexFirst + 2];
  21196. }
  21197. }
  21198. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21199. }
  21200. return instance;
  21201. }
  21202. else {
  21203. var ribbon = new BABYLON.Mesh(name, scene);
  21204. ribbon.sideOrientation = sideOrientation;
  21205. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21206. if (closePath) {
  21207. ribbon._idx = vertexData._idx;
  21208. }
  21209. ribbon._closePath = closePath;
  21210. ribbon._closeArray = closeArray;
  21211. vertexData.applyToMesh(ribbon, updatable);
  21212. return ribbon;
  21213. }
  21214. };
  21215. /**
  21216. * Creates a cylinder or a cone mesh.
  21217. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21218. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21219. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21220. * 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.
  21221. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21222. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21223. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21224. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21225. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21226. * 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).
  21227. * 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
  21228. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21229. * 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
  21230. * 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.
  21231. * If `enclose` is false, a ring surface is one element.
  21232. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21233. * 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
  21234. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21235. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21236. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21237. */
  21238. MeshBuilder.CreateCylinder = function (name, options, scene) {
  21239. var cylinder = new BABYLON.Mesh(name, scene);
  21240. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  21241. vertexData.applyToMesh(cylinder, options.updatable);
  21242. return cylinder;
  21243. };
  21244. /**
  21245. * Creates a torus mesh.
  21246. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  21247. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21248. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21249. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21250. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21251. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21252. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21253. */
  21254. MeshBuilder.CreateTorus = function (name, options, scene) {
  21255. var torus = new BABYLON.Mesh(name, scene);
  21256. var vertexData = BABYLON.VertexData.CreateTorus(options);
  21257. vertexData.applyToMesh(torus, options.updatable);
  21258. return torus;
  21259. };
  21260. /**
  21261. * Creates a torus knot mesh.
  21262. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  21263. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21264. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21265. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21266. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21267. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21268. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21269. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21270. */
  21271. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  21272. var torusKnot = new BABYLON.Mesh(name, scene);
  21273. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  21274. vertexData.applyToMesh(torusKnot, options.updatable);
  21275. return torusKnot;
  21276. };
  21277. /**
  21278. * Creates a line system mesh.
  21279. * A line system is a pool of many lines gathered in a single mesh.
  21280. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  21281. * 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.
  21282. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  21283. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  21284. * 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
  21285. * 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
  21286. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  21287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21288. */
  21289. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  21290. var instance = options.instance;
  21291. var lines = options.lines;
  21292. if (instance) {
  21293. var positionFunction = function (positions) {
  21294. var i = 0;
  21295. for (var l = 0; l < lines.length; l++) {
  21296. var points = lines[l];
  21297. for (var p = 0; p < points.length; p++) {
  21298. positions[i] = points[p].x;
  21299. positions[i + 1] = points[p].y;
  21300. positions[i + 2] = points[p].z;
  21301. i += 3;
  21302. }
  21303. }
  21304. };
  21305. instance.updateMeshPositions(positionFunction, false);
  21306. return instance;
  21307. }
  21308. // line system creation
  21309. var lineSystem = new BABYLON.LinesMesh(name, scene);
  21310. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  21311. vertexData.applyToMesh(lineSystem, options.updatable);
  21312. return lineSystem;
  21313. };
  21314. /**
  21315. * Creates a line mesh.
  21316. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  21317. * 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.
  21318. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21319. * The parameter `points` is an array successive Vector3.
  21320. * 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
  21321. * When updating an instance, remember that only point positions can change, not the number of points.
  21322. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21323. */
  21324. MeshBuilder.CreateLines = function (name, options, scene) {
  21325. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  21326. return lines;
  21327. };
  21328. /**
  21329. * Creates a dashed line mesh.
  21330. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  21331. * 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.
  21332. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21333. * The parameter `points` is an array successive Vector3.
  21334. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21335. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21336. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21337. * 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
  21338. * When updating an instance, remember that only point positions can change, not the number of points.
  21339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21340. */
  21341. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  21342. var points = options.points;
  21343. var instance = options.instance;
  21344. var gapSize = options.gapSize;
  21345. var dashNb = options.dashNb;
  21346. var dashSize = options.dashSize;
  21347. if (instance) {
  21348. var positionFunction = function (positions) {
  21349. var curvect = BABYLON.Vector3.Zero();
  21350. var nbSeg = positions.length / 6;
  21351. var lg = 0;
  21352. var nb = 0;
  21353. var shft = 0;
  21354. var dashshft = 0;
  21355. var curshft = 0;
  21356. var p = 0;
  21357. var i = 0;
  21358. var j = 0;
  21359. for (i = 0; i < points.length - 1; i++) {
  21360. points[i + 1].subtractToRef(points[i], curvect);
  21361. lg += curvect.length();
  21362. }
  21363. shft = lg / nbSeg;
  21364. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  21365. for (i = 0; i < points.length - 1; i++) {
  21366. points[i + 1].subtractToRef(points[i], curvect);
  21367. nb = Math.floor(curvect.length() / shft);
  21368. curvect.normalize();
  21369. j = 0;
  21370. while (j < nb && p < positions.length) {
  21371. curshft = shft * j;
  21372. positions[p] = points[i].x + curshft * curvect.x;
  21373. positions[p + 1] = points[i].y + curshft * curvect.y;
  21374. positions[p + 2] = points[i].z + curshft * curvect.z;
  21375. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  21376. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  21377. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  21378. p += 6;
  21379. j++;
  21380. }
  21381. }
  21382. while (p < positions.length) {
  21383. positions[p] = points[i].x;
  21384. positions[p + 1] = points[i].y;
  21385. positions[p + 2] = points[i].z;
  21386. p += 3;
  21387. }
  21388. };
  21389. instance.updateMeshPositions(positionFunction, false);
  21390. return instance;
  21391. }
  21392. // dashed lines creation
  21393. var dashedLines = new BABYLON.LinesMesh(name, scene);
  21394. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  21395. vertexData.applyToMesh(dashedLines, options.updatable);
  21396. dashedLines.dashSize = dashSize;
  21397. dashedLines.gapSize = gapSize;
  21398. return dashedLines;
  21399. };
  21400. /**
  21401. * Creates an extruded shape mesh.
  21402. * 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.
  21403. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  21404. *
  21405. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21406. * 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
  21407. * extruded along the Z axis.
  21408. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21409. * 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.
  21410. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21411. * 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
  21412. * 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
  21413. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21414. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21415. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21416. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21417. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21418. */
  21419. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  21420. var path = options.path;
  21421. var shape = options.shape;
  21422. var scale = options.scale || 1;
  21423. var rotation = options.rotation || 0;
  21424. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21425. var updatable = options.updatable;
  21426. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21427. var instance = options.instance;
  21428. var invertUV = options.invertUV || false;
  21429. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  21430. };
  21431. /**
  21432. * Creates an custom extruded shape mesh.
  21433. * 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.
  21434. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  21435. *
  21436. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21437. * 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
  21438. * extruded along the Z axis.
  21439. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21440. * 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
  21441. * and the distance of this point from the begining of the path :
  21442. * ```javascript
  21443. * var rotationFunction = function(i, distance) {
  21444. * // do things
  21445. * return rotationValue; }
  21446. * ```
  21447. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21448. * 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
  21449. * and the distance of this point from the begining of the path :
  21450. * ```javascript
  21451. * var scaleFunction = function(i, distance) {
  21452. * // do things
  21453. * return scaleValue;}
  21454. * ```
  21455. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21456. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21457. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21458. * 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
  21459. * 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
  21460. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21461. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21462. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21463. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21464. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21465. */
  21466. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  21467. var path = options.path;
  21468. var shape = options.shape;
  21469. var scaleFunction = options.scaleFunction || (function () { return 1; });
  21470. var rotationFunction = options.rotationFunction || (function () { return 0; });
  21471. var ribbonCloseArray = options.ribbonCloseArray || false;
  21472. var ribbonClosePath = options.ribbonClosePath || false;
  21473. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21474. var updatable = options.updatable;
  21475. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21476. var instance = options.instance;
  21477. var invertUV = options.invertUV || false;
  21478. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  21479. };
  21480. /**
  21481. * Creates lathe mesh.
  21482. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21483. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  21484. *
  21485. * 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
  21486. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21487. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21488. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21489. * 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.
  21490. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  21491. * 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
  21492. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21493. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21494. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21496. */
  21497. MeshBuilder.CreateLathe = function (name, options, scene) {
  21498. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  21499. var closed = (options.closed === undefined) ? true : options.closed;
  21500. var shape = options.shape;
  21501. var radius = options.radius || 1;
  21502. var tessellation = options.tessellation || 64;
  21503. var updatable = options.updatable;
  21504. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21505. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21506. var pi2 = Math.PI * 2;
  21507. var paths = new Array();
  21508. var invertUV = options.invertUV || false;
  21509. var i = 0;
  21510. var p = 0;
  21511. var step = pi2 / tessellation * arc;
  21512. var rotated;
  21513. var path = new Array();
  21514. ;
  21515. for (i = 0; i <= tessellation; i++) {
  21516. var path = [];
  21517. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  21518. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  21519. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  21520. }
  21521. for (p = 0; p < shape.length; p++) {
  21522. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  21523. path.push(rotated);
  21524. }
  21525. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  21526. 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));
  21527. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  21528. }
  21529. paths.push(path);
  21530. }
  21531. // lathe ribbon
  21532. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  21533. return lathe;
  21534. };
  21535. /**
  21536. * Creates a plane mesh.
  21537. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21538. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21539. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  21540. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  21541. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21542. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21544. */
  21545. MeshBuilder.CreatePlane = function (name, options, scene) {
  21546. var plane = new BABYLON.Mesh(name, scene);
  21547. var vertexData = BABYLON.VertexData.CreatePlane(options);
  21548. vertexData.applyToMesh(plane, options.updatable);
  21549. if (options.sourcePlane) {
  21550. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  21551. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  21552. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  21553. plane.rotate(vectorProduct, product);
  21554. }
  21555. return plane;
  21556. };
  21557. /**
  21558. * Creates a ground mesh.
  21559. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21560. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21561. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21562. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21563. */
  21564. MeshBuilder.CreateGround = function (name, options, scene) {
  21565. var ground = new BABYLON.GroundMesh(name, scene);
  21566. ground._setReady(false);
  21567. ground._subdivisions = options.subdivisions || 1;
  21568. ground._width = options.width || 1;
  21569. ground._height = options.height || 1;
  21570. ground._maxX = ground._width / 2;
  21571. ground._maxZ = ground._height / 2;
  21572. ground._minX = -ground._maxX;
  21573. ground._minZ = -ground._maxZ;
  21574. var vertexData = BABYLON.VertexData.CreateGround(options);
  21575. vertexData.applyToMesh(ground, options.updatable);
  21576. ground._setReady(true);
  21577. return ground;
  21578. };
  21579. /**
  21580. * Creates a tiled ground mesh.
  21581. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  21582. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21583. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21584. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21585. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21586. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21587. * numbers of subdivisions on the ground width and height of each tile.
  21588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21589. */
  21590. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  21591. var tiledGround = new BABYLON.Mesh(name, scene);
  21592. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  21593. vertexData.applyToMesh(tiledGround, options.updatable);
  21594. return tiledGround;
  21595. };
  21596. /**
  21597. * Creates a ground mesh from a height map.
  21598. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21599. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  21600. * The parameter `url` sets the URL of the height map image resource.
  21601. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21602. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21603. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21604. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21605. * 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).
  21606. * This function is passed the newly built mesh :
  21607. * ```javascript
  21608. * function(mesh) { // do things
  21609. * return; }
  21610. * ```
  21611. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21612. */
  21613. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  21614. var width = options.width || 10.0;
  21615. var height = options.height || 10.0;
  21616. var subdivisions = options.subdivisions || 1 | 0;
  21617. var minHeight = options.minHeight || 0.0;
  21618. var maxHeight = options.maxHeight || 10.0;
  21619. var updatable = options.updatable;
  21620. var onReady = options.onReady;
  21621. var ground = new BABYLON.GroundMesh(name, scene);
  21622. ground._subdivisions = subdivisions;
  21623. ground._width = width;
  21624. ground._height = height;
  21625. ground._maxX = ground._width / 2.0;
  21626. ground._maxZ = ground._height / 2.0;
  21627. ground._minX = -ground._maxX;
  21628. ground._minZ = -ground._maxZ;
  21629. ground._setReady(false);
  21630. var onload = function (img) {
  21631. // Getting height map data
  21632. var canvas = document.createElement("canvas");
  21633. var context = canvas.getContext("2d");
  21634. var bufferWidth = img.width;
  21635. var bufferHeight = img.height;
  21636. canvas.width = bufferWidth;
  21637. canvas.height = bufferHeight;
  21638. context.drawImage(img, 0, 0);
  21639. // Create VertexData from map data
  21640. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21641. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  21642. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  21643. width: width, height: height,
  21644. subdivisions: subdivisions,
  21645. minHeight: minHeight, maxHeight: maxHeight,
  21646. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  21647. });
  21648. vertexData.applyToMesh(ground, updatable);
  21649. ground._setReady(true);
  21650. //execute ready callback, if set
  21651. if (onReady) {
  21652. onReady(ground);
  21653. }
  21654. };
  21655. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21656. return ground;
  21657. };
  21658. /**
  21659. * Creates a tube mesh.
  21660. * 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.
  21661. *
  21662. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  21663. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21664. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21665. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21666. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21667. * 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.
  21668. * It must return a radius value (positive float) :
  21669. * ```javascript
  21670. * var radiusFunction = function(i, distance) {
  21671. * // do things
  21672. * return radius; }
  21673. * ```
  21674. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  21675. * 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
  21676. * 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
  21677. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21678. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21679. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21680. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21681. */
  21682. MeshBuilder.CreateTube = function (name, options, scene) {
  21683. var path = options.path;
  21684. var radius = options.radius || 1.0;
  21685. var tessellation = options.tessellation || 64 | 0;
  21686. var radiusFunction = options.radiusFunction;
  21687. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21688. var invertUV = options.invertUV || false;
  21689. var updatable = options.updatable;
  21690. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21691. var instance = options.instance;
  21692. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  21693. // tube geometry
  21694. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  21695. var tangents = path3D.getTangents();
  21696. var normals = path3D.getNormals();
  21697. var distances = path3D.getDistances();
  21698. var pi2 = Math.PI * 2;
  21699. var step = pi2 / tessellation * arc;
  21700. var returnRadius = function () { return radius; };
  21701. var radiusFunctionFinal = radiusFunction || returnRadius;
  21702. var circlePath;
  21703. var rad;
  21704. var normal;
  21705. var rotated;
  21706. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21707. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21708. for (var i = 0; i < path.length; i++) {
  21709. rad = radiusFunctionFinal(i, distances[i]); // current radius
  21710. circlePath = Array(); // current circle array
  21711. normal = normals[i]; // current normal
  21712. for (var t = 0; t < tessellation; t++) {
  21713. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  21714. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  21715. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  21716. rotated.scaleInPlace(rad).addInPlace(path[i]);
  21717. circlePath[t] = rotated;
  21718. }
  21719. circlePaths[index] = circlePath;
  21720. index++;
  21721. }
  21722. // cap
  21723. var capPath = function (nbPoints, pathIndex) {
  21724. var pointCap = Array();
  21725. for (var i = 0; i < nbPoints; i++) {
  21726. pointCap.push(path[pathIndex]);
  21727. }
  21728. return pointCap;
  21729. };
  21730. switch (cap) {
  21731. case BABYLON.Mesh.NO_CAP:
  21732. break;
  21733. case BABYLON.Mesh.CAP_START:
  21734. circlePaths[0] = capPath(tessellation, 0);
  21735. circlePaths[1] = circlePaths[2].slice(0);
  21736. break;
  21737. case BABYLON.Mesh.CAP_END:
  21738. circlePaths[index] = circlePaths[index - 1].slice(0);
  21739. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21740. break;
  21741. case BABYLON.Mesh.CAP_ALL:
  21742. circlePaths[0] = capPath(tessellation, 0);
  21743. circlePaths[1] = circlePaths[2].slice(0);
  21744. circlePaths[index] = circlePaths[index - 1].slice(0);
  21745. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21746. break;
  21747. default:
  21748. break;
  21749. }
  21750. return circlePaths;
  21751. };
  21752. var path3D;
  21753. var pathArray;
  21754. if (instance) {
  21755. var arc = options.arc || instance.arc;
  21756. path3D = (instance.path3D).update(path);
  21757. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  21758. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  21759. instance.path3D = path3D;
  21760. instance.pathArray = pathArray;
  21761. instance.arc = arc;
  21762. return instance;
  21763. }
  21764. // tube creation
  21765. path3D = new BABYLON.Path3D(path);
  21766. var newPathArray = new Array();
  21767. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21768. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  21769. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  21770. tube.pathArray = pathArray;
  21771. tube.path3D = path3D;
  21772. tube.tessellation = tessellation;
  21773. tube.cap = cap;
  21774. tube.arc = options.arc;
  21775. return tube;
  21776. };
  21777. /**
  21778. * Creates a polyhedron mesh.
  21779. *
  21780. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  21781. * 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
  21782. * to choose the wanted type.
  21783. * The parameter `size` (positive float, default 1) sets the polygon size.
  21784. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21785. * 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`.
  21786. * 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
  21787. * 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)`).
  21788. * 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
  21789. * 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.
  21790. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21791. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21792. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21793. */
  21794. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  21795. var polyhedron = new BABYLON.Mesh(name, scene);
  21796. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  21797. vertexData.applyToMesh(polyhedron, options.updatable);
  21798. return polyhedron;
  21799. };
  21800. /**
  21801. * Creates a decal mesh.
  21802. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  21803. * 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.
  21804. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21805. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21806. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21807. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21808. */
  21809. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  21810. var indices = sourceMesh.getIndices();
  21811. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21812. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21813. var position = options.position || BABYLON.Vector3.Zero();
  21814. var normal = options.normal || BABYLON.Vector3.Up();
  21815. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  21816. var angle = options.angle || 0;
  21817. // Getting correct rotation
  21818. if (!normal) {
  21819. var target = new BABYLON.Vector3(0, 0, 1);
  21820. var camera = sourceMesh.getScene().activeCamera;
  21821. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  21822. normal = camera.globalPosition.subtract(cameraWorldTarget);
  21823. }
  21824. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  21825. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  21826. var pitch = Math.atan2(normal.y, len);
  21827. // Matrix
  21828. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  21829. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  21830. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  21831. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  21832. var vertexData = new BABYLON.VertexData();
  21833. vertexData.indices = [];
  21834. vertexData.positions = [];
  21835. vertexData.normals = [];
  21836. vertexData.uvs = [];
  21837. var currentVertexDataIndex = 0;
  21838. var extractDecalVector3 = function (indexId) {
  21839. var vertexId = indices[indexId];
  21840. var result = new BABYLON.PositionNormalVertex();
  21841. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  21842. // Send vector to decal local world
  21843. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  21844. // Get normal
  21845. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  21846. return result;
  21847. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  21848. var clip = function (vertices, axis) {
  21849. if (vertices.length === 0) {
  21850. return vertices;
  21851. }
  21852. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  21853. var clipVertices = function (v0, v1) {
  21854. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  21855. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  21856. };
  21857. var result = new Array();
  21858. for (var index = 0; index < vertices.length; index += 3) {
  21859. var v1Out;
  21860. var v2Out;
  21861. var v3Out;
  21862. var total = 0;
  21863. var nV1, nV2, nV3, nV4;
  21864. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  21865. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  21866. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  21867. v1Out = d1 > 0;
  21868. v2Out = d2 > 0;
  21869. v3Out = d3 > 0;
  21870. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  21871. switch (total) {
  21872. case 0:
  21873. result.push(vertices[index]);
  21874. result.push(vertices[index + 1]);
  21875. result.push(vertices[index + 2]);
  21876. break;
  21877. case 1:
  21878. if (v1Out) {
  21879. nV1 = vertices[index + 1];
  21880. nV2 = vertices[index + 2];
  21881. nV3 = clipVertices(vertices[index], nV1);
  21882. nV4 = clipVertices(vertices[index], nV2);
  21883. }
  21884. if (v2Out) {
  21885. nV1 = vertices[index];
  21886. nV2 = vertices[index + 2];
  21887. nV3 = clipVertices(vertices[index + 1], nV1);
  21888. nV4 = clipVertices(vertices[index + 1], nV2);
  21889. result.push(nV3);
  21890. result.push(nV2.clone());
  21891. result.push(nV1.clone());
  21892. result.push(nV2.clone());
  21893. result.push(nV3.clone());
  21894. result.push(nV4);
  21895. break;
  21896. }
  21897. if (v3Out) {
  21898. nV1 = vertices[index];
  21899. nV2 = vertices[index + 1];
  21900. nV3 = clipVertices(vertices[index + 2], nV1);
  21901. nV4 = clipVertices(vertices[index + 2], nV2);
  21902. }
  21903. result.push(nV1.clone());
  21904. result.push(nV2.clone());
  21905. result.push(nV3);
  21906. result.push(nV4);
  21907. result.push(nV3.clone());
  21908. result.push(nV2.clone());
  21909. break;
  21910. case 2:
  21911. if (!v1Out) {
  21912. nV1 = vertices[index].clone();
  21913. nV2 = clipVertices(nV1, vertices[index + 1]);
  21914. nV3 = clipVertices(nV1, vertices[index + 2]);
  21915. result.push(nV1);
  21916. result.push(nV2);
  21917. result.push(nV3);
  21918. }
  21919. if (!v2Out) {
  21920. nV1 = vertices[index + 1].clone();
  21921. nV2 = clipVertices(nV1, vertices[index + 2]);
  21922. nV3 = clipVertices(nV1, vertices[index]);
  21923. result.push(nV1);
  21924. result.push(nV2);
  21925. result.push(nV3);
  21926. }
  21927. if (!v3Out) {
  21928. nV1 = vertices[index + 2].clone();
  21929. nV2 = clipVertices(nV1, vertices[index]);
  21930. nV3 = clipVertices(nV1, vertices[index + 1]);
  21931. result.push(nV1);
  21932. result.push(nV2);
  21933. result.push(nV3);
  21934. }
  21935. break;
  21936. case 3:
  21937. break;
  21938. }
  21939. }
  21940. return result;
  21941. };
  21942. for (var index = 0; index < indices.length; index += 3) {
  21943. var faceVertices = new Array();
  21944. faceVertices.push(extractDecalVector3(index));
  21945. faceVertices.push(extractDecalVector3(index + 1));
  21946. faceVertices.push(extractDecalVector3(index + 2));
  21947. // Clip
  21948. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  21949. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  21950. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  21951. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  21952. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  21953. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  21954. if (faceVertices.length === 0) {
  21955. continue;
  21956. }
  21957. // Add UVs and get back to world
  21958. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  21959. var vertex = faceVertices[vIndex];
  21960. //TODO check for Int32Array
  21961. vertexData.indices.push(currentVertexDataIndex);
  21962. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  21963. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  21964. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  21965. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  21966. currentVertexDataIndex++;
  21967. }
  21968. }
  21969. // Return mesh
  21970. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  21971. vertexData.applyToMesh(decal);
  21972. decal.position = position.clone();
  21973. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  21974. return decal;
  21975. };
  21976. // Privates
  21977. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  21978. // extrusion geometry
  21979. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  21980. var tangents = path3D.getTangents();
  21981. var normals = path3D.getNormals();
  21982. var binormals = path3D.getBinormals();
  21983. var distances = path3D.getDistances();
  21984. var angle = 0;
  21985. var returnScale = function () { return scale; };
  21986. var returnRotation = function () { return rotation; };
  21987. var rotate = custom ? rotateFunction : returnRotation;
  21988. var scl = custom ? scaleFunction : returnScale;
  21989. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21990. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21991. for (var i = 0; i < curve.length; i++) {
  21992. var shapePath = new Array();
  21993. var angleStep = rotate(i, distances[i]);
  21994. var scaleRatio = scl(i, distances[i]);
  21995. for (var p = 0; p < shape.length; p++) {
  21996. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  21997. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  21998. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  21999. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  22000. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  22001. shapePath[p] = rotated;
  22002. }
  22003. shapePaths[index] = shapePath;
  22004. angle += angleStep;
  22005. index++;
  22006. }
  22007. // cap
  22008. var capPath = function (shapePath) {
  22009. var pointCap = Array();
  22010. var barycenter = BABYLON.Vector3.Zero();
  22011. var i;
  22012. for (i = 0; i < shapePath.length; i++) {
  22013. barycenter.addInPlace(shapePath[i]);
  22014. }
  22015. barycenter.scaleInPlace(1 / shapePath.length);
  22016. for (i = 0; i < shapePath.length; i++) {
  22017. pointCap.push(barycenter);
  22018. }
  22019. return pointCap;
  22020. };
  22021. switch (cap) {
  22022. case BABYLON.Mesh.NO_CAP:
  22023. break;
  22024. case BABYLON.Mesh.CAP_START:
  22025. shapePaths[0] = capPath(shapePaths[2]);
  22026. shapePaths[1] = shapePaths[2].slice(0);
  22027. break;
  22028. case BABYLON.Mesh.CAP_END:
  22029. shapePaths[index] = shapePaths[index - 1];
  22030. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22031. break;
  22032. case BABYLON.Mesh.CAP_ALL:
  22033. shapePaths[0] = capPath(shapePaths[2]);
  22034. shapePaths[1] = shapePaths[2].slice(0);
  22035. shapePaths[index] = shapePaths[index - 1];
  22036. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22037. break;
  22038. default:
  22039. break;
  22040. }
  22041. return shapePaths;
  22042. };
  22043. var path3D;
  22044. var pathArray;
  22045. if (instance) {
  22046. path3D = (instance.path3D).update(curve);
  22047. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  22048. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  22049. return instance;
  22050. }
  22051. // extruded shape creation
  22052. path3D = new BABYLON.Path3D(curve);
  22053. var newShapePaths = new Array();
  22054. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22055. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  22056. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  22057. extrudedGeneric.pathArray = pathArray;
  22058. extrudedGeneric.path3D = path3D;
  22059. extrudedGeneric.cap = cap;
  22060. return extrudedGeneric;
  22061. };
  22062. return MeshBuilder;
  22063. })();
  22064. BABYLON.MeshBuilder = MeshBuilder;
  22065. })(BABYLON || (BABYLON = {}));
  22066. var BABYLON;
  22067. (function (BABYLON) {
  22068. var BaseTexture = (function () {
  22069. function BaseTexture(scene) {
  22070. this.hasAlpha = false;
  22071. this.getAlphaFromRGB = false;
  22072. this.level = 1;
  22073. this.coordinatesIndex = 0;
  22074. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22075. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22076. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22077. this.anisotropicFilteringLevel = 4;
  22078. this.isCube = false;
  22079. this.isRenderTarget = false;
  22080. this.animations = new Array();
  22081. /**
  22082. * An event triggered when the texture is disposed.
  22083. * @type {BABYLON.Observable}
  22084. */
  22085. this.onDisposeObservable = new BABYLON.Observable();
  22086. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22087. this._scene = scene;
  22088. this._scene.textures.push(this);
  22089. }
  22090. BaseTexture.prototype.toString = function () {
  22091. return this.name;
  22092. };
  22093. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22094. set: function (callback) {
  22095. if (this._onDisposeObserver) {
  22096. this.onDisposeObservable.remove(this._onDisposeObserver);
  22097. }
  22098. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22099. },
  22100. enumerable: true,
  22101. configurable: true
  22102. });
  22103. BaseTexture.prototype.getScene = function () {
  22104. return this._scene;
  22105. };
  22106. BaseTexture.prototype.getTextureMatrix = function () {
  22107. return null;
  22108. };
  22109. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22110. return null;
  22111. };
  22112. BaseTexture.prototype.getInternalTexture = function () {
  22113. return this._texture;
  22114. };
  22115. BaseTexture.prototype.isReady = function () {
  22116. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22117. return true;
  22118. }
  22119. if (this._texture) {
  22120. return this._texture.isReady;
  22121. }
  22122. return false;
  22123. };
  22124. BaseTexture.prototype.getSize = function () {
  22125. if (this._texture._width) {
  22126. return new BABYLON.Size(this._texture._width, this._texture._height);
  22127. }
  22128. if (this._texture._size) {
  22129. return new BABYLON.Size(this._texture._size, this._texture._size);
  22130. }
  22131. return BABYLON.Size.Zero();
  22132. };
  22133. BaseTexture.prototype.getBaseSize = function () {
  22134. if (!this.isReady() || !this._texture)
  22135. return BABYLON.Size.Zero();
  22136. if (this._texture._size) {
  22137. return new BABYLON.Size(this._texture._size, this._texture._size);
  22138. }
  22139. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22140. };
  22141. BaseTexture.prototype.scale = function (ratio) {
  22142. };
  22143. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22144. get: function () {
  22145. return false;
  22146. },
  22147. enumerable: true,
  22148. configurable: true
  22149. });
  22150. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22151. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22152. for (var index = 0; index < texturesCache.length; index++) {
  22153. var texturesCacheEntry = texturesCache[index];
  22154. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22155. texturesCache.splice(index, 1);
  22156. return;
  22157. }
  22158. }
  22159. };
  22160. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22161. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22162. for (var index = 0; index < texturesCache.length; index++) {
  22163. var texturesCacheEntry = texturesCache[index];
  22164. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22165. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22166. texturesCacheEntry.references++;
  22167. return texturesCacheEntry;
  22168. }
  22169. }
  22170. }
  22171. return null;
  22172. };
  22173. BaseTexture.prototype.delayLoad = function () {
  22174. };
  22175. BaseTexture.prototype.clone = function () {
  22176. return null;
  22177. };
  22178. BaseTexture.prototype.releaseInternalTexture = function () {
  22179. if (this._texture) {
  22180. this._scene.getEngine().releaseInternalTexture(this._texture);
  22181. delete this._texture;
  22182. }
  22183. };
  22184. BaseTexture.prototype.dispose = function () {
  22185. // Animations
  22186. this.getScene().stopAnimation(this);
  22187. // Remove from scene
  22188. var index = this._scene.textures.indexOf(this);
  22189. if (index >= 0) {
  22190. this._scene.textures.splice(index, 1);
  22191. }
  22192. if (this._texture === undefined) {
  22193. return;
  22194. }
  22195. // Release
  22196. this.releaseInternalTexture();
  22197. // Callback
  22198. this.onDisposeObservable.notifyObservers(this);
  22199. this.onDisposeObservable.clear();
  22200. };
  22201. BaseTexture.prototype.serialize = function () {
  22202. if (!this.name) {
  22203. return null;
  22204. }
  22205. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22206. // Animations
  22207. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22208. return serializationObject;
  22209. };
  22210. __decorate([
  22211. BABYLON.serialize()
  22212. ], BaseTexture.prototype, "name", void 0);
  22213. __decorate([
  22214. BABYLON.serialize()
  22215. ], BaseTexture.prototype, "hasAlpha", void 0);
  22216. __decorate([
  22217. BABYLON.serialize()
  22218. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22219. __decorate([
  22220. BABYLON.serialize()
  22221. ], BaseTexture.prototype, "level", void 0);
  22222. __decorate([
  22223. BABYLON.serialize()
  22224. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22225. __decorate([
  22226. BABYLON.serialize()
  22227. ], BaseTexture.prototype, "coordinatesMode", void 0);
  22228. __decorate([
  22229. BABYLON.serialize()
  22230. ], BaseTexture.prototype, "wrapU", void 0);
  22231. __decorate([
  22232. BABYLON.serialize()
  22233. ], BaseTexture.prototype, "wrapV", void 0);
  22234. __decorate([
  22235. BABYLON.serialize()
  22236. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22237. __decorate([
  22238. BABYLON.serialize()
  22239. ], BaseTexture.prototype, "isCube", void 0);
  22240. __decorate([
  22241. BABYLON.serialize()
  22242. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22243. return BaseTexture;
  22244. })();
  22245. BABYLON.BaseTexture = BaseTexture;
  22246. })(BABYLON || (BABYLON = {}));
  22247. var BABYLON;
  22248. (function (BABYLON) {
  22249. var Texture = (function (_super) {
  22250. __extends(Texture, _super);
  22251. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  22252. var _this = this;
  22253. if (noMipmap === void 0) { noMipmap = false; }
  22254. if (invertY === void 0) { invertY = true; }
  22255. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22256. if (onLoad === void 0) { onLoad = null; }
  22257. if (onError === void 0) { onError = null; }
  22258. if (buffer === void 0) { buffer = null; }
  22259. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22260. _super.call(this, scene);
  22261. this.uOffset = 0;
  22262. this.vOffset = 0;
  22263. this.uScale = 1.0;
  22264. this.vScale = 1.0;
  22265. this.uAng = 0;
  22266. this.vAng = 0;
  22267. this.wAng = 0;
  22268. this.name = url;
  22269. this.url = url;
  22270. this._noMipmap = noMipmap;
  22271. this._invertY = invertY;
  22272. this._samplingMode = samplingMode;
  22273. this._buffer = buffer;
  22274. this._deleteBuffer = deleteBuffer;
  22275. if (!url) {
  22276. return;
  22277. }
  22278. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  22279. var load = function () {
  22280. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  22281. _this.onLoadObservable.notifyObservers(true);
  22282. }
  22283. if (onLoad) {
  22284. onLoad();
  22285. }
  22286. };
  22287. if (!this._texture) {
  22288. if (!scene.useDelayedTextureLoading) {
  22289. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  22290. if (deleteBuffer) {
  22291. delete this._buffer;
  22292. }
  22293. }
  22294. else {
  22295. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22296. this._delayedOnLoad = load;
  22297. this._delayedOnError = onError;
  22298. }
  22299. }
  22300. else {
  22301. if (this._texture.isReady) {
  22302. BABYLON.Tools.SetImmediate(function () { return load(); });
  22303. }
  22304. else {
  22305. this._texture.onLoadedCallbacks.push(load);
  22306. }
  22307. }
  22308. }
  22309. Object.defineProperty(Texture.prototype, "noMipmap", {
  22310. get: function () {
  22311. return this._noMipmap;
  22312. },
  22313. enumerable: true,
  22314. configurable: true
  22315. });
  22316. Texture.prototype.delayLoad = function () {
  22317. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22318. return;
  22319. }
  22320. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22321. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22322. if (!this._texture) {
  22323. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  22324. if (this._deleteBuffer) {
  22325. delete this._buffer;
  22326. }
  22327. }
  22328. };
  22329. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22330. if (!this._texture) {
  22331. return;
  22332. }
  22333. this._samplingMode = samplingMode;
  22334. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22335. };
  22336. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22337. x *= this.uScale;
  22338. y *= this.vScale;
  22339. x -= 0.5 * this.uScale;
  22340. y -= 0.5 * this.vScale;
  22341. z -= 0.5;
  22342. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22343. t.x += 0.5 * this.uScale + this.uOffset;
  22344. t.y += 0.5 * this.vScale + this.vOffset;
  22345. t.z += 0.5;
  22346. };
  22347. Texture.prototype.getTextureMatrix = function () {
  22348. if (this.uOffset === this._cachedUOffset &&
  22349. this.vOffset === this._cachedVOffset &&
  22350. this.uScale === this._cachedUScale &&
  22351. this.vScale === this._cachedVScale &&
  22352. this.uAng === this._cachedUAng &&
  22353. this.vAng === this._cachedVAng &&
  22354. this.wAng === this._cachedWAng) {
  22355. return this._cachedTextureMatrix;
  22356. }
  22357. this._cachedUOffset = this.uOffset;
  22358. this._cachedVOffset = this.vOffset;
  22359. this._cachedUScale = this.uScale;
  22360. this._cachedVScale = this.vScale;
  22361. this._cachedUAng = this.uAng;
  22362. this._cachedVAng = this.vAng;
  22363. this._cachedWAng = this.wAng;
  22364. if (!this._cachedTextureMatrix) {
  22365. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22366. this._rowGenerationMatrix = new BABYLON.Matrix();
  22367. this._t0 = BABYLON.Vector3.Zero();
  22368. this._t1 = BABYLON.Vector3.Zero();
  22369. this._t2 = BABYLON.Vector3.Zero();
  22370. }
  22371. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22372. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22373. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22374. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22375. this._t1.subtractInPlace(this._t0);
  22376. this._t2.subtractInPlace(this._t0);
  22377. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22378. this._cachedTextureMatrix.m[0] = this._t1.x;
  22379. this._cachedTextureMatrix.m[1] = this._t1.y;
  22380. this._cachedTextureMatrix.m[2] = this._t1.z;
  22381. this._cachedTextureMatrix.m[4] = this._t2.x;
  22382. this._cachedTextureMatrix.m[5] = this._t2.y;
  22383. this._cachedTextureMatrix.m[6] = this._t2.z;
  22384. this._cachedTextureMatrix.m[8] = this._t0.x;
  22385. this._cachedTextureMatrix.m[9] = this._t0.y;
  22386. this._cachedTextureMatrix.m[10] = this._t0.z;
  22387. return this._cachedTextureMatrix;
  22388. };
  22389. Texture.prototype.getReflectionTextureMatrix = function () {
  22390. if (this.uOffset === this._cachedUOffset &&
  22391. this.vOffset === this._cachedVOffset &&
  22392. this.uScale === this._cachedUScale &&
  22393. this.vScale === this._cachedVScale &&
  22394. this.coordinatesMode === this._cachedCoordinatesMode) {
  22395. return this._cachedTextureMatrix;
  22396. }
  22397. if (!this._cachedTextureMatrix) {
  22398. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22399. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22400. }
  22401. this._cachedCoordinatesMode = this.coordinatesMode;
  22402. switch (this.coordinatesMode) {
  22403. case Texture.PLANAR_MODE:
  22404. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22405. this._cachedTextureMatrix[0] = this.uScale;
  22406. this._cachedTextureMatrix[5] = this.vScale;
  22407. this._cachedTextureMatrix[12] = this.uOffset;
  22408. this._cachedTextureMatrix[13] = this.vOffset;
  22409. break;
  22410. case Texture.PROJECTION_MODE:
  22411. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22412. this._projectionModeMatrix.m[0] = 0.5;
  22413. this._projectionModeMatrix.m[5] = -0.5;
  22414. this._projectionModeMatrix.m[10] = 0.0;
  22415. this._projectionModeMatrix.m[12] = 0.5;
  22416. this._projectionModeMatrix.m[13] = 0.5;
  22417. this._projectionModeMatrix.m[14] = 1.0;
  22418. this._projectionModeMatrix.m[15] = 1.0;
  22419. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22420. break;
  22421. default:
  22422. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22423. break;
  22424. }
  22425. return this._cachedTextureMatrix;
  22426. };
  22427. Texture.prototype.clone = function () {
  22428. var _this = this;
  22429. return BABYLON.SerializationHelper.Clone(function () {
  22430. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22431. }, this);
  22432. };
  22433. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22434. get: function () {
  22435. if (!this._onLoadObservarble) {
  22436. this._onLoadObservarble = new BABYLON.Observable();
  22437. }
  22438. return this._onLoadObservarble;
  22439. },
  22440. enumerable: true,
  22441. configurable: true
  22442. });
  22443. // Statics
  22444. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  22445. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22446. if (onLoad === void 0) { onLoad = null; }
  22447. if (onError === void 0) { onError = null; }
  22448. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  22449. };
  22450. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22451. if (parsedTexture.isCube) {
  22452. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22453. }
  22454. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22455. return null;
  22456. }
  22457. var texture = BABYLON.SerializationHelper.Parse(function () {
  22458. if (parsedTexture.customType) {
  22459. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22460. return customTexture.Parse(parsedTexture, scene, rootUrl);
  22461. }
  22462. else if (parsedTexture.mirrorPlane) {
  22463. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22464. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22465. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22466. return mirrorTexture;
  22467. }
  22468. else if (parsedTexture.isRenderTarget) {
  22469. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22470. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22471. return renderTargetTexture;
  22472. }
  22473. else {
  22474. var texture;
  22475. if (parsedTexture.base64String) {
  22476. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22477. }
  22478. else {
  22479. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22480. }
  22481. return texture;
  22482. }
  22483. }, parsedTexture, scene);
  22484. // Animations
  22485. if (parsedTexture.animations) {
  22486. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22487. var parsedAnimation = parsedTexture.animations[animationIndex];
  22488. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22489. }
  22490. }
  22491. return texture;
  22492. };
  22493. // Constants
  22494. Texture.NEAREST_SAMPLINGMODE = 1;
  22495. Texture.BILINEAR_SAMPLINGMODE = 2;
  22496. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22497. Texture.EXPLICIT_MODE = 0;
  22498. Texture.SPHERICAL_MODE = 1;
  22499. Texture.PLANAR_MODE = 2;
  22500. Texture.CUBIC_MODE = 3;
  22501. Texture.PROJECTION_MODE = 4;
  22502. Texture.SKYBOX_MODE = 5;
  22503. Texture.INVCUBIC_MODE = 6;
  22504. Texture.EQUIRECTANGULAR_MODE = 7;
  22505. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22506. Texture.CLAMP_ADDRESSMODE = 0;
  22507. Texture.WRAP_ADDRESSMODE = 1;
  22508. Texture.MIRROR_ADDRESSMODE = 2;
  22509. __decorate([
  22510. BABYLON.serialize()
  22511. ], Texture.prototype, "url", void 0);
  22512. __decorate([
  22513. BABYLON.serialize()
  22514. ], Texture.prototype, "uOffset", void 0);
  22515. __decorate([
  22516. BABYLON.serialize()
  22517. ], Texture.prototype, "vOffset", void 0);
  22518. __decorate([
  22519. BABYLON.serialize()
  22520. ], Texture.prototype, "uScale", void 0);
  22521. __decorate([
  22522. BABYLON.serialize()
  22523. ], Texture.prototype, "vScale", void 0);
  22524. __decorate([
  22525. BABYLON.serialize()
  22526. ], Texture.prototype, "uAng", void 0);
  22527. __decorate([
  22528. BABYLON.serialize()
  22529. ], Texture.prototype, "vAng", void 0);
  22530. __decorate([
  22531. BABYLON.serialize()
  22532. ], Texture.prototype, "wAng", void 0);
  22533. return Texture;
  22534. })(BABYLON.BaseTexture);
  22535. BABYLON.Texture = Texture;
  22536. })(BABYLON || (BABYLON = {}));
  22537. var BABYLON;
  22538. (function (BABYLON) {
  22539. var CubeTexture = (function (_super) {
  22540. __extends(CubeTexture, _super);
  22541. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  22542. _super.call(this, scene);
  22543. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  22544. this.name = rootUrl;
  22545. this.url = rootUrl;
  22546. this._noMipmap = noMipmap;
  22547. this.hasAlpha = false;
  22548. if (!rootUrl && !files) {
  22549. return;
  22550. }
  22551. this._texture = this._getFromCache(rootUrl, noMipmap);
  22552. if (!files) {
  22553. if (!extensions) {
  22554. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  22555. }
  22556. files = [];
  22557. for (var index = 0; index < extensions.length; index++) {
  22558. files.push(rootUrl + extensions[index]);
  22559. }
  22560. this._extensions = extensions;
  22561. }
  22562. this._files = files;
  22563. if (!this._texture) {
  22564. if (!scene.useDelayedTextureLoading) {
  22565. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  22566. }
  22567. else {
  22568. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22569. }
  22570. }
  22571. this.isCube = true;
  22572. this._textureMatrix = BABYLON.Matrix.Identity();
  22573. }
  22574. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  22575. return new CubeTexture("", scene, null, noMipmap, files);
  22576. };
  22577. // Methods
  22578. CubeTexture.prototype.delayLoad = function () {
  22579. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22580. return;
  22581. }
  22582. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22583. this._texture = this._getFromCache(this.url, this._noMipmap);
  22584. if (!this._texture) {
  22585. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  22586. }
  22587. };
  22588. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  22589. return this._textureMatrix;
  22590. };
  22591. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  22592. var texture = BABYLON.SerializationHelper.Parse(function () {
  22593. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  22594. }, parsedTexture, scene);
  22595. // Animations
  22596. if (parsedTexture.animations) {
  22597. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22598. var parsedAnimation = parsedTexture.animations[animationIndex];
  22599. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22600. }
  22601. }
  22602. return texture;
  22603. };
  22604. CubeTexture.prototype.clone = function () {
  22605. var _this = this;
  22606. return BABYLON.SerializationHelper.Clone(function () {
  22607. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  22608. }, this);
  22609. };
  22610. return CubeTexture;
  22611. })(BABYLON.BaseTexture);
  22612. BABYLON.CubeTexture = CubeTexture;
  22613. })(BABYLON || (BABYLON = {}));
  22614. var BABYLON;
  22615. (function (BABYLON) {
  22616. var RenderTargetTexture = (function (_super) {
  22617. __extends(RenderTargetTexture, _super);
  22618. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  22619. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  22620. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22621. if (isCube === void 0) { isCube = false; }
  22622. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22623. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  22624. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  22625. _super.call(this, null, scene, !generateMipMaps);
  22626. this.isCube = isCube;
  22627. /**
  22628. * Use this list to define the list of mesh you want to render.
  22629. */
  22630. this.renderList = new Array();
  22631. this.renderParticles = true;
  22632. this.renderSprites = false;
  22633. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  22634. // Events
  22635. /**
  22636. * An event triggered when the texture is unbind.
  22637. * @type {BABYLON.Observable}
  22638. */
  22639. this.onAfterUnbindObservable = new BABYLON.Observable();
  22640. /**
  22641. * An event triggered before rendering the texture
  22642. * @type {BABYLON.Observable}
  22643. */
  22644. this.onBeforeRenderObservable = new BABYLON.Observable();
  22645. /**
  22646. * An event triggered after rendering the texture
  22647. * @type {BABYLON.Observable}
  22648. */
  22649. this.onAfterRenderObservable = new BABYLON.Observable();
  22650. /**
  22651. * An event triggered after the texture clear
  22652. * @type {BABYLON.Observable}
  22653. */
  22654. this.onClearObservable = new BABYLON.Observable();
  22655. this._currentRefreshId = -1;
  22656. this._refreshRate = 1;
  22657. this.name = name;
  22658. this.isRenderTarget = true;
  22659. this._size = size;
  22660. this._generateMipMaps = generateMipMaps;
  22661. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  22662. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  22663. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22664. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22665. }
  22666. if (isCube) {
  22667. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  22668. generateMipMaps: generateMipMaps,
  22669. samplingMode: samplingMode,
  22670. generateDepthBuffer: generateDepthBuffer,
  22671. generateStencilBuffer: generateStencilBuffer
  22672. });
  22673. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  22674. this._textureMatrix = BABYLON.Matrix.Identity();
  22675. }
  22676. else {
  22677. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  22678. generateMipMaps: generateMipMaps,
  22679. type: type,
  22680. samplingMode: samplingMode,
  22681. generateDepthBuffer: generateDepthBuffer,
  22682. generateStencilBuffer: generateStencilBuffer
  22683. });
  22684. }
  22685. // Rendering groups
  22686. this._renderingManager = new BABYLON.RenderingManager(scene);
  22687. }
  22688. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  22689. get: function () {
  22690. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  22691. },
  22692. enumerable: true,
  22693. configurable: true
  22694. });
  22695. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  22696. get: function () {
  22697. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  22698. },
  22699. enumerable: true,
  22700. configurable: true
  22701. });
  22702. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  22703. get: function () {
  22704. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  22705. },
  22706. enumerable: true,
  22707. configurable: true
  22708. });
  22709. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  22710. set: function (callback) {
  22711. if (this._onAfterUnbindObserver) {
  22712. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  22713. }
  22714. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  22715. },
  22716. enumerable: true,
  22717. configurable: true
  22718. });
  22719. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  22720. set: function (callback) {
  22721. if (this._onBeforeRenderObserver) {
  22722. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22723. }
  22724. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22725. },
  22726. enumerable: true,
  22727. configurable: true
  22728. });
  22729. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  22730. set: function (callback) {
  22731. if (this._onAfterRenderObserver) {
  22732. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22733. }
  22734. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22735. },
  22736. enumerable: true,
  22737. configurable: true
  22738. });
  22739. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  22740. set: function (callback) {
  22741. if (this._onClearObserver) {
  22742. this.onClearObservable.remove(this._onClearObserver);
  22743. }
  22744. this._onClearObserver = this.onClearObservable.add(callback);
  22745. },
  22746. enumerable: true,
  22747. configurable: true
  22748. });
  22749. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  22750. this._currentRefreshId = -1;
  22751. };
  22752. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  22753. get: function () {
  22754. return this._refreshRate;
  22755. },
  22756. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22757. set: function (value) {
  22758. this._refreshRate = value;
  22759. this.resetRefreshCounter();
  22760. },
  22761. enumerable: true,
  22762. configurable: true
  22763. });
  22764. RenderTargetTexture.prototype._shouldRender = function () {
  22765. if (this._currentRefreshId === -1) {
  22766. this._currentRefreshId = 1;
  22767. return true;
  22768. }
  22769. if (this.refreshRate === this._currentRefreshId) {
  22770. this._currentRefreshId = 1;
  22771. return true;
  22772. }
  22773. this._currentRefreshId++;
  22774. return false;
  22775. };
  22776. RenderTargetTexture.prototype.isReady = function () {
  22777. if (!this.getScene().renderTargetsEnabled) {
  22778. return false;
  22779. }
  22780. return _super.prototype.isReady.call(this);
  22781. };
  22782. RenderTargetTexture.prototype.getRenderSize = function () {
  22783. return this._size;
  22784. };
  22785. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  22786. get: function () {
  22787. return true;
  22788. },
  22789. enumerable: true,
  22790. configurable: true
  22791. });
  22792. RenderTargetTexture.prototype.scale = function (ratio) {
  22793. var newSize = this._size * ratio;
  22794. this.resize(newSize, this._generateMipMaps);
  22795. };
  22796. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  22797. if (this.isCube) {
  22798. return this._textureMatrix;
  22799. }
  22800. return _super.prototype.getReflectionTextureMatrix.call(this);
  22801. };
  22802. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  22803. this.releaseInternalTexture();
  22804. if (this.isCube) {
  22805. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  22806. }
  22807. else {
  22808. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22809. }
  22810. };
  22811. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  22812. var scene = this.getScene();
  22813. if (this.useCameraPostProcesses !== undefined) {
  22814. useCameraPostProcess = this.useCameraPostProcesses;
  22815. }
  22816. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22817. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  22818. }
  22819. if (this._waitingRenderList) {
  22820. this.renderList = [];
  22821. for (var index = 0; index < this._waitingRenderList.length; index++) {
  22822. var id = this._waitingRenderList[index];
  22823. this.renderList.push(scene.getMeshByID(id));
  22824. }
  22825. delete this._waitingRenderList;
  22826. }
  22827. // Is predicate defined?
  22828. if (this.renderListPredicate) {
  22829. this.renderList.splice(0); // Clear previous renderList
  22830. var sceneMeshes = this.getScene().meshes;
  22831. for (var index = 0; index < sceneMeshes.length; index++) {
  22832. var mesh = sceneMeshes[index];
  22833. if (this.renderListPredicate(mesh)) {
  22834. this.renderList.push(mesh);
  22835. }
  22836. }
  22837. }
  22838. if (this.renderList && this.renderList.length === 0) {
  22839. return;
  22840. }
  22841. // Prepare renderingManager
  22842. this._renderingManager.reset();
  22843. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  22844. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  22845. var sceneRenderId = scene.getRenderId();
  22846. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  22847. var mesh = currentRenderList[meshIndex];
  22848. if (mesh) {
  22849. if (!mesh.isReady()) {
  22850. // Reset _currentRefreshId
  22851. this.resetRefreshCounter();
  22852. continue;
  22853. }
  22854. mesh._preActivateForIntermediateRendering(sceneRenderId);
  22855. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  22856. mesh._activate(sceneRenderId);
  22857. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22858. var subMesh = mesh.subMeshes[subIndex];
  22859. scene._activeIndices.addCount(subMesh.indexCount, false);
  22860. this._renderingManager.dispatch(subMesh);
  22861. }
  22862. }
  22863. }
  22864. }
  22865. if (this.isCube) {
  22866. for (var face = 0; face < 6; face++) {
  22867. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22868. scene.incrementRenderId();
  22869. scene.resetCachedMaterial();
  22870. }
  22871. }
  22872. else {
  22873. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22874. }
  22875. this.onAfterUnbindObservable.notifyObservers(this);
  22876. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22877. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  22878. }
  22879. scene.resetCachedMaterial();
  22880. };
  22881. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  22882. var scene = this.getScene();
  22883. var engine = scene.getEngine();
  22884. // Bind
  22885. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  22886. if (this.isCube) {
  22887. engine.bindFramebuffer(this._texture, faceIndex);
  22888. }
  22889. else {
  22890. engine.bindFramebuffer(this._texture);
  22891. }
  22892. }
  22893. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  22894. // Clear
  22895. if (this.onClearObservable.hasObservers()) {
  22896. this.onClearObservable.notifyObservers(engine);
  22897. }
  22898. else {
  22899. engine.clear(scene.clearColor, true, true, true);
  22900. }
  22901. if (!this._doNotChangeAspectRatio) {
  22902. scene.updateTransformMatrix(true);
  22903. }
  22904. // Render
  22905. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  22906. if (useCameraPostProcess) {
  22907. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  22908. }
  22909. if (!this._doNotChangeAspectRatio) {
  22910. scene.updateTransformMatrix(true);
  22911. }
  22912. this.onAfterRenderObservable.notifyObservers(faceIndex);
  22913. // Dump ?
  22914. if (dumpForDebug) {
  22915. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  22916. }
  22917. // Unbind
  22918. if (!this.isCube || faceIndex === 5) {
  22919. if (this.isCube) {
  22920. if (faceIndex === 5) {
  22921. engine.generateMipMapsForCubemap(this._texture);
  22922. }
  22923. }
  22924. engine.unBindFramebuffer(this._texture, this.isCube);
  22925. }
  22926. };
  22927. /**
  22928. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22929. * This allowed control for front to back rendering or reversly depending of the special needs.
  22930. *
  22931. * @param renderingGroupId The rendering group id corresponding to its index
  22932. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22933. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22934. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22935. */
  22936. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22937. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22938. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22939. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22940. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22941. };
  22942. /**
  22943. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22944. *
  22945. * @param renderingGroupId The rendering group id corresponding to its index
  22946. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22947. */
  22948. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  22949. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  22950. };
  22951. RenderTargetTexture.prototype.clone = function () {
  22952. var textureSize = this.getSize();
  22953. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22954. // Base texture
  22955. newTexture.hasAlpha = this.hasAlpha;
  22956. newTexture.level = this.level;
  22957. // RenderTarget Texture
  22958. newTexture.coordinatesMode = this.coordinatesMode;
  22959. newTexture.renderList = this.renderList.slice(0);
  22960. return newTexture;
  22961. };
  22962. RenderTargetTexture.prototype.serialize = function () {
  22963. if (!this.name) {
  22964. return null;
  22965. }
  22966. var serializationObject = _super.prototype.serialize.call(this);
  22967. serializationObject.renderTargetSize = this.getRenderSize();
  22968. serializationObject.renderList = [];
  22969. for (var index = 0; index < this.renderList.length; index++) {
  22970. serializationObject.renderList.push(this.renderList[index].id);
  22971. }
  22972. return serializationObject;
  22973. };
  22974. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  22975. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  22976. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  22977. return RenderTargetTexture;
  22978. })(BABYLON.Texture);
  22979. BABYLON.RenderTargetTexture = RenderTargetTexture;
  22980. })(BABYLON || (BABYLON = {}));
  22981. var BABYLON;
  22982. (function (BABYLON) {
  22983. var ProceduralTexture = (function (_super) {
  22984. __extends(ProceduralTexture, _super);
  22985. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  22986. if (generateMipMaps === void 0) { generateMipMaps = true; }
  22987. if (isCube === void 0) { isCube = false; }
  22988. _super.call(this, null, scene, !generateMipMaps);
  22989. this.isCube = isCube;
  22990. this.isEnabled = true;
  22991. this._currentRefreshId = -1;
  22992. this._refreshRate = 1;
  22993. this._vertexBuffers = {};
  22994. this._uniforms = new Array();
  22995. this._samplers = new Array();
  22996. this._textures = new Array();
  22997. this._floats = new Array();
  22998. this._floatsArrays = {};
  22999. this._colors3 = new Array();
  23000. this._colors4 = new Array();
  23001. this._vectors2 = new Array();
  23002. this._vectors3 = new Array();
  23003. this._matrices = new Array();
  23004. this._fallbackTextureUsed = false;
  23005. scene._proceduralTextures.push(this);
  23006. this.name = name;
  23007. this.isRenderTarget = true;
  23008. this._size = size;
  23009. this._generateMipMaps = generateMipMaps;
  23010. this.setFragment(fragment);
  23011. this._fallbackTexture = fallbackTexture;
  23012. var engine = scene.getEngine();
  23013. if (isCube) {
  23014. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  23015. this.setFloat("face", 0);
  23016. }
  23017. else {
  23018. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  23019. }
  23020. // VBO
  23021. var vertices = [];
  23022. vertices.push(1, 1);
  23023. vertices.push(-1, 1);
  23024. vertices.push(-1, -1);
  23025. vertices.push(1, -1);
  23026. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  23027. // Indices
  23028. var indices = [];
  23029. indices.push(0);
  23030. indices.push(1);
  23031. indices.push(2);
  23032. indices.push(0);
  23033. indices.push(2);
  23034. indices.push(3);
  23035. this._indexBuffer = engine.createIndexBuffer(indices);
  23036. }
  23037. ProceduralTexture.prototype.reset = function () {
  23038. if (this._effect === undefined) {
  23039. return;
  23040. }
  23041. var engine = this.getScene().getEngine();
  23042. engine._releaseEffect(this._effect);
  23043. };
  23044. ProceduralTexture.prototype.isReady = function () {
  23045. var _this = this;
  23046. var engine = this.getScene().getEngine();
  23047. var shaders;
  23048. if (!this._fragment) {
  23049. return false;
  23050. }
  23051. if (this._fallbackTextureUsed) {
  23052. return true;
  23053. }
  23054. if (this._fragment.fragmentElement !== undefined) {
  23055. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  23056. }
  23057. else {
  23058. shaders = { vertex: "procedural", fragment: this._fragment };
  23059. }
  23060. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  23061. _this.releaseInternalTexture();
  23062. if (_this._fallbackTexture) {
  23063. _this._texture = _this._fallbackTexture._texture;
  23064. _this._texture.references++;
  23065. }
  23066. _this._fallbackTextureUsed = true;
  23067. });
  23068. return this._effect.isReady();
  23069. };
  23070. ProceduralTexture.prototype.resetRefreshCounter = function () {
  23071. this._currentRefreshId = -1;
  23072. };
  23073. ProceduralTexture.prototype.setFragment = function (fragment) {
  23074. this._fragment = fragment;
  23075. };
  23076. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  23077. get: function () {
  23078. return this._refreshRate;
  23079. },
  23080. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23081. set: function (value) {
  23082. this._refreshRate = value;
  23083. this.resetRefreshCounter();
  23084. },
  23085. enumerable: true,
  23086. configurable: true
  23087. });
  23088. ProceduralTexture.prototype._shouldRender = function () {
  23089. if (!this.isEnabled || !this.isReady() || !this._texture) {
  23090. return false;
  23091. }
  23092. if (this._fallbackTextureUsed) {
  23093. return false;
  23094. }
  23095. if (this._currentRefreshId === -1) {
  23096. this._currentRefreshId = 1;
  23097. return true;
  23098. }
  23099. if (this.refreshRate === this._currentRefreshId) {
  23100. this._currentRefreshId = 1;
  23101. return true;
  23102. }
  23103. this._currentRefreshId++;
  23104. return false;
  23105. };
  23106. ProceduralTexture.prototype.getRenderSize = function () {
  23107. return this._size;
  23108. };
  23109. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  23110. if (this._fallbackTextureUsed) {
  23111. return;
  23112. }
  23113. this.releaseInternalTexture();
  23114. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23115. };
  23116. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  23117. if (this._uniforms.indexOf(uniformName) === -1) {
  23118. this._uniforms.push(uniformName);
  23119. }
  23120. };
  23121. ProceduralTexture.prototype.setTexture = function (name, texture) {
  23122. if (this._samplers.indexOf(name) === -1) {
  23123. this._samplers.push(name);
  23124. }
  23125. this._textures[name] = texture;
  23126. return this;
  23127. };
  23128. ProceduralTexture.prototype.setFloat = function (name, value) {
  23129. this._checkUniform(name);
  23130. this._floats[name] = value;
  23131. return this;
  23132. };
  23133. ProceduralTexture.prototype.setFloats = function (name, value) {
  23134. this._checkUniform(name);
  23135. this._floatsArrays[name] = value;
  23136. return this;
  23137. };
  23138. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23139. this._checkUniform(name);
  23140. this._colors3[name] = value;
  23141. return this;
  23142. };
  23143. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23144. this._checkUniform(name);
  23145. this._colors4[name] = value;
  23146. return this;
  23147. };
  23148. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23149. this._checkUniform(name);
  23150. this._vectors2[name] = value;
  23151. return this;
  23152. };
  23153. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23154. this._checkUniform(name);
  23155. this._vectors3[name] = value;
  23156. return this;
  23157. };
  23158. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23159. this._checkUniform(name);
  23160. this._matrices[name] = value;
  23161. return this;
  23162. };
  23163. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23164. var scene = this.getScene();
  23165. var engine = scene.getEngine();
  23166. // Render
  23167. engine.enableEffect(this._effect);
  23168. engine.setState(false);
  23169. // Texture
  23170. for (var name in this._textures) {
  23171. this._effect.setTexture(name, this._textures[name]);
  23172. }
  23173. // Float
  23174. for (name in this._floats) {
  23175. this._effect.setFloat(name, this._floats[name]);
  23176. }
  23177. // Floats
  23178. for (name in this._floatsArrays) {
  23179. this._effect.setArray(name, this._floatsArrays[name]);
  23180. }
  23181. // Color3
  23182. for (name in this._colors3) {
  23183. this._effect.setColor3(name, this._colors3[name]);
  23184. }
  23185. // Color4
  23186. for (name in this._colors4) {
  23187. var color = this._colors4[name];
  23188. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23189. }
  23190. // Vector2
  23191. for (name in this._vectors2) {
  23192. this._effect.setVector2(name, this._vectors2[name]);
  23193. }
  23194. // Vector3
  23195. for (name in this._vectors3) {
  23196. this._effect.setVector3(name, this._vectors3[name]);
  23197. }
  23198. // Matrix
  23199. for (name in this._matrices) {
  23200. this._effect.setMatrix(name, this._matrices[name]);
  23201. }
  23202. // VBOs
  23203. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23204. if (this.isCube) {
  23205. for (var face = 0; face < 6; face++) {
  23206. engine.bindFramebuffer(this._texture, face);
  23207. this._effect.setFloat("face", face);
  23208. // Clear
  23209. engine.clear(scene.clearColor, true, true, true);
  23210. // Draw order
  23211. engine.draw(true, 0, 6);
  23212. // Mipmaps
  23213. if (face === 5) {
  23214. engine.generateMipMapsForCubemap(this._texture);
  23215. }
  23216. }
  23217. }
  23218. else {
  23219. engine.bindFramebuffer(this._texture);
  23220. // Clear
  23221. engine.clear(scene.clearColor, true, true, true);
  23222. // Draw order
  23223. engine.draw(true, 0, 6);
  23224. }
  23225. // Unbind
  23226. engine.unBindFramebuffer(this._texture, this.isCube);
  23227. if (this.onGenerated) {
  23228. this.onGenerated();
  23229. }
  23230. };
  23231. ProceduralTexture.prototype.clone = function () {
  23232. var textureSize = this.getSize();
  23233. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  23234. // Base texture
  23235. newTexture.hasAlpha = this.hasAlpha;
  23236. newTexture.level = this.level;
  23237. // RenderTarget Texture
  23238. newTexture.coordinatesMode = this.coordinatesMode;
  23239. return newTexture;
  23240. };
  23241. ProceduralTexture.prototype.dispose = function () {
  23242. var index = this.getScene()._proceduralTextures.indexOf(this);
  23243. if (index >= 0) {
  23244. this.getScene()._proceduralTextures.splice(index, 1);
  23245. }
  23246. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  23247. if (vertexBuffer) {
  23248. vertexBuffer.dispose();
  23249. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  23250. }
  23251. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  23252. this._indexBuffer = null;
  23253. }
  23254. _super.prototype.dispose.call(this);
  23255. };
  23256. return ProceduralTexture;
  23257. })(BABYLON.Texture);
  23258. BABYLON.ProceduralTexture = ProceduralTexture;
  23259. })(BABYLON || (BABYLON = {}));
  23260. var BABYLON;
  23261. (function (BABYLON) {
  23262. var MirrorTexture = (function (_super) {
  23263. __extends(MirrorTexture, _super);
  23264. function MirrorTexture(name, size, scene, generateMipMaps) {
  23265. var _this = this;
  23266. _super.call(this, name, size, scene, generateMipMaps, true);
  23267. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  23268. this._transformMatrix = BABYLON.Matrix.Zero();
  23269. this._mirrorMatrix = BABYLON.Matrix.Zero();
  23270. this.onBeforeRenderObservable.add(function () {
  23271. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  23272. _this._savedViewMatrix = scene.getViewMatrix();
  23273. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  23274. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  23275. scene.clipPlane = _this.mirrorPlane;
  23276. scene.getEngine().cullBackFaces = false;
  23277. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  23278. });
  23279. this.onAfterRenderObservable.add(function () {
  23280. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  23281. scene.getEngine().cullBackFaces = true;
  23282. scene._mirroredCameraPosition = null;
  23283. delete scene.clipPlane;
  23284. });
  23285. }
  23286. MirrorTexture.prototype.clone = function () {
  23287. var textureSize = this.getSize();
  23288. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23289. // Base texture
  23290. newTexture.hasAlpha = this.hasAlpha;
  23291. newTexture.level = this.level;
  23292. // Mirror Texture
  23293. newTexture.mirrorPlane = this.mirrorPlane.clone();
  23294. newTexture.renderList = this.renderList.slice(0);
  23295. return newTexture;
  23296. };
  23297. MirrorTexture.prototype.serialize = function () {
  23298. if (!this.name) {
  23299. return null;
  23300. }
  23301. var serializationObject = _super.prototype.serialize.call(this);
  23302. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  23303. return serializationObject;
  23304. };
  23305. return MirrorTexture;
  23306. })(BABYLON.RenderTargetTexture);
  23307. BABYLON.MirrorTexture = MirrorTexture;
  23308. })(BABYLON || (BABYLON = {}));
  23309. var BABYLON;
  23310. (function (BABYLON) {
  23311. /**
  23312. * Creates a refraction texture used by refraction channel of the standard material.
  23313. * @param name the texture name
  23314. * @param size size of the underlying texture
  23315. * @param scene root scene
  23316. */
  23317. var RefractionTexture = (function (_super) {
  23318. __extends(RefractionTexture, _super);
  23319. function RefractionTexture(name, size, scene, generateMipMaps) {
  23320. var _this = this;
  23321. _super.call(this, name, size, scene, generateMipMaps, true);
  23322. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  23323. this.depth = 2.0;
  23324. this.onBeforeRenderObservable.add(function () {
  23325. scene.clipPlane = _this.refractionPlane;
  23326. });
  23327. this.onAfterRenderObservable.add(function () {
  23328. delete scene.clipPlane;
  23329. });
  23330. }
  23331. RefractionTexture.prototype.clone = function () {
  23332. var textureSize = this.getSize();
  23333. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23334. // Base texture
  23335. newTexture.hasAlpha = this.hasAlpha;
  23336. newTexture.level = this.level;
  23337. // Refraction Texture
  23338. newTexture.refractionPlane = this.refractionPlane.clone();
  23339. newTexture.renderList = this.renderList.slice(0);
  23340. newTexture.depth = this.depth;
  23341. return newTexture;
  23342. };
  23343. RefractionTexture.prototype.serialize = function () {
  23344. if (!this.name) {
  23345. return null;
  23346. }
  23347. var serializationObject = _super.prototype.serialize.call(this);
  23348. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  23349. serializationObject.depth = this.depth;
  23350. return serializationObject;
  23351. };
  23352. return RefractionTexture;
  23353. })(BABYLON.RenderTargetTexture);
  23354. BABYLON.RefractionTexture = RefractionTexture;
  23355. })(BABYLON || (BABYLON = {}));
  23356. var BABYLON;
  23357. (function (BABYLON) {
  23358. var DynamicTexture = (function (_super) {
  23359. __extends(DynamicTexture, _super);
  23360. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  23361. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23362. _super.call(this, null, scene, !generateMipMaps);
  23363. this.name = name;
  23364. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23365. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23366. this._generateMipMaps = generateMipMaps;
  23367. if (options.getContext) {
  23368. this._canvas = options;
  23369. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23370. }
  23371. else {
  23372. this._canvas = document.createElement("canvas");
  23373. if (options.width) {
  23374. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23375. }
  23376. else {
  23377. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  23378. }
  23379. }
  23380. var textureSize = this.getSize();
  23381. this._canvas.width = textureSize.width;
  23382. this._canvas.height = textureSize.height;
  23383. this._context = this._canvas.getContext("2d");
  23384. }
  23385. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  23386. get: function () {
  23387. return true;
  23388. },
  23389. enumerable: true,
  23390. configurable: true
  23391. });
  23392. DynamicTexture.prototype.scale = function (ratio) {
  23393. var textureSize = this.getSize();
  23394. textureSize.width *= ratio;
  23395. textureSize.height *= ratio;
  23396. this._canvas.width = textureSize.width;
  23397. this._canvas.height = textureSize.height;
  23398. this.releaseInternalTexture();
  23399. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  23400. };
  23401. DynamicTexture.prototype.getContext = function () {
  23402. return this._context;
  23403. };
  23404. DynamicTexture.prototype.clear = function () {
  23405. var size = this.getSize();
  23406. this._context.fillRect(0, 0, size.width, size.height);
  23407. };
  23408. DynamicTexture.prototype.update = function (invertY) {
  23409. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  23410. };
  23411. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  23412. if (update === void 0) { update = true; }
  23413. var size = this.getSize();
  23414. if (clearColor) {
  23415. this._context.fillStyle = clearColor;
  23416. this._context.fillRect(0, 0, size.width, size.height);
  23417. }
  23418. this._context.font = font;
  23419. if (x === null) {
  23420. var textSize = this._context.measureText(text);
  23421. x = (size.width - textSize.width) / 2;
  23422. }
  23423. this._context.fillStyle = color;
  23424. this._context.fillText(text, x, y);
  23425. if (update) {
  23426. this.update(invertY);
  23427. }
  23428. };
  23429. DynamicTexture.prototype.clone = function () {
  23430. var textureSize = this.getSize();
  23431. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  23432. // Base texture
  23433. newTexture.hasAlpha = this.hasAlpha;
  23434. newTexture.level = this.level;
  23435. // Dynamic Texture
  23436. newTexture.wrapU = this.wrapU;
  23437. newTexture.wrapV = this.wrapV;
  23438. return newTexture;
  23439. };
  23440. return DynamicTexture;
  23441. })(BABYLON.Texture);
  23442. BABYLON.DynamicTexture = DynamicTexture;
  23443. })(BABYLON || (BABYLON = {}));
  23444. var BABYLON;
  23445. (function (BABYLON) {
  23446. var VideoTexture = (function (_super) {
  23447. __extends(VideoTexture, _super);
  23448. /**
  23449. * Creates a video texture.
  23450. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  23451. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  23452. * @param {BABYLON.Scene} scene is obviously the current scene.
  23453. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  23454. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  23455. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  23456. */
  23457. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  23458. var _this = this;
  23459. if (generateMipMaps === void 0) { generateMipMaps = false; }
  23460. if (invertY === void 0) { invertY = false; }
  23461. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23462. _super.call(this, null, scene, !generateMipMaps, invertY);
  23463. this._autoLaunch = true;
  23464. var urls;
  23465. this.name = name;
  23466. if (urlsOrVideo instanceof HTMLVideoElement) {
  23467. this.video = urlsOrVideo;
  23468. }
  23469. else {
  23470. urls = urlsOrVideo;
  23471. this.video = document.createElement("video");
  23472. this.video.autoplay = false;
  23473. this.video.loop = true;
  23474. }
  23475. this._generateMipMaps = generateMipMaps;
  23476. this._samplingMode = samplingMode;
  23477. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  23478. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23479. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23480. }
  23481. else {
  23482. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23483. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23484. this._generateMipMaps = false;
  23485. }
  23486. if (urls) {
  23487. this.video.addEventListener("canplaythrough", function () {
  23488. _this._createTexture();
  23489. });
  23490. urls.forEach(function (url) {
  23491. var source = document.createElement("source");
  23492. source.src = url;
  23493. _this.video.appendChild(source);
  23494. });
  23495. }
  23496. else {
  23497. this._createTexture();
  23498. }
  23499. this._lastUpdate = BABYLON.Tools.Now;
  23500. }
  23501. VideoTexture.prototype._createTexture = function () {
  23502. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  23503. this._texture.isReady = true;
  23504. };
  23505. VideoTexture.prototype.update = function () {
  23506. if (this._autoLaunch) {
  23507. this._autoLaunch = false;
  23508. this.video.play();
  23509. }
  23510. var now = BABYLON.Tools.Now;
  23511. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  23512. return false;
  23513. }
  23514. this._lastUpdate = now;
  23515. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  23516. return true;
  23517. };
  23518. return VideoTexture;
  23519. })(BABYLON.Texture);
  23520. BABYLON.VideoTexture = VideoTexture;
  23521. })(BABYLON || (BABYLON = {}));
  23522. var BABYLON;
  23523. (function (BABYLON) {
  23524. var CustomProceduralTexture = (function (_super) {
  23525. __extends(CustomProceduralTexture, _super);
  23526. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  23527. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  23528. this._animate = true;
  23529. this._time = 0;
  23530. this._texturePath = texturePath;
  23531. //Try to load json
  23532. this.loadJson(texturePath);
  23533. this.refreshRate = 1;
  23534. }
  23535. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  23536. var _this = this;
  23537. var that = this;
  23538. function noConfigFile() {
  23539. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  23540. try {
  23541. that.setFragment(that._texturePath);
  23542. }
  23543. catch (ex) {
  23544. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  23545. }
  23546. }
  23547. var configFileUrl = jsonUrl + "/config.json";
  23548. var xhr = new XMLHttpRequest();
  23549. xhr.open("GET", configFileUrl, true);
  23550. xhr.addEventListener("load", function () {
  23551. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  23552. try {
  23553. _this._config = JSON.parse(xhr.response);
  23554. _this.updateShaderUniforms();
  23555. _this.updateTextures();
  23556. _this.setFragment(_this._texturePath + "/custom");
  23557. _this._animate = _this._config.animate;
  23558. _this.refreshRate = _this._config.refreshrate;
  23559. }
  23560. catch (ex) {
  23561. noConfigFile();
  23562. }
  23563. }
  23564. else {
  23565. noConfigFile();
  23566. }
  23567. }, false);
  23568. xhr.addEventListener("error", function () {
  23569. noConfigFile();
  23570. }, false);
  23571. try {
  23572. xhr.send();
  23573. }
  23574. catch (ex) {
  23575. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  23576. }
  23577. };
  23578. CustomProceduralTexture.prototype.isReady = function () {
  23579. if (!_super.prototype.isReady.call(this)) {
  23580. return false;
  23581. }
  23582. for (var name in this._textures) {
  23583. var texture = this._textures[name];
  23584. if (!texture.isReady()) {
  23585. return false;
  23586. }
  23587. }
  23588. return true;
  23589. };
  23590. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23591. if (this._animate) {
  23592. this._time += this.getScene().getAnimationRatio() * 0.03;
  23593. this.updateShaderUniforms();
  23594. }
  23595. _super.prototype.render.call(this, useCameraPostProcess);
  23596. };
  23597. CustomProceduralTexture.prototype.updateTextures = function () {
  23598. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  23599. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  23600. }
  23601. };
  23602. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  23603. if (this._config) {
  23604. for (var j = 0; j < this._config.uniforms.length; j++) {
  23605. var uniform = this._config.uniforms[j];
  23606. switch (uniform.type) {
  23607. case "float":
  23608. this.setFloat(uniform.name, uniform.value);
  23609. break;
  23610. case "color3":
  23611. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  23612. break;
  23613. case "color4":
  23614. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  23615. break;
  23616. case "vector2":
  23617. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  23618. break;
  23619. case "vector3":
  23620. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  23621. break;
  23622. }
  23623. }
  23624. }
  23625. this.setFloat("time", this._time);
  23626. };
  23627. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  23628. get: function () {
  23629. return this._animate;
  23630. },
  23631. set: function (value) {
  23632. this._animate = value;
  23633. },
  23634. enumerable: true,
  23635. configurable: true
  23636. });
  23637. return CustomProceduralTexture;
  23638. })(BABYLON.ProceduralTexture);
  23639. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  23640. })(BABYLON || (BABYLON = {}));
  23641. var BABYLON;
  23642. (function (BABYLON) {
  23643. var EffectFallbacks = (function () {
  23644. function EffectFallbacks() {
  23645. this._defines = {};
  23646. this._currentRank = 32;
  23647. this._maxRank = -1;
  23648. }
  23649. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23650. if (!this._defines[rank]) {
  23651. if (rank < this._currentRank) {
  23652. this._currentRank = rank;
  23653. }
  23654. if (rank > this._maxRank) {
  23655. this._maxRank = rank;
  23656. }
  23657. this._defines[rank] = new Array();
  23658. }
  23659. this._defines[rank].push(define);
  23660. };
  23661. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23662. this._meshRank = rank;
  23663. this._mesh = mesh;
  23664. if (rank > this._maxRank) {
  23665. this._maxRank = rank;
  23666. }
  23667. };
  23668. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23669. get: function () {
  23670. return this._currentRank <= this._maxRank;
  23671. },
  23672. enumerable: true,
  23673. configurable: true
  23674. });
  23675. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23676. var currentFallbacks = this._defines[this._currentRank];
  23677. for (var index = 0; index < currentFallbacks.length; index++) {
  23678. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23679. }
  23680. if (this._mesh && this._currentRank === this._meshRank) {
  23681. this._mesh.computeBonesUsingShaders = false;
  23682. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23683. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23684. }
  23685. this._currentRank++;
  23686. return currentDefines;
  23687. };
  23688. return EffectFallbacks;
  23689. })();
  23690. BABYLON.EffectFallbacks = EffectFallbacks;
  23691. var Effect = (function () {
  23692. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23693. var _this = this;
  23694. this._isReady = false;
  23695. this._compilationError = "";
  23696. this._valueCache = {};
  23697. this._engine = engine;
  23698. this.name = baseName;
  23699. this.defines = defines;
  23700. this._uniformsNames = uniformsNames.concat(samplers);
  23701. this._samplers = samplers;
  23702. this._attributesNames = attributesNames;
  23703. this.onError = onError;
  23704. this.onCompiled = onCompiled;
  23705. this._indexParameters = indexParameters;
  23706. var vertexSource;
  23707. var fragmentSource;
  23708. if (baseName.vertexElement) {
  23709. vertexSource = document.getElementById(baseName.vertexElement);
  23710. if (!vertexSource) {
  23711. vertexSource = baseName.vertexElement;
  23712. }
  23713. }
  23714. else {
  23715. vertexSource = baseName.vertex || baseName;
  23716. }
  23717. if (baseName.fragmentElement) {
  23718. fragmentSource = document.getElementById(baseName.fragmentElement);
  23719. if (!fragmentSource) {
  23720. fragmentSource = baseName.fragmentElement;
  23721. }
  23722. }
  23723. else {
  23724. fragmentSource = baseName.fragment || baseName;
  23725. }
  23726. this._loadVertexShader(vertexSource, function (vertexCode) {
  23727. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23728. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23729. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23730. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  23731. });
  23732. });
  23733. });
  23734. });
  23735. }
  23736. // Properties
  23737. Effect.prototype.isReady = function () {
  23738. return this._isReady;
  23739. };
  23740. Effect.prototype.getProgram = function () {
  23741. return this._program;
  23742. };
  23743. Effect.prototype.getAttributesNames = function () {
  23744. return this._attributesNames;
  23745. };
  23746. Effect.prototype.getAttributeLocation = function (index) {
  23747. return this._attributes[index];
  23748. };
  23749. Effect.prototype.getAttributeLocationByName = function (name) {
  23750. var index = this._attributesNames.indexOf(name);
  23751. return this._attributes[index];
  23752. };
  23753. Effect.prototype.getAttributesCount = function () {
  23754. return this._attributes.length;
  23755. };
  23756. Effect.prototype.getUniformIndex = function (uniformName) {
  23757. return this._uniformsNames.indexOf(uniformName);
  23758. };
  23759. Effect.prototype.getUniform = function (uniformName) {
  23760. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23761. };
  23762. Effect.prototype.getSamplers = function () {
  23763. return this._samplers;
  23764. };
  23765. Effect.prototype.getCompilationError = function () {
  23766. return this._compilationError;
  23767. };
  23768. // Methods
  23769. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23770. // DOM element ?
  23771. if (vertex instanceof HTMLElement) {
  23772. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23773. callback(vertexCode);
  23774. return;
  23775. }
  23776. // Is in local store ?
  23777. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23778. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23779. return;
  23780. }
  23781. var vertexShaderUrl;
  23782. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23783. vertexShaderUrl = vertex;
  23784. }
  23785. else {
  23786. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23787. }
  23788. // Vertex shader
  23789. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23790. };
  23791. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23792. // DOM element ?
  23793. if (fragment instanceof HTMLElement) {
  23794. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23795. callback(fragmentCode);
  23796. return;
  23797. }
  23798. // Is in local store ?
  23799. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23800. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23801. return;
  23802. }
  23803. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23804. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23805. return;
  23806. }
  23807. var fragmentShaderUrl;
  23808. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23809. fragmentShaderUrl = fragment;
  23810. }
  23811. else {
  23812. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23813. }
  23814. // Fragment shader
  23815. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23816. };
  23817. Effect.prototype._dumpShadersName = function () {
  23818. if (this.name.vertexElement) {
  23819. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  23820. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  23821. }
  23822. else if (this.name.vertex) {
  23823. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  23824. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  23825. }
  23826. else {
  23827. BABYLON.Tools.Error("Vertex shader:" + this.name);
  23828. BABYLON.Tools.Error("Fragment shader:" + this.name);
  23829. }
  23830. };
  23831. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23832. var _this = this;
  23833. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23834. var match = regex.exec(sourceCode);
  23835. var returnValue = new String(sourceCode);
  23836. while (match != null) {
  23837. var includeFile = match[1];
  23838. if (Effect.IncludesShadersStore[includeFile]) {
  23839. // Substitution
  23840. var includeContent = Effect.IncludesShadersStore[includeFile];
  23841. if (match[2]) {
  23842. var splits = match[3].split(",");
  23843. for (var index = 0; index < splits.length; index += 2) {
  23844. var source = new RegExp(splits[index], "g");
  23845. var dest = splits[index + 1];
  23846. includeContent = includeContent.replace(source, dest);
  23847. }
  23848. }
  23849. if (match[4]) {
  23850. var indexString = match[5];
  23851. if (indexString.indexOf("..") !== -1) {
  23852. var indexSplits = indexString.split("..");
  23853. var minIndex = parseInt(indexSplits[0]);
  23854. var maxIndex = parseInt(indexSplits[1]);
  23855. var sourceIncludeContent = includeContent.slice(0);
  23856. includeContent = "";
  23857. if (isNaN(maxIndex)) {
  23858. maxIndex = this._indexParameters[indexSplits[1]];
  23859. }
  23860. for (var i = minIndex; i <= maxIndex; i++) {
  23861. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23862. }
  23863. }
  23864. else {
  23865. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23866. }
  23867. }
  23868. // Replace
  23869. returnValue = returnValue.replace(match[0], includeContent);
  23870. }
  23871. else {
  23872. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23873. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23874. Effect.IncludesShadersStore[includeFile] = fileContent;
  23875. _this._processIncludes(returnValue, callback);
  23876. });
  23877. return;
  23878. }
  23879. match = regex.exec(sourceCode);
  23880. }
  23881. callback(returnValue);
  23882. };
  23883. Effect.prototype._processPrecision = function (source) {
  23884. if (source.indexOf("precision highp float") === -1) {
  23885. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23886. source = "precision mediump float;\n" + source;
  23887. }
  23888. else {
  23889. source = "precision highp float;\n" + source;
  23890. }
  23891. }
  23892. else {
  23893. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23894. source = source.replace("precision highp float", "precision mediump float");
  23895. }
  23896. }
  23897. return source;
  23898. };
  23899. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23900. try {
  23901. var engine = this._engine;
  23902. // Precision
  23903. vertexSourceCode = this._processPrecision(vertexSourceCode);
  23904. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  23905. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23906. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23907. this._attributes = engine.getAttributes(this._program, attributesNames);
  23908. var index;
  23909. for (index = 0; index < this._samplers.length; index++) {
  23910. var sampler = this.getUniform(this._samplers[index]);
  23911. if (sampler == null) {
  23912. this._samplers.splice(index, 1);
  23913. index--;
  23914. }
  23915. }
  23916. engine.bindSamplers(this);
  23917. this._isReady = true;
  23918. if (this.onCompiled) {
  23919. this.onCompiled(this);
  23920. }
  23921. }
  23922. catch (e) {
  23923. // Let's go through fallbacks then
  23924. if (fallbacks && fallbacks.isMoreFallbacks) {
  23925. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  23926. this._dumpShadersName();
  23927. defines = fallbacks.reduce(defines);
  23928. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23929. }
  23930. else {
  23931. BABYLON.Tools.Error("Unable to compile effect: ");
  23932. this._dumpShadersName();
  23933. BABYLON.Tools.Error("Defines: " + defines);
  23934. BABYLON.Tools.Error("Error: " + e.message);
  23935. this._compilationError = e.message;
  23936. if (this.onError) {
  23937. this.onError(this, this._compilationError);
  23938. }
  23939. }
  23940. }
  23941. };
  23942. Object.defineProperty(Effect.prototype, "isSupported", {
  23943. get: function () {
  23944. return this._compilationError === "";
  23945. },
  23946. enumerable: true,
  23947. configurable: true
  23948. });
  23949. Effect.prototype._bindTexture = function (channel, texture) {
  23950. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23951. };
  23952. Effect.prototype.setTexture = function (channel, texture) {
  23953. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23954. };
  23955. Effect.prototype.setTextureArray = function (channel, textures) {
  23956. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23957. var initialPos = this._samplers.indexOf(channel);
  23958. for (var index = 1; index < textures.length; index++) {
  23959. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23960. }
  23961. }
  23962. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23963. };
  23964. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23965. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23966. };
  23967. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23968. var changed = false;
  23969. var cache = this._valueCache[uniformName];
  23970. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  23971. changed = true;
  23972. cache = new BABYLON.Matrix();
  23973. }
  23974. var tm = cache.m;
  23975. var om = matrix.m;
  23976. for (var index = 0; index < 16; index++) {
  23977. if (tm[index] !== om[index]) {
  23978. tm[index] = om[index];
  23979. changed = true;
  23980. }
  23981. }
  23982. this._valueCache[uniformName] = cache;
  23983. return changed;
  23984. };
  23985. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23986. var cache = this._valueCache[uniformName];
  23987. if (!cache) {
  23988. cache = [x, y];
  23989. this._valueCache[uniformName] = cache;
  23990. return true;
  23991. }
  23992. var changed = false;
  23993. if (cache[0] !== x) {
  23994. cache[0] = x;
  23995. changed = true;
  23996. }
  23997. if (cache[1] !== y) {
  23998. cache[1] = y;
  23999. changed = true;
  24000. }
  24001. return changed;
  24002. };
  24003. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24004. var cache = this._valueCache[uniformName];
  24005. if (!cache) {
  24006. cache = [x, y, z];
  24007. this._valueCache[uniformName] = cache;
  24008. return true;
  24009. }
  24010. var changed = false;
  24011. if (cache[0] !== x) {
  24012. cache[0] = x;
  24013. changed = true;
  24014. }
  24015. if (cache[1] !== y) {
  24016. cache[1] = y;
  24017. changed = true;
  24018. }
  24019. if (cache[2] !== z) {
  24020. cache[2] = z;
  24021. changed = true;
  24022. }
  24023. return changed;
  24024. };
  24025. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24026. var cache = this._valueCache[uniformName];
  24027. if (!cache) {
  24028. cache = [x, y, z, w];
  24029. this._valueCache[uniformName] = cache;
  24030. return true;
  24031. }
  24032. var changed = false;
  24033. if (cache[0] !== x) {
  24034. cache[0] = x;
  24035. changed = true;
  24036. }
  24037. if (cache[1] !== y) {
  24038. cache[1] = y;
  24039. changed = true;
  24040. }
  24041. if (cache[2] !== z) {
  24042. cache[2] = z;
  24043. changed = true;
  24044. }
  24045. if (cache[3] !== w) {
  24046. cache[3] = w;
  24047. changed = true;
  24048. }
  24049. return changed;
  24050. };
  24051. Effect.prototype.setIntArray = function (uniformName, array) {
  24052. this._valueCache[uniformName] = null;
  24053. this._engine.setIntArray(this.getUniform(uniformName), array);
  24054. return this;
  24055. };
  24056. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24057. this._valueCache[uniformName] = null;
  24058. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24059. return this;
  24060. };
  24061. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24062. this._valueCache[uniformName] = null;
  24063. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24064. return this;
  24065. };
  24066. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24067. this._valueCache[uniformName] = null;
  24068. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24069. return this;
  24070. };
  24071. Effect.prototype.setFloatArray = function (uniformName, array) {
  24072. this._valueCache[uniformName] = null;
  24073. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24074. return this;
  24075. };
  24076. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24077. this._valueCache[uniformName] = null;
  24078. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24079. return this;
  24080. };
  24081. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24082. this._valueCache[uniformName] = null;
  24083. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24084. return this;
  24085. };
  24086. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24087. this._valueCache[uniformName] = null;
  24088. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24089. return this;
  24090. };
  24091. Effect.prototype.setArray = function (uniformName, array) {
  24092. this._valueCache[uniformName] = null;
  24093. this._engine.setArray(this.getUniform(uniformName), array);
  24094. return this;
  24095. };
  24096. Effect.prototype.setArray2 = function (uniformName, array) {
  24097. this._valueCache[uniformName] = null;
  24098. this._engine.setArray2(this.getUniform(uniformName), array);
  24099. return this;
  24100. };
  24101. Effect.prototype.setArray3 = function (uniformName, array) {
  24102. this._valueCache[uniformName] = null;
  24103. this._engine.setArray3(this.getUniform(uniformName), array);
  24104. return this;
  24105. };
  24106. Effect.prototype.setArray4 = function (uniformName, array) {
  24107. this._valueCache[uniformName] = null;
  24108. this._engine.setArray4(this.getUniform(uniformName), array);
  24109. return this;
  24110. };
  24111. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24112. this._valueCache[uniformName] = null;
  24113. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24114. return this;
  24115. };
  24116. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24117. if (this._cacheMatrix(uniformName, matrix)) {
  24118. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24119. }
  24120. return this;
  24121. };
  24122. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24123. this._valueCache[uniformName] = null;
  24124. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24125. return this;
  24126. };
  24127. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24128. this._valueCache[uniformName] = null;
  24129. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24130. return this;
  24131. };
  24132. Effect.prototype.setFloat = function (uniformName, value) {
  24133. var cache = this._valueCache[uniformName];
  24134. if (cache !== undefined && cache === value)
  24135. return this;
  24136. this._valueCache[uniformName] = value;
  24137. this._engine.setFloat(this.getUniform(uniformName), value);
  24138. return this;
  24139. };
  24140. Effect.prototype.setBool = function (uniformName, bool) {
  24141. var cache = this._valueCache[uniformName];
  24142. if (cache !== undefined && cache === bool)
  24143. return this;
  24144. this._valueCache[uniformName] = bool;
  24145. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24146. return this;
  24147. };
  24148. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24149. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24150. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24151. }
  24152. return this;
  24153. };
  24154. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24155. if (this._cacheFloat2(uniformName, x, y)) {
  24156. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24157. }
  24158. return this;
  24159. };
  24160. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24161. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24162. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24163. }
  24164. return this;
  24165. };
  24166. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24167. if (this._cacheFloat3(uniformName, x, y, z)) {
  24168. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24169. }
  24170. return this;
  24171. };
  24172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24175. }
  24176. return this;
  24177. };
  24178. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24179. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24180. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24181. }
  24182. return this;
  24183. };
  24184. Effect.prototype.setColor3 = function (uniformName, color3) {
  24185. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24186. this._engine.setColor3(this.getUniform(uniformName), color3);
  24187. }
  24188. return this;
  24189. };
  24190. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24191. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24192. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24193. }
  24194. return this;
  24195. };
  24196. // Statics
  24197. Effect.ShadersStore = {};
  24198. Effect.IncludesShadersStore = {};
  24199. return Effect;
  24200. })();
  24201. BABYLON.Effect = Effect;
  24202. })(BABYLON || (BABYLON = {}));
  24203. var BABYLON;
  24204. (function (BABYLON) {
  24205. var MaterialHelper = (function () {
  24206. function MaterialHelper() {
  24207. }
  24208. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  24209. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24210. var lightIndex = 0;
  24211. var needNormals = false;
  24212. var needRebuild = false;
  24213. var needShadows = false;
  24214. for (var index = 0; index < scene.lights.length; index++) {
  24215. var light = scene.lights[index];
  24216. if (!light.isEnabled()) {
  24217. continue;
  24218. }
  24219. // Excluded check
  24220. if (light._excludedMeshesIds.length > 0) {
  24221. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  24222. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  24223. if (excludedMesh) {
  24224. light.excludedMeshes.push(excludedMesh);
  24225. }
  24226. }
  24227. light._excludedMeshesIds = [];
  24228. }
  24229. // Included check
  24230. if (light._includedOnlyMeshesIds.length > 0) {
  24231. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  24232. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  24233. if (includedOnlyMesh) {
  24234. light.includedOnlyMeshes.push(includedOnlyMesh);
  24235. }
  24236. }
  24237. light._includedOnlyMeshesIds = [];
  24238. }
  24239. if (!light.canAffectMesh(mesh)) {
  24240. continue;
  24241. }
  24242. needNormals = true;
  24243. if (defines["LIGHT" + lightIndex] === undefined) {
  24244. needRebuild = true;
  24245. }
  24246. defines["LIGHT" + lightIndex] = true;
  24247. var type;
  24248. if (light instanceof BABYLON.SpotLight) {
  24249. type = "SPOTLIGHT" + lightIndex;
  24250. }
  24251. else if (light instanceof BABYLON.HemisphericLight) {
  24252. type = "HEMILIGHT" + lightIndex;
  24253. }
  24254. else if (light instanceof BABYLON.PointLight) {
  24255. type = "POINTLIGHT" + lightIndex;
  24256. }
  24257. else {
  24258. type = "DIRLIGHT" + lightIndex;
  24259. }
  24260. if (defines[type] === undefined) {
  24261. needRebuild = true;
  24262. }
  24263. defines[type] = true;
  24264. // Specular
  24265. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  24266. defines["SPECULARTERM"] = true;
  24267. }
  24268. // Shadows
  24269. if (scene.shadowsEnabled) {
  24270. var shadowGenerator = light.getShadowGenerator();
  24271. if (mesh && mesh.receiveShadows && shadowGenerator) {
  24272. if (defines["SHADOW" + lightIndex] === undefined) {
  24273. needRebuild = true;
  24274. }
  24275. defines["SHADOW" + lightIndex] = true;
  24276. defines["SHADOWS"] = true;
  24277. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  24278. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  24279. needRebuild = true;
  24280. }
  24281. defines["SHADOWVSM" + lightIndex] = true;
  24282. }
  24283. if (shadowGenerator.usePoissonSampling) {
  24284. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  24285. needRebuild = true;
  24286. }
  24287. defines["SHADOWPCF" + lightIndex] = true;
  24288. }
  24289. needShadows = true;
  24290. }
  24291. }
  24292. lightIndex++;
  24293. if (lightIndex === maxSimultaneousLights)
  24294. break;
  24295. }
  24296. var caps = scene.getEngine().getCaps();
  24297. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  24298. if (defines["SHADOWFULLFLOAT"] === undefined) {
  24299. needRebuild = true;
  24300. }
  24301. defines["SHADOWFULLFLOAT"] = true;
  24302. }
  24303. if (needRebuild) {
  24304. defines.rebuild();
  24305. }
  24306. return needNormals;
  24307. };
  24308. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  24309. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24310. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24311. if (!defines["LIGHT" + lightIndex]) {
  24312. break;
  24313. }
  24314. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  24315. samplersList.push("shadowSampler" + lightIndex);
  24316. }
  24317. };
  24318. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24319. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24320. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24321. if (!defines["LIGHT" + lightIndex]) {
  24322. break;
  24323. }
  24324. if (lightIndex > 0) {
  24325. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24326. }
  24327. if (defines["SHADOW" + lightIndex]) {
  24328. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24329. }
  24330. if (defines["SHADOWPCF" + lightIndex]) {
  24331. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24332. }
  24333. if (defines["SHADOWVSM" + lightIndex]) {
  24334. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  24335. }
  24336. }
  24337. };
  24338. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24339. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24340. fallbacks.addCPUSkinningFallback(0, mesh);
  24341. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24342. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24343. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24344. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24345. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24346. }
  24347. }
  24348. };
  24349. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24350. if (defines["INSTANCES"]) {
  24351. attribs.push("world0");
  24352. attribs.push("world1");
  24353. attribs.push("world2");
  24354. attribs.push("world3");
  24355. }
  24356. };
  24357. // Bindings
  24358. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  24359. var shadowGenerator = light.getShadowGenerator();
  24360. if (mesh.receiveShadows && shadowGenerator) {
  24361. if (!light.needCube()) {
  24362. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  24363. }
  24364. else {
  24365. if (!depthValuesAlreadySet) {
  24366. depthValuesAlreadySet = true;
  24367. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  24368. }
  24369. }
  24370. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  24371. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  24372. }
  24373. return depthValuesAlreadySet;
  24374. };
  24375. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24376. if (light instanceof BABYLON.PointLight) {
  24377. // Point Light
  24378. light.transferToEffect(effect, "vLightData" + lightIndex);
  24379. }
  24380. else if (light instanceof BABYLON.DirectionalLight) {
  24381. // Directional Light
  24382. light.transferToEffect(effect, "vLightData" + lightIndex);
  24383. }
  24384. else if (light instanceof BABYLON.SpotLight) {
  24385. // Spot Light
  24386. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  24387. }
  24388. else if (light instanceof BABYLON.HemisphericLight) {
  24389. // Hemispheric Light
  24390. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  24391. }
  24392. };
  24393. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  24394. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24395. var lightIndex = 0;
  24396. var depthValuesAlreadySet = false;
  24397. for (var index = 0; index < scene.lights.length; index++) {
  24398. var light = scene.lights[index];
  24399. if (!light.isEnabled()) {
  24400. continue;
  24401. }
  24402. if (!light.canAffectMesh(mesh)) {
  24403. continue;
  24404. }
  24405. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24406. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  24407. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  24408. if (defines["SPECULARTERM"]) {
  24409. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  24410. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  24411. }
  24412. // Shadows
  24413. if (scene.shadowsEnabled) {
  24414. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  24415. }
  24416. lightIndex++;
  24417. if (lightIndex === maxSimultaneousLights)
  24418. break;
  24419. }
  24420. };
  24421. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24422. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24423. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24424. effect.setColor3("vFogColor", scene.fogColor);
  24425. }
  24426. };
  24427. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24428. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24429. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  24430. }
  24431. };
  24432. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24433. if (defines["LOGARITHMICDEPTH"]) {
  24434. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24435. }
  24436. };
  24437. MaterialHelper.BindClipPlane = function (effect, scene) {
  24438. if (scene.clipPlane) {
  24439. var clipPlane = scene.clipPlane;
  24440. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24441. }
  24442. };
  24443. return MaterialHelper;
  24444. })();
  24445. BABYLON.MaterialHelper = MaterialHelper;
  24446. })(BABYLON || (BABYLON = {}));
  24447. var BABYLON;
  24448. (function (BABYLON) {
  24449. var FresnelParameters = (function () {
  24450. function FresnelParameters() {
  24451. this.isEnabled = true;
  24452. this.leftColor = BABYLON.Color3.White();
  24453. this.rightColor = BABYLON.Color3.Black();
  24454. this.bias = 0;
  24455. this.power = 1;
  24456. }
  24457. FresnelParameters.prototype.clone = function () {
  24458. var newFresnelParameters = new FresnelParameters();
  24459. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  24460. return new FresnelParameters;
  24461. };
  24462. FresnelParameters.prototype.serialize = function () {
  24463. var serializationObject = {};
  24464. serializationObject.isEnabled = this.isEnabled;
  24465. serializationObject.leftColor = this.leftColor;
  24466. serializationObject.rightColor = this.rightColor;
  24467. serializationObject.bias = this.bias;
  24468. serializationObject.power = this.power;
  24469. return serializationObject;
  24470. };
  24471. FresnelParameters.Parse = function (parsedFresnelParameters) {
  24472. var fresnelParameters = new FresnelParameters();
  24473. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  24474. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  24475. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  24476. fresnelParameters.bias = parsedFresnelParameters.bias;
  24477. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  24478. return fresnelParameters;
  24479. };
  24480. return FresnelParameters;
  24481. })();
  24482. BABYLON.FresnelParameters = FresnelParameters;
  24483. })(BABYLON || (BABYLON = {}));
  24484. var BABYLON;
  24485. (function (BABYLON) {
  24486. var MaterialDefines = (function () {
  24487. function MaterialDefines() {
  24488. }
  24489. MaterialDefines.prototype.rebuild = function () {
  24490. if (this._keys) {
  24491. delete this._keys;
  24492. }
  24493. this._keys = Object.keys(this);
  24494. };
  24495. MaterialDefines.prototype.isEqual = function (other) {
  24496. if (this._keys.length !== other._keys.length) {
  24497. return false;
  24498. }
  24499. for (var index = 0; index < this._keys.length; index++) {
  24500. var prop = this._keys[index];
  24501. if (this[prop] !== other[prop]) {
  24502. return false;
  24503. }
  24504. }
  24505. return true;
  24506. };
  24507. MaterialDefines.prototype.cloneTo = function (other) {
  24508. if (this._keys.length !== other._keys.length) {
  24509. other._keys = this._keys.slice(0);
  24510. }
  24511. for (var index = 0; index < this._keys.length; index++) {
  24512. var prop = this._keys[index];
  24513. other[prop] = this[prop];
  24514. }
  24515. };
  24516. MaterialDefines.prototype.reset = function () {
  24517. for (var index = 0; index < this._keys.length; index++) {
  24518. var prop = this._keys[index];
  24519. if (typeof (this[prop]) === "number") {
  24520. this[prop] = 0;
  24521. }
  24522. else {
  24523. this[prop] = false;
  24524. }
  24525. }
  24526. };
  24527. MaterialDefines.prototype.toString = function () {
  24528. var result = "";
  24529. for (var index = 0; index < this._keys.length; index++) {
  24530. var prop = this._keys[index];
  24531. if (typeof (this[prop]) === "number") {
  24532. result += "#define " + prop + " " + this[prop] + "\n";
  24533. }
  24534. else if (this[prop]) {
  24535. result += "#define " + prop + "\n";
  24536. }
  24537. }
  24538. return result;
  24539. };
  24540. return MaterialDefines;
  24541. })();
  24542. BABYLON.MaterialDefines = MaterialDefines;
  24543. var Material = (function () {
  24544. function Material(name, scene, doNotAdd) {
  24545. this.name = name;
  24546. this.checkReadyOnEveryCall = false;
  24547. this.checkReadyOnlyOnce = false;
  24548. this.state = "";
  24549. this.alpha = 1.0;
  24550. this.backFaceCulling = true;
  24551. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  24552. /**
  24553. * An event triggered when the material is disposed.
  24554. * @type {BABYLON.Observable}
  24555. */
  24556. this.onDisposeObservable = new BABYLON.Observable();
  24557. /**
  24558. * An event triggered when the material is bound.
  24559. * @type {BABYLON.Observable}
  24560. */
  24561. this.onBindObservable = new BABYLON.Observable();
  24562. /**
  24563. * An event triggered when the material is unbound.
  24564. * @type {BABYLON.Observable}
  24565. */
  24566. this.onUnBindObservable = new BABYLON.Observable();
  24567. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  24568. this.disableDepthWrite = false;
  24569. this.fogEnabled = true;
  24570. this.pointSize = 1.0;
  24571. this.zOffset = 0;
  24572. this._wasPreviouslyReady = false;
  24573. this._fillMode = Material.TriangleFillMode;
  24574. this.id = name;
  24575. this._scene = scene;
  24576. if (!doNotAdd) {
  24577. scene.materials.push(this);
  24578. }
  24579. }
  24580. Object.defineProperty(Material, "TriangleFillMode", {
  24581. get: function () {
  24582. return Material._TriangleFillMode;
  24583. },
  24584. enumerable: true,
  24585. configurable: true
  24586. });
  24587. Object.defineProperty(Material, "WireFrameFillMode", {
  24588. get: function () {
  24589. return Material._WireFrameFillMode;
  24590. },
  24591. enumerable: true,
  24592. configurable: true
  24593. });
  24594. Object.defineProperty(Material, "PointFillMode", {
  24595. get: function () {
  24596. return Material._PointFillMode;
  24597. },
  24598. enumerable: true,
  24599. configurable: true
  24600. });
  24601. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24602. get: function () {
  24603. return Material._ClockWiseSideOrientation;
  24604. },
  24605. enumerable: true,
  24606. configurable: true
  24607. });
  24608. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24609. get: function () {
  24610. return Material._CounterClockWiseSideOrientation;
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. Object.defineProperty(Material.prototype, "onDispose", {
  24616. set: function (callback) {
  24617. if (this._onDisposeObserver) {
  24618. this.onDisposeObservable.remove(this._onDisposeObserver);
  24619. }
  24620. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24621. },
  24622. enumerable: true,
  24623. configurable: true
  24624. });
  24625. Object.defineProperty(Material.prototype, "onBind", {
  24626. set: function (callback) {
  24627. if (this._onBindObserver) {
  24628. this.onBindObservable.remove(this._onBindObserver);
  24629. }
  24630. this._onBindObserver = this.onBindObservable.add(callback);
  24631. },
  24632. enumerable: true,
  24633. configurable: true
  24634. });
  24635. Object.defineProperty(Material.prototype, "wireframe", {
  24636. get: function () {
  24637. return this._fillMode === Material.WireFrameFillMode;
  24638. },
  24639. set: function (value) {
  24640. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24641. },
  24642. enumerable: true,
  24643. configurable: true
  24644. });
  24645. Object.defineProperty(Material.prototype, "pointsCloud", {
  24646. get: function () {
  24647. return this._fillMode === Material.PointFillMode;
  24648. },
  24649. set: function (value) {
  24650. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24651. },
  24652. enumerable: true,
  24653. configurable: true
  24654. });
  24655. Object.defineProperty(Material.prototype, "fillMode", {
  24656. get: function () {
  24657. return this._fillMode;
  24658. },
  24659. set: function (value) {
  24660. this._fillMode = value;
  24661. },
  24662. enumerable: true,
  24663. configurable: true
  24664. });
  24665. /**
  24666. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24667. * subclasses should override adding information pertainent to themselves
  24668. */
  24669. Material.prototype.toString = function (fullDetails) {
  24670. var ret = "Name: " + this.name;
  24671. if (fullDetails) {
  24672. }
  24673. return ret;
  24674. };
  24675. Object.defineProperty(Material.prototype, "isFrozen", {
  24676. get: function () {
  24677. return this.checkReadyOnlyOnce;
  24678. },
  24679. enumerable: true,
  24680. configurable: true
  24681. });
  24682. Material.prototype.freeze = function () {
  24683. this.checkReadyOnlyOnce = true;
  24684. };
  24685. Material.prototype.unfreeze = function () {
  24686. this.checkReadyOnlyOnce = false;
  24687. };
  24688. Material.prototype.isReady = function (mesh, useInstances) {
  24689. return true;
  24690. };
  24691. Material.prototype.getEffect = function () {
  24692. return this._effect;
  24693. };
  24694. Material.prototype.getScene = function () {
  24695. return this._scene;
  24696. };
  24697. Material.prototype.needAlphaBlending = function () {
  24698. return (this.alpha < 1.0);
  24699. };
  24700. Material.prototype.needAlphaTesting = function () {
  24701. return false;
  24702. };
  24703. Material.prototype.getAlphaTestTexture = function () {
  24704. return null;
  24705. };
  24706. Material.prototype.markDirty = function () {
  24707. this._wasPreviouslyReady = false;
  24708. };
  24709. Material.prototype._preBind = function () {
  24710. var engine = this._scene.getEngine();
  24711. engine.enableEffect(this._effect);
  24712. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  24713. };
  24714. Material.prototype.bind = function (world, mesh) {
  24715. this._scene._cachedMaterial = this;
  24716. this.onBindObservable.notifyObservers(mesh);
  24717. if (this.disableDepthWrite) {
  24718. var engine = this._scene.getEngine();
  24719. this._cachedDepthWriteState = engine.getDepthWrite();
  24720. engine.setDepthWrite(false);
  24721. }
  24722. };
  24723. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24724. };
  24725. Material.prototype.unbind = function () {
  24726. this.onUnBindObservable.notifyObservers(this);
  24727. if (this.disableDepthWrite) {
  24728. var engine = this._scene.getEngine();
  24729. engine.setDepthWrite(this._cachedDepthWriteState);
  24730. }
  24731. };
  24732. Material.prototype.clone = function (name) {
  24733. return null;
  24734. };
  24735. Material.prototype.getBindedMeshes = function () {
  24736. var result = new Array();
  24737. for (var index = 0; index < this._scene.meshes.length; index++) {
  24738. var mesh = this._scene.meshes[index];
  24739. if (mesh.material === this) {
  24740. result.push(mesh);
  24741. }
  24742. }
  24743. return result;
  24744. };
  24745. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24746. // Animations
  24747. this.getScene().stopAnimation(this);
  24748. // Remove from scene
  24749. var index = this._scene.materials.indexOf(this);
  24750. if (index >= 0) {
  24751. this._scene.materials.splice(index, 1);
  24752. }
  24753. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24754. if (forceDisposeEffect && this._effect) {
  24755. this._scene.getEngine()._releaseEffect(this._effect);
  24756. this._effect = null;
  24757. }
  24758. // Remove from meshes
  24759. for (index = 0; index < this._scene.meshes.length; index++) {
  24760. var mesh = this._scene.meshes[index];
  24761. if (mesh.material === this) {
  24762. mesh.material = null;
  24763. }
  24764. }
  24765. // Callback
  24766. this.onDisposeObservable.notifyObservers(this);
  24767. this.onDisposeObservable.clear();
  24768. this.onBindObservable.clear();
  24769. };
  24770. Material.prototype.serialize = function () {
  24771. return BABYLON.SerializationHelper.Serialize(this);
  24772. };
  24773. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24774. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24775. multiMaterial.id = parsedMultiMaterial.id;
  24776. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24777. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24778. var subMatId = parsedMultiMaterial.materials[matIndex];
  24779. if (subMatId) {
  24780. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24781. }
  24782. else {
  24783. multiMaterial.subMaterials.push(null);
  24784. }
  24785. }
  24786. return multiMaterial;
  24787. };
  24788. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24789. if (!parsedMaterial.customType) {
  24790. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24791. }
  24792. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24793. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24794. ;
  24795. };
  24796. Material._TriangleFillMode = 0;
  24797. Material._WireFrameFillMode = 1;
  24798. Material._PointFillMode = 2;
  24799. Material._ClockWiseSideOrientation = 0;
  24800. Material._CounterClockWiseSideOrientation = 1;
  24801. __decorate([
  24802. BABYLON.serialize()
  24803. ], Material.prototype, "id", void 0);
  24804. __decorate([
  24805. BABYLON.serialize()
  24806. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24807. __decorate([
  24808. BABYLON.serialize()
  24809. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24810. __decorate([
  24811. BABYLON.serialize()
  24812. ], Material.prototype, "state", void 0);
  24813. __decorate([
  24814. BABYLON.serialize()
  24815. ], Material.prototype, "alpha", void 0);
  24816. __decorate([
  24817. BABYLON.serialize()
  24818. ], Material.prototype, "backFaceCulling", void 0);
  24819. __decorate([
  24820. BABYLON.serialize()
  24821. ], Material.prototype, "sideOrientation", void 0);
  24822. __decorate([
  24823. BABYLON.serialize()
  24824. ], Material.prototype, "alphaMode", void 0);
  24825. __decorate([
  24826. BABYLON.serialize()
  24827. ], Material.prototype, "disableDepthWrite", void 0);
  24828. __decorate([
  24829. BABYLON.serialize()
  24830. ], Material.prototype, "fogEnabled", void 0);
  24831. __decorate([
  24832. BABYLON.serialize()
  24833. ], Material.prototype, "pointSize", void 0);
  24834. __decorate([
  24835. BABYLON.serialize()
  24836. ], Material.prototype, "zOffset", void 0);
  24837. __decorate([
  24838. BABYLON.serialize()
  24839. ], Material.prototype, "wireframe", null);
  24840. __decorate([
  24841. BABYLON.serialize()
  24842. ], Material.prototype, "pointsCloud", null);
  24843. __decorate([
  24844. BABYLON.serialize()
  24845. ], Material.prototype, "fillMode", null);
  24846. return Material;
  24847. })();
  24848. BABYLON.Material = Material;
  24849. })(BABYLON || (BABYLON = {}));
  24850. var BABYLON;
  24851. (function (BABYLON) {
  24852. var StandardMaterialDefines = (function (_super) {
  24853. __extends(StandardMaterialDefines, _super);
  24854. function StandardMaterialDefines() {
  24855. _super.call(this);
  24856. this.DIFFUSE = false;
  24857. this.AMBIENT = false;
  24858. this.OPACITY = false;
  24859. this.OPACITYRGB = false;
  24860. this.REFLECTION = false;
  24861. this.EMISSIVE = false;
  24862. this.SPECULAR = false;
  24863. this.BUMP = false;
  24864. this.PARALLAX = false;
  24865. this.PARALLAXOCCLUSION = false;
  24866. this.SPECULAROVERALPHA = false;
  24867. this.CLIPPLANE = false;
  24868. this.ALPHATEST = false;
  24869. this.ALPHAFROMDIFFUSE = false;
  24870. this.POINTSIZE = false;
  24871. this.FOG = false;
  24872. this.SPECULARTERM = false;
  24873. this.DIFFUSEFRESNEL = false;
  24874. this.OPACITYFRESNEL = false;
  24875. this.REFLECTIONFRESNEL = false;
  24876. this.REFRACTIONFRESNEL = false;
  24877. this.EMISSIVEFRESNEL = false;
  24878. this.FRESNEL = false;
  24879. this.NORMAL = false;
  24880. this.UV1 = false;
  24881. this.UV2 = false;
  24882. this.VERTEXCOLOR = false;
  24883. this.VERTEXALPHA = false;
  24884. this.NUM_BONE_INFLUENCERS = 0;
  24885. this.BonesPerMesh = 0;
  24886. this.INSTANCES = false;
  24887. this.GLOSSINESS = false;
  24888. this.ROUGHNESS = false;
  24889. this.EMISSIVEASILLUMINATION = false;
  24890. this.LINKEMISSIVEWITHDIFFUSE = false;
  24891. this.REFLECTIONFRESNELFROMSPECULAR = false;
  24892. this.LIGHTMAP = false;
  24893. this.USELIGHTMAPASSHADOWMAP = false;
  24894. this.REFLECTIONMAP_3D = false;
  24895. this.REFLECTIONMAP_SPHERICAL = false;
  24896. this.REFLECTIONMAP_PLANAR = false;
  24897. this.REFLECTIONMAP_CUBIC = false;
  24898. this.REFLECTIONMAP_PROJECTION = false;
  24899. this.REFLECTIONMAP_SKYBOX = false;
  24900. this.REFLECTIONMAP_EXPLICIT = false;
  24901. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  24902. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  24903. this.INVERTCUBICMAP = false;
  24904. this.LOGARITHMICDEPTH = false;
  24905. this.REFRACTION = false;
  24906. this.REFRACTIONMAP_3D = false;
  24907. this.REFLECTIONOVERALPHA = false;
  24908. this.INVERTNORMALMAPX = false;
  24909. this.INVERTNORMALMAPY = false;
  24910. this.SHADOWFULLFLOAT = false;
  24911. this.CAMERACOLORGRADING = false;
  24912. this.CAMERACOLORCURVES = false;
  24913. this.rebuild();
  24914. }
  24915. return StandardMaterialDefines;
  24916. })(BABYLON.MaterialDefines);
  24917. var StandardMaterial = (function (_super) {
  24918. __extends(StandardMaterial, _super);
  24919. function StandardMaterial(name, scene) {
  24920. var _this = this;
  24921. _super.call(this, name, scene);
  24922. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24923. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  24924. this.specularColor = new BABYLON.Color3(1, 1, 1);
  24925. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  24926. this.specularPower = 64;
  24927. this.useAlphaFromDiffuseTexture = false;
  24928. this.useEmissiveAsIllumination = false;
  24929. this.linkEmissiveWithDiffuse = false;
  24930. this.useReflectionFresnelFromSpecular = false;
  24931. this.useSpecularOverAlpha = false;
  24932. this.useReflectionOverAlpha = false;
  24933. this.disableLighting = false;
  24934. this.useParallax = false;
  24935. this.useParallaxOcclusion = false;
  24936. this.parallaxScaleBias = 0.05;
  24937. this.roughness = 0;
  24938. this.indexOfRefraction = 0.98;
  24939. this.invertRefractionY = true;
  24940. this.useLightmapAsShadowmap = false;
  24941. this.useGlossinessFromSpecularMapAlpha = false;
  24942. this.maxSimultaneousLights = 4;
  24943. /**
  24944. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  24945. */
  24946. this.invertNormalMapX = false;
  24947. /**
  24948. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  24949. */
  24950. this.invertNormalMapY = false;
  24951. /**
  24952. * Color Grading 2D Lookup Texture.
  24953. * This allows special effects like sepia, black and white to sixties rendering style.
  24954. */
  24955. this.cameraColorGradingTexture = null;
  24956. /**
  24957. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  24958. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  24959. * 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;
  24960. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  24961. */
  24962. this.cameraColorCurves = null;
  24963. this._renderTargets = new BABYLON.SmartArray(16);
  24964. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  24965. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  24966. this._defines = new StandardMaterialDefines();
  24967. this._cachedDefines = new StandardMaterialDefines();
  24968. this._cachedDefines.BonesPerMesh = -1;
  24969. this.getRenderTargetTextures = function () {
  24970. _this._renderTargets.reset();
  24971. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  24972. _this._renderTargets.push(_this.reflectionTexture);
  24973. }
  24974. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  24975. _this._renderTargets.push(_this.refractionTexture);
  24976. }
  24977. return _this._renderTargets;
  24978. };
  24979. }
  24980. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  24981. get: function () {
  24982. return this._useLogarithmicDepth;
  24983. },
  24984. set: function (value) {
  24985. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  24986. },
  24987. enumerable: true,
  24988. configurable: true
  24989. });
  24990. StandardMaterial.prototype.needAlphaBlending = function () {
  24991. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  24992. };
  24993. StandardMaterial.prototype.needAlphaTesting = function () {
  24994. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  24995. };
  24996. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  24997. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  24998. };
  24999. StandardMaterial.prototype.getAlphaTestTexture = function () {
  25000. return this.diffuseTexture;
  25001. };
  25002. // Methods
  25003. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  25004. if (!mesh) {
  25005. return true;
  25006. }
  25007. if (this._defines.INSTANCES !== useInstances) {
  25008. return false;
  25009. }
  25010. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  25011. return true;
  25012. }
  25013. return false;
  25014. };
  25015. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  25016. if (this.isFrozen) {
  25017. if (this._wasPreviouslyReady) {
  25018. return true;
  25019. }
  25020. }
  25021. var scene = this.getScene();
  25022. if (!this.checkReadyOnEveryCall) {
  25023. if (this._renderId === scene.getRenderId()) {
  25024. if (this._checkCache(scene, mesh, useInstances)) {
  25025. return true;
  25026. }
  25027. }
  25028. }
  25029. var engine = scene.getEngine();
  25030. var needNormals = false;
  25031. var needUVs = false;
  25032. this._defines.reset();
  25033. // Textures
  25034. if (scene.texturesEnabled) {
  25035. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25036. if (!this.diffuseTexture.isReady()) {
  25037. return false;
  25038. }
  25039. else {
  25040. needUVs = true;
  25041. this._defines.DIFFUSE = true;
  25042. }
  25043. }
  25044. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25045. if (!this.ambientTexture.isReady()) {
  25046. return false;
  25047. }
  25048. else {
  25049. needUVs = true;
  25050. this._defines.AMBIENT = true;
  25051. }
  25052. }
  25053. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25054. if (!this.opacityTexture.isReady()) {
  25055. return false;
  25056. }
  25057. else {
  25058. needUVs = true;
  25059. this._defines.OPACITY = true;
  25060. if (this.opacityTexture.getAlphaFromRGB) {
  25061. this._defines.OPACITYRGB = true;
  25062. }
  25063. }
  25064. }
  25065. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25066. if (!this.reflectionTexture.isReady()) {
  25067. return false;
  25068. }
  25069. else {
  25070. needNormals = true;
  25071. this._defines.REFLECTION = true;
  25072. if (this.roughness > 0) {
  25073. this._defines.ROUGHNESS = true;
  25074. }
  25075. if (this.useReflectionOverAlpha) {
  25076. this._defines.REFLECTIONOVERALPHA = true;
  25077. }
  25078. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  25079. this._defines.INVERTCUBICMAP = true;
  25080. }
  25081. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  25082. switch (this.reflectionTexture.coordinatesMode) {
  25083. case BABYLON.Texture.CUBIC_MODE:
  25084. case BABYLON.Texture.INVCUBIC_MODE:
  25085. this._defines.REFLECTIONMAP_CUBIC = true;
  25086. break;
  25087. case BABYLON.Texture.EXPLICIT_MODE:
  25088. this._defines.REFLECTIONMAP_EXPLICIT = true;
  25089. break;
  25090. case BABYLON.Texture.PLANAR_MODE:
  25091. this._defines.REFLECTIONMAP_PLANAR = true;
  25092. break;
  25093. case BABYLON.Texture.PROJECTION_MODE:
  25094. this._defines.REFLECTIONMAP_PROJECTION = true;
  25095. break;
  25096. case BABYLON.Texture.SKYBOX_MODE:
  25097. this._defines.REFLECTIONMAP_SKYBOX = true;
  25098. break;
  25099. case BABYLON.Texture.SPHERICAL_MODE:
  25100. this._defines.REFLECTIONMAP_SPHERICAL = true;
  25101. break;
  25102. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  25103. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  25104. break;
  25105. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  25106. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  25107. break;
  25108. }
  25109. }
  25110. }
  25111. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25112. if (!this.emissiveTexture.isReady()) {
  25113. return false;
  25114. }
  25115. else {
  25116. needUVs = true;
  25117. this._defines.EMISSIVE = true;
  25118. }
  25119. }
  25120. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25121. if (!this.lightmapTexture.isReady()) {
  25122. return false;
  25123. }
  25124. else {
  25125. needUVs = true;
  25126. this._defines.LIGHTMAP = true;
  25127. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  25128. }
  25129. }
  25130. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25131. if (!this.specularTexture.isReady()) {
  25132. return false;
  25133. }
  25134. else {
  25135. needUVs = true;
  25136. this._defines.SPECULAR = true;
  25137. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25138. }
  25139. }
  25140. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25141. if (!this.bumpTexture.isReady()) {
  25142. return false;
  25143. }
  25144. else {
  25145. needUVs = true;
  25146. this._defines.BUMP = true;
  25147. if (this.useParallax) {
  25148. this._defines.PARALLAX = true;
  25149. if (this.useParallaxOcclusion) {
  25150. this._defines.PARALLAXOCCLUSION = true;
  25151. }
  25152. }
  25153. if (this.invertNormalMapX) {
  25154. this._defines.INVERTNORMALMAPX = true;
  25155. }
  25156. if (this.invertNormalMapY) {
  25157. this._defines.INVERTNORMALMAPY = true;
  25158. }
  25159. }
  25160. }
  25161. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25162. if (!this.refractionTexture.isReady()) {
  25163. return false;
  25164. }
  25165. else {
  25166. needUVs = true;
  25167. this._defines.REFRACTION = true;
  25168. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  25169. }
  25170. }
  25171. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25172. if (!this.cameraColorGradingTexture.isReady()) {
  25173. return false;
  25174. }
  25175. else {
  25176. this._defines.CAMERACOLORGRADING = true;
  25177. }
  25178. }
  25179. }
  25180. // Effect
  25181. if (scene.clipPlane) {
  25182. this._defines.CLIPPLANE = true;
  25183. }
  25184. if (engine.getAlphaTesting()) {
  25185. this._defines.ALPHATEST = true;
  25186. }
  25187. if (this._shouldUseAlphaFromDiffuseTexture()) {
  25188. this._defines.ALPHAFROMDIFFUSE = true;
  25189. }
  25190. if (this.useEmissiveAsIllumination) {
  25191. this._defines.EMISSIVEASILLUMINATION = true;
  25192. }
  25193. if (this.linkEmissiveWithDiffuse) {
  25194. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  25195. }
  25196. if (this.useLogarithmicDepth) {
  25197. this._defines.LOGARITHMICDEPTH = true;
  25198. }
  25199. if (this.cameraColorCurves) {
  25200. this._defines.CAMERACOLORCURVES = true;
  25201. }
  25202. // Point size
  25203. if (this.pointsCloud || scene.forcePointsCloud) {
  25204. this._defines.POINTSIZE = true;
  25205. }
  25206. // Fog
  25207. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25208. this._defines.FOG = true;
  25209. }
  25210. if (scene.lightsEnabled && !this.disableLighting) {
  25211. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  25212. }
  25213. if (StandardMaterial.FresnelEnabled) {
  25214. // Fresnel
  25215. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  25216. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  25217. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  25218. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  25219. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25220. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25221. this._defines.DIFFUSEFRESNEL = true;
  25222. }
  25223. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25224. this._defines.OPACITYFRESNEL = true;
  25225. }
  25226. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25227. this._defines.REFLECTIONFRESNEL = true;
  25228. if (this.useReflectionFresnelFromSpecular) {
  25229. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  25230. }
  25231. }
  25232. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25233. this._defines.REFRACTIONFRESNEL = true;
  25234. }
  25235. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25236. this._defines.EMISSIVEFRESNEL = true;
  25237. }
  25238. needNormals = true;
  25239. this._defines.FRESNEL = true;
  25240. }
  25241. }
  25242. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  25243. this._defines.SPECULAROVERALPHA = true;
  25244. }
  25245. // Attribs
  25246. if (mesh) {
  25247. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25248. this._defines.NORMAL = true;
  25249. }
  25250. if (needUVs) {
  25251. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25252. this._defines.UV1 = true;
  25253. }
  25254. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25255. this._defines.UV2 = true;
  25256. }
  25257. }
  25258. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25259. this._defines.VERTEXCOLOR = true;
  25260. if (mesh.hasVertexAlpha) {
  25261. this._defines.VERTEXALPHA = true;
  25262. }
  25263. }
  25264. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25265. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  25266. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  25267. }
  25268. // Instances
  25269. if (useInstances) {
  25270. this._defines.INSTANCES = true;
  25271. }
  25272. }
  25273. // Get correct effect
  25274. if (!this._defines.isEqual(this._cachedDefines)) {
  25275. this._defines.cloneTo(this._cachedDefines);
  25276. scene.resetCachedMaterial();
  25277. // Fallbacks
  25278. var fallbacks = new BABYLON.EffectFallbacks();
  25279. if (this._defines.REFLECTION) {
  25280. fallbacks.addFallback(0, "REFLECTION");
  25281. }
  25282. if (this._defines.SPECULAR) {
  25283. fallbacks.addFallback(0, "SPECULAR");
  25284. }
  25285. if (this._defines.BUMP) {
  25286. fallbacks.addFallback(0, "BUMP");
  25287. }
  25288. if (this._defines.PARALLAX) {
  25289. fallbacks.addFallback(1, "PARALLAX");
  25290. }
  25291. if (this._defines.PARALLAXOCCLUSION) {
  25292. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  25293. }
  25294. if (this._defines.SPECULAROVERALPHA) {
  25295. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  25296. }
  25297. if (this._defines.FOG) {
  25298. fallbacks.addFallback(1, "FOG");
  25299. }
  25300. if (this._defines.POINTSIZE) {
  25301. fallbacks.addFallback(0, "POINTSIZE");
  25302. }
  25303. if (this._defines.LOGARITHMICDEPTH) {
  25304. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  25305. }
  25306. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  25307. if (this._defines.SPECULARTERM) {
  25308. fallbacks.addFallback(0, "SPECULARTERM");
  25309. }
  25310. if (this._defines.DIFFUSEFRESNEL) {
  25311. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  25312. }
  25313. if (this._defines.OPACITYFRESNEL) {
  25314. fallbacks.addFallback(2, "OPACITYFRESNEL");
  25315. }
  25316. if (this._defines.REFLECTIONFRESNEL) {
  25317. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  25318. }
  25319. if (this._defines.EMISSIVEFRESNEL) {
  25320. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  25321. }
  25322. if (this._defines.FRESNEL) {
  25323. fallbacks.addFallback(4, "FRESNEL");
  25324. }
  25325. //Attributes
  25326. var attribs = [BABYLON.VertexBuffer.PositionKind];
  25327. if (this._defines.NORMAL) {
  25328. attribs.push(BABYLON.VertexBuffer.NormalKind);
  25329. }
  25330. if (this._defines.UV1) {
  25331. attribs.push(BABYLON.VertexBuffer.UVKind);
  25332. }
  25333. if (this._defines.UV2) {
  25334. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25335. }
  25336. if (this._defines.VERTEXCOLOR) {
  25337. attribs.push(BABYLON.VertexBuffer.ColorKind);
  25338. }
  25339. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  25340. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  25341. var shaderName = "default";
  25342. var join = this._defines.toString();
  25343. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  25344. "vFogInfos", "vFogColor", "pointSize",
  25345. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  25346. "mBones",
  25347. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  25348. "depthValues",
  25349. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  25350. "logarithmicDepthConstant"
  25351. ];
  25352. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  25353. if (this._defines.CAMERACOLORCURVES) {
  25354. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  25355. }
  25356. if (this._defines.CAMERACOLORGRADING) {
  25357. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  25358. }
  25359. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  25360. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  25361. }
  25362. if (!this._effect.isReady()) {
  25363. return false;
  25364. }
  25365. this._renderId = scene.getRenderId();
  25366. this._wasPreviouslyReady = true;
  25367. if (mesh) {
  25368. if (!mesh._materialDefines) {
  25369. mesh._materialDefines = new StandardMaterialDefines();
  25370. }
  25371. this._defines.cloneTo(mesh._materialDefines);
  25372. }
  25373. return true;
  25374. };
  25375. StandardMaterial.prototype.unbind = function () {
  25376. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  25377. this._effect.setTexture("reflection2DSampler", null);
  25378. }
  25379. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  25380. this._effect.setTexture("refraction2DSampler", null);
  25381. }
  25382. _super.prototype.unbind.call(this);
  25383. };
  25384. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25385. this._effect.setMatrix("world", world);
  25386. };
  25387. StandardMaterial.prototype.bind = function (world, mesh) {
  25388. var scene = this.getScene();
  25389. // Matrices
  25390. this.bindOnlyWorldMatrix(world);
  25391. // Bones
  25392. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  25393. if (scene.getCachedMaterial() !== this) {
  25394. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25395. if (StandardMaterial.FresnelEnabled) {
  25396. // Fresnel
  25397. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25398. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  25399. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  25400. }
  25401. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25402. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  25403. }
  25404. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25405. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  25406. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  25407. }
  25408. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25409. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  25410. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  25411. }
  25412. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25413. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  25414. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  25415. }
  25416. }
  25417. // Textures
  25418. if (scene.texturesEnabled) {
  25419. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25420. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  25421. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  25422. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  25423. }
  25424. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25425. this._effect.setTexture("ambientSampler", this.ambientTexture);
  25426. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  25427. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  25428. }
  25429. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25430. this._effect.setTexture("opacitySampler", this.opacityTexture);
  25431. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  25432. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  25433. }
  25434. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25435. if (this.reflectionTexture.isCube) {
  25436. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  25437. }
  25438. else {
  25439. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  25440. }
  25441. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  25442. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  25443. }
  25444. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25445. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  25446. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  25447. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  25448. }
  25449. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25450. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  25451. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  25452. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  25453. }
  25454. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25455. this._effect.setTexture("specularSampler", this.specularTexture);
  25456. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  25457. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  25458. }
  25459. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  25460. this._effect.setTexture("bumpSampler", this.bumpTexture);
  25461. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  25462. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  25463. }
  25464. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25465. var depth = 1.0;
  25466. if (this.refractionTexture.isCube) {
  25467. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  25468. }
  25469. else {
  25470. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  25471. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  25472. if (this.refractionTexture.depth) {
  25473. depth = this.refractionTexture.depth;
  25474. }
  25475. }
  25476. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  25477. }
  25478. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25479. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  25480. }
  25481. }
  25482. // Clip plane
  25483. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  25484. // Point size
  25485. if (this.pointsCloud) {
  25486. this._effect.setFloat("pointSize", this.pointSize);
  25487. }
  25488. // Colors
  25489. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  25490. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  25491. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  25492. if (this._defines.SPECULARTERM) {
  25493. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  25494. }
  25495. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  25496. }
  25497. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  25498. // Diffuse
  25499. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  25500. // Lights
  25501. if (scene.lightsEnabled && !this.disableLighting) {
  25502. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  25503. }
  25504. // View
  25505. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  25506. this._effect.setMatrix("view", scene.getViewMatrix());
  25507. }
  25508. // Fog
  25509. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  25510. // Log. depth
  25511. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  25512. // Color Curves
  25513. if (this.cameraColorCurves) {
  25514. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  25515. }
  25516. }
  25517. _super.prototype.bind.call(this, world, mesh);
  25518. };
  25519. StandardMaterial.prototype.getAnimatables = function () {
  25520. var results = [];
  25521. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  25522. results.push(this.diffuseTexture);
  25523. }
  25524. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  25525. results.push(this.ambientTexture);
  25526. }
  25527. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  25528. results.push(this.opacityTexture);
  25529. }
  25530. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  25531. results.push(this.reflectionTexture);
  25532. }
  25533. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  25534. results.push(this.emissiveTexture);
  25535. }
  25536. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  25537. results.push(this.specularTexture);
  25538. }
  25539. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  25540. results.push(this.bumpTexture);
  25541. }
  25542. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  25543. results.push(this.lightmapTexture);
  25544. }
  25545. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  25546. results.push(this.refractionTexture);
  25547. }
  25548. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  25549. results.push(this.cameraColorGradingTexture);
  25550. }
  25551. return results;
  25552. };
  25553. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25554. if (forceDisposeTextures) {
  25555. if (this.diffuseTexture) {
  25556. this.diffuseTexture.dispose();
  25557. }
  25558. if (this.ambientTexture) {
  25559. this.ambientTexture.dispose();
  25560. }
  25561. if (this.opacityTexture) {
  25562. this.opacityTexture.dispose();
  25563. }
  25564. if (this.reflectionTexture) {
  25565. this.reflectionTexture.dispose();
  25566. }
  25567. if (this.emissiveTexture) {
  25568. this.emissiveTexture.dispose();
  25569. }
  25570. if (this.specularTexture) {
  25571. this.specularTexture.dispose();
  25572. }
  25573. if (this.bumpTexture) {
  25574. this.bumpTexture.dispose();
  25575. }
  25576. if (this.lightmapTexture) {
  25577. this.lightmapTexture.dispose();
  25578. }
  25579. if (this.refractionTexture) {
  25580. this.refractionTexture.dispose();
  25581. }
  25582. if (this.cameraColorGradingTexture) {
  25583. this.cameraColorGradingTexture.dispose();
  25584. }
  25585. }
  25586. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  25587. };
  25588. StandardMaterial.prototype.clone = function (name) {
  25589. var _this = this;
  25590. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  25591. };
  25592. StandardMaterial.prototype.serialize = function () {
  25593. return BABYLON.SerializationHelper.Serialize(this);
  25594. };
  25595. // Statics
  25596. StandardMaterial.Parse = function (source, scene, rootUrl) {
  25597. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  25598. };
  25599. // Flags used to enable or disable a type of texture for all Standard Materials
  25600. StandardMaterial.DiffuseTextureEnabled = true;
  25601. StandardMaterial.AmbientTextureEnabled = true;
  25602. StandardMaterial.OpacityTextureEnabled = true;
  25603. StandardMaterial.ReflectionTextureEnabled = true;
  25604. StandardMaterial.EmissiveTextureEnabled = true;
  25605. StandardMaterial.SpecularTextureEnabled = true;
  25606. StandardMaterial.BumpTextureEnabled = true;
  25607. StandardMaterial.FresnelEnabled = true;
  25608. StandardMaterial.LightmapTextureEnabled = true;
  25609. StandardMaterial.RefractionTextureEnabled = true;
  25610. StandardMaterial.ColorGradingTextureEnabled = true;
  25611. __decorate([
  25612. BABYLON.serializeAsTexture()
  25613. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  25614. __decorate([
  25615. BABYLON.serializeAsTexture()
  25616. ], StandardMaterial.prototype, "ambientTexture", void 0);
  25617. __decorate([
  25618. BABYLON.serializeAsTexture()
  25619. ], StandardMaterial.prototype, "opacityTexture", void 0);
  25620. __decorate([
  25621. BABYLON.serializeAsTexture()
  25622. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  25623. __decorate([
  25624. BABYLON.serializeAsTexture()
  25625. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  25626. __decorate([
  25627. BABYLON.serializeAsTexture()
  25628. ], StandardMaterial.prototype, "specularTexture", void 0);
  25629. __decorate([
  25630. BABYLON.serializeAsTexture()
  25631. ], StandardMaterial.prototype, "bumpTexture", void 0);
  25632. __decorate([
  25633. BABYLON.serializeAsTexture()
  25634. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  25635. __decorate([
  25636. BABYLON.serializeAsTexture()
  25637. ], StandardMaterial.prototype, "refractionTexture", void 0);
  25638. __decorate([
  25639. BABYLON.serializeAsColor3("ambient")
  25640. ], StandardMaterial.prototype, "ambientColor", void 0);
  25641. __decorate([
  25642. BABYLON.serializeAsColor3("diffuse")
  25643. ], StandardMaterial.prototype, "diffuseColor", void 0);
  25644. __decorate([
  25645. BABYLON.serializeAsColor3("specular")
  25646. ], StandardMaterial.prototype, "specularColor", void 0);
  25647. __decorate([
  25648. BABYLON.serializeAsColor3("emissive")
  25649. ], StandardMaterial.prototype, "emissiveColor", void 0);
  25650. __decorate([
  25651. BABYLON.serialize()
  25652. ], StandardMaterial.prototype, "specularPower", void 0);
  25653. __decorate([
  25654. BABYLON.serialize()
  25655. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  25656. __decorate([
  25657. BABYLON.serialize()
  25658. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  25659. __decorate([
  25660. BABYLON.serialize()
  25661. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  25662. __decorate([
  25663. BABYLON.serialize()
  25664. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  25665. __decorate([
  25666. BABYLON.serialize()
  25667. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  25668. __decorate([
  25669. BABYLON.serialize()
  25670. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  25671. __decorate([
  25672. BABYLON.serialize()
  25673. ], StandardMaterial.prototype, "disableLighting", void 0);
  25674. __decorate([
  25675. BABYLON.serialize()
  25676. ], StandardMaterial.prototype, "useParallax", void 0);
  25677. __decorate([
  25678. BABYLON.serialize()
  25679. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  25680. __decorate([
  25681. BABYLON.serialize()
  25682. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  25683. __decorate([
  25684. BABYLON.serialize()
  25685. ], StandardMaterial.prototype, "roughness", void 0);
  25686. __decorate([
  25687. BABYLON.serialize()
  25688. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  25689. __decorate([
  25690. BABYLON.serialize()
  25691. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  25692. __decorate([
  25693. BABYLON.serialize()
  25694. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  25695. __decorate([
  25696. BABYLON.serializeAsFresnelParameters()
  25697. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  25698. __decorate([
  25699. BABYLON.serializeAsFresnelParameters()
  25700. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  25701. __decorate([
  25702. BABYLON.serializeAsFresnelParameters()
  25703. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  25704. __decorate([
  25705. BABYLON.serializeAsFresnelParameters()
  25706. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  25707. __decorate([
  25708. BABYLON.serializeAsFresnelParameters()
  25709. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  25710. __decorate([
  25711. BABYLON.serialize()
  25712. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  25713. __decorate([
  25714. BABYLON.serialize()
  25715. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  25716. __decorate([
  25717. BABYLON.serialize()
  25718. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  25719. __decorate([
  25720. BABYLON.serialize()
  25721. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  25722. __decorate([
  25723. BABYLON.serializeAsTexture()
  25724. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  25725. __decorate([
  25726. BABYLON.serializeAsColorCurves()
  25727. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  25728. __decorate([
  25729. BABYLON.serialize()
  25730. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  25731. return StandardMaterial;
  25732. })(BABYLON.Material);
  25733. BABYLON.StandardMaterial = StandardMaterial;
  25734. })(BABYLON || (BABYLON = {}));
  25735. var BABYLON;
  25736. (function (BABYLON) {
  25737. var MultiMaterial = (function (_super) {
  25738. __extends(MultiMaterial, _super);
  25739. function MultiMaterial(name, scene) {
  25740. _super.call(this, name, scene, true);
  25741. this.subMaterials = new Array();
  25742. scene.multiMaterials.push(this);
  25743. }
  25744. // Properties
  25745. MultiMaterial.prototype.getSubMaterial = function (index) {
  25746. if (index < 0 || index >= this.subMaterials.length) {
  25747. return this.getScene().defaultMaterial;
  25748. }
  25749. return this.subMaterials[index];
  25750. };
  25751. // Methods
  25752. MultiMaterial.prototype.isReady = function (mesh) {
  25753. for (var index = 0; index < this.subMaterials.length; index++) {
  25754. var subMaterial = this.subMaterials[index];
  25755. if (subMaterial) {
  25756. if (!this.subMaterials[index].isReady(mesh)) {
  25757. return false;
  25758. }
  25759. }
  25760. }
  25761. return true;
  25762. };
  25763. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  25764. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  25765. for (var index = 0; index < this.subMaterials.length; index++) {
  25766. var subMaterial = null;
  25767. if (cloneChildren) {
  25768. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  25769. }
  25770. else {
  25771. subMaterial = this.subMaterials[index];
  25772. }
  25773. newMultiMaterial.subMaterials.push(subMaterial);
  25774. }
  25775. return newMultiMaterial;
  25776. };
  25777. MultiMaterial.prototype.serialize = function () {
  25778. var serializationObject = {};
  25779. serializationObject.name = this.name;
  25780. serializationObject.id = this.id;
  25781. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25782. serializationObject.materials = [];
  25783. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  25784. var subMat = this.subMaterials[matIndex];
  25785. if (subMat) {
  25786. serializationObject.materials.push(subMat.id);
  25787. }
  25788. else {
  25789. serializationObject.materials.push(null);
  25790. }
  25791. }
  25792. return serializationObject;
  25793. };
  25794. return MultiMaterial;
  25795. })(BABYLON.Material);
  25796. BABYLON.MultiMaterial = MultiMaterial;
  25797. })(BABYLON || (BABYLON = {}));
  25798. var BABYLON;
  25799. (function (BABYLON) {
  25800. var SceneLoader = (function () {
  25801. function SceneLoader() {
  25802. }
  25803. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  25804. get: function () {
  25805. return 0;
  25806. },
  25807. enumerable: true,
  25808. configurable: true
  25809. });
  25810. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  25811. get: function () {
  25812. return 1;
  25813. },
  25814. enumerable: true,
  25815. configurable: true
  25816. });
  25817. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  25818. get: function () {
  25819. return 2;
  25820. },
  25821. enumerable: true,
  25822. configurable: true
  25823. });
  25824. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  25825. get: function () {
  25826. return 3;
  25827. },
  25828. enumerable: true,
  25829. configurable: true
  25830. });
  25831. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  25832. get: function () {
  25833. return SceneLoader._ForceFullSceneLoadingForIncremental;
  25834. },
  25835. set: function (value) {
  25836. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  25837. },
  25838. enumerable: true,
  25839. configurable: true
  25840. });
  25841. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  25842. get: function () {
  25843. return SceneLoader._ShowLoadingScreen;
  25844. },
  25845. set: function (value) {
  25846. SceneLoader._ShowLoadingScreen = value;
  25847. },
  25848. enumerable: true,
  25849. configurable: true
  25850. });
  25851. Object.defineProperty(SceneLoader, "loggingLevel", {
  25852. get: function () {
  25853. return SceneLoader._loggingLevel;
  25854. },
  25855. set: function (value) {
  25856. SceneLoader._loggingLevel = value;
  25857. },
  25858. enumerable: true,
  25859. configurable: true
  25860. });
  25861. SceneLoader._getPluginForFilename = function (sceneFilename) {
  25862. var dotPosition = sceneFilename.lastIndexOf(".");
  25863. var queryStringPosition = sceneFilename.indexOf("?");
  25864. if (queryStringPosition === -1) {
  25865. queryStringPosition = sceneFilename.length;
  25866. }
  25867. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  25868. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25869. var plugin = this._registeredPlugins[index];
  25870. if (plugin.extensions.indexOf(extension) !== -1) {
  25871. return plugin;
  25872. }
  25873. }
  25874. return this._registeredPlugins[0];
  25875. };
  25876. // Public functions
  25877. SceneLoader.GetPluginForExtension = function (extension) {
  25878. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25879. var plugin = this._registeredPlugins[index];
  25880. if (plugin.extensions.indexOf(extension) !== -1) {
  25881. return plugin;
  25882. }
  25883. }
  25884. return null;
  25885. };
  25886. SceneLoader.RegisterPlugin = function (plugin) {
  25887. plugin.extensions = plugin.extensions.toLowerCase();
  25888. SceneLoader._registeredPlugins.push(plugin);
  25889. };
  25890. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25891. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25892. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25893. return;
  25894. }
  25895. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25896. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25897. return;
  25898. }
  25899. var loadingToken = {};
  25900. scene._addPendingData(loadingToken);
  25901. var manifestChecked = function (success) {
  25902. scene.database = database;
  25903. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  25904. var importMeshFromData = function (data) {
  25905. var meshes = [];
  25906. var particleSystems = [];
  25907. var skeletons = [];
  25908. try {
  25909. if (plugin.importMesh) {
  25910. var syncedPlugin = plugin;
  25911. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  25912. if (onerror) {
  25913. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25914. }
  25915. scene._removePendingData(loadingToken);
  25916. return;
  25917. }
  25918. if (onsuccess) {
  25919. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25920. onsuccess(meshes, particleSystems, skeletons);
  25921. scene._removePendingData(loadingToken);
  25922. }
  25923. }
  25924. else {
  25925. var asyncedPlugin = plugin;
  25926. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  25927. if (onsuccess) {
  25928. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25929. onsuccess(meshes, particleSystems, skeletons);
  25930. scene._removePendingData(loadingToken);
  25931. }
  25932. }, function () {
  25933. if (onerror) {
  25934. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25935. }
  25936. scene._removePendingData(loadingToken);
  25937. });
  25938. }
  25939. }
  25940. catch (e) {
  25941. if (onerror) {
  25942. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  25943. }
  25944. scene._removePendingData(loadingToken);
  25945. }
  25946. };
  25947. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25948. // Direct load
  25949. importMeshFromData(sceneFilename.substr(5));
  25950. return;
  25951. }
  25952. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  25953. importMeshFromData(data);
  25954. }, progressCallBack, database);
  25955. };
  25956. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  25957. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25958. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25959. }
  25960. else {
  25961. // If the scene is a data stream or offline support is not enabled, it's a direct load
  25962. manifestChecked(true);
  25963. }
  25964. };
  25965. /**
  25966. * Load a scene
  25967. * @param rootUrl a string that defines the root url for scene and resources
  25968. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25969. * @param engine is the instance of BABYLON.Engine to use to create the scene
  25970. */
  25971. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  25972. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  25973. };
  25974. /**
  25975. * Append a scene
  25976. * @param rootUrl a string that defines the root url for scene and resources
  25977. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25978. * @param scene is the instance of BABYLON.Scene to append to
  25979. */
  25980. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25981. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25982. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25983. return;
  25984. }
  25985. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  25986. var database;
  25987. var loadingToken = {};
  25988. scene._addPendingData(loadingToken);
  25989. if (SceneLoader.ShowLoadingScreen) {
  25990. scene.getEngine().displayLoadingUI();
  25991. }
  25992. var loadSceneFromData = function (data) {
  25993. scene.database = database;
  25994. if (plugin.load) {
  25995. var syncedPlugin = plugin;
  25996. if (!syncedPlugin.load(scene, data, rootUrl)) {
  25997. if (onerror) {
  25998. onerror(scene);
  25999. }
  26000. scene._removePendingData(loadingToken);
  26001. scene.getEngine().hideLoadingUI();
  26002. return;
  26003. }
  26004. if (onsuccess) {
  26005. onsuccess(scene);
  26006. }
  26007. scene._removePendingData(loadingToken);
  26008. }
  26009. else {
  26010. var asyncedPlugin = plugin;
  26011. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  26012. if (onsuccess) {
  26013. onsuccess(scene);
  26014. }
  26015. }, function () {
  26016. if (onerror) {
  26017. onerror(scene);
  26018. }
  26019. scene._removePendingData(loadingToken);
  26020. scene.getEngine().hideLoadingUI();
  26021. });
  26022. }
  26023. if (SceneLoader.ShowLoadingScreen) {
  26024. scene.executeWhenReady(function () {
  26025. scene.getEngine().hideLoadingUI();
  26026. });
  26027. }
  26028. };
  26029. var manifestChecked = function (success) {
  26030. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  26031. };
  26032. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  26033. // Direct load
  26034. loadSceneFromData(sceneFilename.substr(5));
  26035. return;
  26036. }
  26037. if (rootUrl.indexOf("file:") === -1) {
  26038. if (scene.getEngine().enableOfflineSupport) {
  26039. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26040. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26041. }
  26042. else {
  26043. manifestChecked(true);
  26044. }
  26045. }
  26046. else {
  26047. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  26048. }
  26049. };
  26050. // Flags
  26051. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  26052. SceneLoader._ShowLoadingScreen = true;
  26053. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  26054. // Members
  26055. SceneLoader._registeredPlugins = new Array();
  26056. return SceneLoader;
  26057. })();
  26058. BABYLON.SceneLoader = SceneLoader;
  26059. ;
  26060. })(BABYLON || (BABYLON = {}));
  26061. var BABYLON;
  26062. (function (BABYLON) {
  26063. var Internals;
  26064. (function (Internals) {
  26065. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  26066. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26067. var parsedMaterial = parsedData.materials[index];
  26068. if (parsedMaterial.id === id) {
  26069. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26070. }
  26071. }
  26072. return null;
  26073. };
  26074. var isDescendantOf = function (mesh, names, hierarchyIds) {
  26075. names = (names instanceof Array) ? names : [names];
  26076. for (var i in names) {
  26077. if (mesh.name === names[i]) {
  26078. hierarchyIds.push(mesh.id);
  26079. return true;
  26080. }
  26081. }
  26082. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  26083. hierarchyIds.push(mesh.id);
  26084. return true;
  26085. }
  26086. return false;
  26087. };
  26088. var logOperation = function (operation, producer) {
  26089. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  26090. };
  26091. BABYLON.SceneLoader.RegisterPlugin({
  26092. extensions: ".babylon",
  26093. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  26094. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26095. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26096. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26097. // and avoid problems with multiple concurrent .babylon loads.
  26098. var log = "importMesh has failed JSON parse";
  26099. try {
  26100. var parsedData = JSON.parse(data);
  26101. log = "";
  26102. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26103. var loadedSkeletonsIds = [];
  26104. var loadedMaterialsIds = [];
  26105. var hierarchyIds = [];
  26106. var index;
  26107. var cache;
  26108. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26109. var parsedMesh = parsedData.meshes[index];
  26110. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  26111. if (meshesNames instanceof Array) {
  26112. // Remove found mesh name from list.
  26113. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  26114. }
  26115. //Geometry?
  26116. if (parsedMesh.geometryId) {
  26117. //does the file contain geometries?
  26118. if (parsedData.geometries) {
  26119. //find the correct geometry and add it to the scene
  26120. var found = false;
  26121. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  26122. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  26123. return;
  26124. }
  26125. else {
  26126. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  26127. if (parsedGeometryData.id === parsedMesh.geometryId) {
  26128. switch (geometryType) {
  26129. case "boxes":
  26130. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  26131. break;
  26132. case "spheres":
  26133. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  26134. break;
  26135. case "cylinders":
  26136. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  26137. break;
  26138. case "toruses":
  26139. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  26140. break;
  26141. case "grounds":
  26142. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  26143. break;
  26144. case "planes":
  26145. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  26146. break;
  26147. case "torusKnots":
  26148. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  26149. break;
  26150. case "vertexData":
  26151. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  26152. break;
  26153. }
  26154. found = true;
  26155. }
  26156. });
  26157. }
  26158. });
  26159. if (!found) {
  26160. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  26161. }
  26162. }
  26163. }
  26164. // Material ?
  26165. if (parsedMesh.materialId) {
  26166. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  26167. if (!materialFound && parsedData.multiMaterials) {
  26168. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  26169. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  26170. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  26171. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  26172. var subMatId = parsedMultiMaterial.materials[matIndex];
  26173. loadedMaterialsIds.push(subMatId);
  26174. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  26175. log += "\n\tMaterial " + mat.toString(fullDetails);
  26176. }
  26177. loadedMaterialsIds.push(parsedMultiMaterial.id);
  26178. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26179. materialFound = true;
  26180. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  26181. break;
  26182. }
  26183. }
  26184. }
  26185. if (!materialFound) {
  26186. loadedMaterialsIds.push(parsedMesh.materialId);
  26187. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  26188. if (!mat) {
  26189. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  26190. }
  26191. else {
  26192. log += "\n\tMaterial " + mat.toString(fullDetails);
  26193. }
  26194. }
  26195. }
  26196. // Skeleton ?
  26197. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  26198. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  26199. if (!skeletonAlreadyLoaded) {
  26200. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  26201. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  26202. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  26203. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26204. skeletons.push(skeleton);
  26205. loadedSkeletonsIds.push(parsedSkeleton.id);
  26206. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  26207. }
  26208. }
  26209. }
  26210. }
  26211. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26212. meshes.push(mesh);
  26213. log += "\n\tMesh " + mesh.toString(fullDetails);
  26214. }
  26215. }
  26216. // Connecting parents
  26217. var currentMesh;
  26218. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26219. currentMesh = scene.meshes[index];
  26220. if (currentMesh._waitingParentId) {
  26221. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  26222. currentMesh._waitingParentId = undefined;
  26223. }
  26224. }
  26225. // freeze and compute world matrix application
  26226. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26227. currentMesh = scene.meshes[index];
  26228. if (currentMesh._waitingFreezeWorldMatrix) {
  26229. currentMesh.freezeWorldMatrix();
  26230. currentMesh._waitingFreezeWorldMatrix = undefined;
  26231. }
  26232. else {
  26233. currentMesh.computeWorldMatrix(true);
  26234. }
  26235. }
  26236. // Particles
  26237. if (parsedData.particleSystems) {
  26238. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26239. var parsedParticleSystem = parsedData.particleSystems[index];
  26240. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  26241. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  26242. }
  26243. }
  26244. }
  26245. return true;
  26246. }
  26247. catch (err) {
  26248. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  26249. log = null;
  26250. throw err;
  26251. }
  26252. finally {
  26253. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26254. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26255. }
  26256. }
  26257. },
  26258. load: function (scene, data, rootUrl) {
  26259. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26260. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26261. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26262. // and avoid problems with multiple concurrent .babylon loads.
  26263. var log = "importScene has failed JSON parse";
  26264. try {
  26265. var parsedData = JSON.parse(data);
  26266. log = "";
  26267. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26268. // Scene
  26269. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  26270. scene.autoClear = parsedData.autoClear;
  26271. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  26272. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  26273. if (parsedData.gravity) {
  26274. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  26275. }
  26276. // Fog
  26277. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  26278. scene.fogMode = parsedData.fogMode;
  26279. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  26280. scene.fogStart = parsedData.fogStart;
  26281. scene.fogEnd = parsedData.fogEnd;
  26282. scene.fogDensity = parsedData.fogDensity;
  26283. log += "\tFog mode for scene: ";
  26284. switch (scene.fogMode) {
  26285. // getters not compiling, so using hardcoded
  26286. case 1:
  26287. log += "exp\n";
  26288. break;
  26289. case 2:
  26290. log += "exp2\n";
  26291. break;
  26292. case 3:
  26293. log += "linear\n";
  26294. break;
  26295. }
  26296. }
  26297. //Physics
  26298. if (parsedData.physicsEnabled) {
  26299. var physicsPlugin;
  26300. if (parsedData.physicsEngine === "cannon") {
  26301. physicsPlugin = new BABYLON.CannonJSPlugin();
  26302. }
  26303. else if (parsedData.physicsEngine === "oimo") {
  26304. physicsPlugin = new BABYLON.OimoJSPlugin();
  26305. }
  26306. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  26307. //else - default engine, which is currently oimo
  26308. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  26309. scene.enablePhysics(physicsGravity, physicsPlugin);
  26310. }
  26311. //collisions, if defined. otherwise, default is true
  26312. if (parsedData.collisionsEnabled != undefined) {
  26313. scene.collisionsEnabled = parsedData.collisionsEnabled;
  26314. }
  26315. scene.workerCollisions = !!parsedData.workerCollisions;
  26316. var index;
  26317. var cache;
  26318. // Lights
  26319. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  26320. var parsedLight = parsedData.lights[index];
  26321. var light = BABYLON.Light.Parse(parsedLight, scene);
  26322. log += (index === 0 ? "\n\tLights:" : "");
  26323. log += "\n\t\t" + light.toString(fullDetails);
  26324. }
  26325. // Animations
  26326. if (parsedData.animations) {
  26327. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  26328. var parsedAnimation = parsedData.animations[index];
  26329. var animation = BABYLON.Animation.Parse(parsedAnimation);
  26330. scene.animations.push(animation);
  26331. log += (index === 0 ? "\n\tAnimations:" : "");
  26332. log += "\n\t\t" + animation.toString(fullDetails);
  26333. }
  26334. }
  26335. if (parsedData.autoAnimate) {
  26336. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  26337. }
  26338. // Materials
  26339. if (parsedData.materials) {
  26340. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26341. var parsedMaterial = parsedData.materials[index];
  26342. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26343. log += (index === 0 ? "\n\tMaterials:" : "");
  26344. log += "\n\t\t" + mat.toString(fullDetails);
  26345. }
  26346. }
  26347. if (parsedData.multiMaterials) {
  26348. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  26349. var parsedMultiMaterial = parsedData.multiMaterials[index];
  26350. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26351. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  26352. log += "\n\t\t" + mmat.toString(fullDetails);
  26353. }
  26354. }
  26355. // Skeletons
  26356. if (parsedData.skeletons) {
  26357. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  26358. var parsedSkeleton = parsedData.skeletons[index];
  26359. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26360. log += (index === 0 ? "\n\tSkeletons:" : "");
  26361. log += "\n\t\t" + skeleton.toString(fullDetails);
  26362. }
  26363. }
  26364. // Geometries
  26365. var geometries = parsedData.geometries;
  26366. if (geometries) {
  26367. // Boxes
  26368. var boxes = geometries.boxes;
  26369. if (boxes) {
  26370. for (index = 0, cache = boxes.length; index < cache; index++) {
  26371. var parsedBox = boxes[index];
  26372. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  26373. }
  26374. }
  26375. // Spheres
  26376. var spheres = geometries.spheres;
  26377. if (spheres) {
  26378. for (index = 0, cache = spheres.length; index < cache; index++) {
  26379. var parsedSphere = spheres[index];
  26380. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  26381. }
  26382. }
  26383. // Cylinders
  26384. var cylinders = geometries.cylinders;
  26385. if (cylinders) {
  26386. for (index = 0, cache = cylinders.length; index < cache; index++) {
  26387. var parsedCylinder = cylinders[index];
  26388. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  26389. }
  26390. }
  26391. // Toruses
  26392. var toruses = geometries.toruses;
  26393. if (toruses) {
  26394. for (index = 0, cache = toruses.length; index < cache; index++) {
  26395. var parsedTorus = toruses[index];
  26396. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  26397. }
  26398. }
  26399. // Grounds
  26400. var grounds = geometries.grounds;
  26401. if (grounds) {
  26402. for (index = 0, cache = grounds.length; index < cache; index++) {
  26403. var parsedGround = grounds[index];
  26404. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  26405. }
  26406. }
  26407. // Planes
  26408. var planes = geometries.planes;
  26409. if (planes) {
  26410. for (index = 0, cache = planes.length; index < cache; index++) {
  26411. var parsedPlane = planes[index];
  26412. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  26413. }
  26414. }
  26415. // TorusKnots
  26416. var torusKnots = geometries.torusKnots;
  26417. if (torusKnots) {
  26418. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  26419. var parsedTorusKnot = torusKnots[index];
  26420. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  26421. }
  26422. }
  26423. // VertexData
  26424. var vertexData = geometries.vertexData;
  26425. if (vertexData) {
  26426. for (index = 0, cache = vertexData.length; index < cache; index++) {
  26427. var parsedVertexData = vertexData[index];
  26428. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  26429. }
  26430. }
  26431. }
  26432. // Meshes
  26433. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26434. var parsedMesh = parsedData.meshes[index];
  26435. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26436. log += (index === 0 ? "\n\tMeshes:" : "");
  26437. log += "\n\t\t" + mesh.toString(fullDetails);
  26438. }
  26439. // Cameras
  26440. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  26441. var parsedCamera = parsedData.cameras[index];
  26442. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  26443. log += (index === 0 ? "\n\tCameras:" : "");
  26444. log += "\n\t\t" + camera.toString(fullDetails);
  26445. }
  26446. if (parsedData.activeCameraID) {
  26447. scene.setActiveCameraByID(parsedData.activeCameraID);
  26448. }
  26449. // Browsing all the graph to connect the dots
  26450. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  26451. var camera = scene.cameras[index];
  26452. if (camera._waitingParentId) {
  26453. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  26454. camera._waitingParentId = undefined;
  26455. }
  26456. }
  26457. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  26458. var light = scene.lights[index];
  26459. if (light._waitingParentId) {
  26460. light.parent = scene.getLastEntryByID(light._waitingParentId);
  26461. light._waitingParentId = undefined;
  26462. }
  26463. }
  26464. // Sounds
  26465. var loadedSounds = [];
  26466. var loadedSound;
  26467. if (BABYLON.AudioEngine && parsedData.sounds) {
  26468. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  26469. var parsedSound = parsedData.sounds[index];
  26470. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26471. if (!parsedSound.url)
  26472. parsedSound.url = parsedSound.name;
  26473. if (!loadedSounds[parsedSound.url]) {
  26474. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  26475. loadedSounds[parsedSound.url] = loadedSound;
  26476. }
  26477. else {
  26478. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  26479. }
  26480. }
  26481. else {
  26482. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  26483. }
  26484. }
  26485. }
  26486. loadedSounds = [];
  26487. // Connect parents & children and parse actions
  26488. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26489. var mesh = scene.meshes[index];
  26490. if (mesh._waitingParentId) {
  26491. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  26492. mesh._waitingParentId = undefined;
  26493. }
  26494. if (mesh._waitingActions) {
  26495. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  26496. mesh._waitingActions = undefined;
  26497. }
  26498. }
  26499. // freeze world matrix application
  26500. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26501. var currentMesh = scene.meshes[index];
  26502. if (currentMesh._waitingFreezeWorldMatrix) {
  26503. currentMesh.freezeWorldMatrix();
  26504. currentMesh._waitingFreezeWorldMatrix = undefined;
  26505. }
  26506. else {
  26507. currentMesh.computeWorldMatrix(true);
  26508. }
  26509. }
  26510. // Particles Systems
  26511. if (parsedData.particleSystems) {
  26512. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26513. var parsedParticleSystem = parsedData.particleSystems[index];
  26514. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  26515. }
  26516. }
  26517. // Lens flares
  26518. if (parsedData.lensFlareSystems) {
  26519. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  26520. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  26521. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  26522. }
  26523. }
  26524. // Shadows
  26525. if (parsedData.shadowGenerators) {
  26526. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  26527. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  26528. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  26529. }
  26530. }
  26531. // Actions (scene)
  26532. if (parsedData.actions) {
  26533. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  26534. }
  26535. // Finish
  26536. return true;
  26537. }
  26538. catch (err) {
  26539. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  26540. log = null;
  26541. throw err;
  26542. }
  26543. finally {
  26544. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26545. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26546. }
  26547. }
  26548. }
  26549. });
  26550. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26551. })(BABYLON || (BABYLON = {}));
  26552. var BABYLON;
  26553. (function (BABYLON) {
  26554. var SpriteManager = (function () {
  26555. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  26556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26557. this.name = name;
  26558. this.sprites = new Array();
  26559. this.renderingGroupId = 0;
  26560. this.layerMask = 0x0FFFFFFF;
  26561. this.fogEnabled = true;
  26562. this.isPickable = false;
  26563. /**
  26564. * An event triggered when the manager is disposed.
  26565. * @type {BABYLON.Observable}
  26566. */
  26567. this.onDisposeObservable = new BABYLON.Observable();
  26568. this._vertexBuffers = {};
  26569. this._capacity = capacity;
  26570. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  26571. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26572. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26573. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  26574. if (cellSize.width) {
  26575. this.cellWidth = cellSize.width;
  26576. this.cellHeight = cellSize.height;
  26577. }
  26578. else {
  26579. this.cellWidth = cellSize;
  26580. this.cellHeight = cellSize;
  26581. }
  26582. this._scene = scene;
  26583. this._scene.spriteManagers.push(this);
  26584. var indices = [];
  26585. var index = 0;
  26586. for (var count = 0; count < capacity; count++) {
  26587. indices.push(index);
  26588. indices.push(index + 1);
  26589. indices.push(index + 2);
  26590. indices.push(index);
  26591. indices.push(index + 2);
  26592. indices.push(index + 3);
  26593. index += 4;
  26594. }
  26595. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26596. // VBO
  26597. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  26598. this._vertexData = new Float32Array(capacity * 16 * 4);
  26599. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  26600. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  26601. var options = this._buffer.createVertexBuffer("options", 4, 4);
  26602. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  26603. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  26604. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26605. this._vertexBuffers["options"] = options;
  26606. this._vertexBuffers["cellInfo"] = cellInfo;
  26607. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26608. // Effects
  26609. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  26610. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  26611. }
  26612. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  26613. set: function (callback) {
  26614. if (this._onDisposeObserver) {
  26615. this.onDisposeObservable.remove(this._onDisposeObserver);
  26616. }
  26617. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26618. },
  26619. enumerable: true,
  26620. configurable: true
  26621. });
  26622. Object.defineProperty(SpriteManager.prototype, "texture", {
  26623. get: function () {
  26624. return this._spriteTexture;
  26625. },
  26626. set: function (value) {
  26627. this._spriteTexture = value;
  26628. },
  26629. enumerable: true,
  26630. configurable: true
  26631. });
  26632. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  26633. var arrayOffset = index * 16;
  26634. if (offsetX === 0)
  26635. offsetX = this._epsilon;
  26636. else if (offsetX === 1)
  26637. offsetX = 1 - this._epsilon;
  26638. if (offsetY === 0)
  26639. offsetY = this._epsilon;
  26640. else if (offsetY === 1)
  26641. offsetY = 1 - this._epsilon;
  26642. this._vertexData[arrayOffset] = sprite.position.x;
  26643. this._vertexData[arrayOffset + 1] = sprite.position.y;
  26644. this._vertexData[arrayOffset + 2] = sprite.position.z;
  26645. this._vertexData[arrayOffset + 3] = sprite.angle;
  26646. this._vertexData[arrayOffset + 4] = sprite.width;
  26647. this._vertexData[arrayOffset + 5] = sprite.height;
  26648. this._vertexData[arrayOffset + 6] = offsetX;
  26649. this._vertexData[arrayOffset + 7] = offsetY;
  26650. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  26651. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  26652. var offset = (sprite.cellIndex / rowSize) >> 0;
  26653. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  26654. this._vertexData[arrayOffset + 11] = offset;
  26655. // Color
  26656. this._vertexData[arrayOffset + 12] = sprite.color.r;
  26657. this._vertexData[arrayOffset + 13] = sprite.color.g;
  26658. this._vertexData[arrayOffset + 14] = sprite.color.b;
  26659. this._vertexData[arrayOffset + 15] = sprite.color.a;
  26660. };
  26661. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  26662. var count = Math.min(this._capacity, this.sprites.length);
  26663. var min = BABYLON.Vector3.Zero();
  26664. var max = BABYLON.Vector3.Zero();
  26665. var distance = Number.MAX_VALUE;
  26666. var currentSprite;
  26667. var cameraSpacePosition = BABYLON.Vector3.Zero();
  26668. var cameraView = camera.getViewMatrix();
  26669. for (var index = 0; index < count; index++) {
  26670. var sprite = this.sprites[index];
  26671. if (!sprite) {
  26672. continue;
  26673. }
  26674. if (predicate) {
  26675. if (!predicate(sprite)) {
  26676. continue;
  26677. }
  26678. }
  26679. else if (!sprite.isPickable) {
  26680. continue;
  26681. }
  26682. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  26683. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  26684. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  26685. if (ray.intersectsBoxMinMax(min, max)) {
  26686. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  26687. if (distance > currentDistance) {
  26688. distance = currentDistance;
  26689. currentSprite = sprite;
  26690. if (fastCheck) {
  26691. break;
  26692. }
  26693. }
  26694. }
  26695. }
  26696. if (currentSprite) {
  26697. var result = new BABYLON.PickingInfo();
  26698. result.hit = true;
  26699. result.pickedSprite = currentSprite;
  26700. result.distance = distance;
  26701. return result;
  26702. }
  26703. return null;
  26704. };
  26705. SpriteManager.prototype.render = function () {
  26706. // Check
  26707. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  26708. return;
  26709. var engine = this._scene.getEngine();
  26710. var baseSize = this._spriteTexture.getBaseSize();
  26711. // Sprites
  26712. var deltaTime = engine.getDeltaTime();
  26713. var max = Math.min(this._capacity, this.sprites.length);
  26714. var rowSize = baseSize.width / this.cellWidth;
  26715. var offset = 0;
  26716. for (var index = 0; index < max; index++) {
  26717. var sprite = this.sprites[index];
  26718. if (!sprite) {
  26719. continue;
  26720. }
  26721. sprite._animate(deltaTime);
  26722. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  26723. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  26724. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  26725. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  26726. }
  26727. this._buffer.update(this._vertexData);
  26728. // Render
  26729. var effect = this._effectBase;
  26730. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26731. effect = this._effectFog;
  26732. }
  26733. engine.enableEffect(effect);
  26734. var viewMatrix = this._scene.getViewMatrix();
  26735. effect.setTexture("diffuseSampler", this._spriteTexture);
  26736. effect.setMatrix("view", viewMatrix);
  26737. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26738. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  26739. // Fog
  26740. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26741. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  26742. effect.setColor3("vFogColor", this._scene.fogColor);
  26743. }
  26744. // VBOs
  26745. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26746. // Draw order
  26747. engine.setDepthFunctionToLessOrEqual();
  26748. effect.setBool("alphaTest", true);
  26749. engine.setColorWrite(false);
  26750. engine.draw(true, 0, max * 6);
  26751. engine.setColorWrite(true);
  26752. effect.setBool("alphaTest", false);
  26753. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26754. engine.draw(true, 0, max * 6);
  26755. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26756. };
  26757. SpriteManager.prototype.dispose = function () {
  26758. if (this._buffer) {
  26759. this._buffer.dispose();
  26760. this._buffer = null;
  26761. }
  26762. if (this._indexBuffer) {
  26763. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26764. this._indexBuffer = null;
  26765. }
  26766. if (this._spriteTexture) {
  26767. this._spriteTexture.dispose();
  26768. this._spriteTexture = null;
  26769. }
  26770. // Remove from scene
  26771. var index = this._scene.spriteManagers.indexOf(this);
  26772. this._scene.spriteManagers.splice(index, 1);
  26773. // Callback
  26774. this.onDisposeObservable.notifyObservers(this);
  26775. this.onDisposeObservable.clear();
  26776. };
  26777. return SpriteManager;
  26778. })();
  26779. BABYLON.SpriteManager = SpriteManager;
  26780. })(BABYLON || (BABYLON = {}));
  26781. var BABYLON;
  26782. (function (BABYLON) {
  26783. var Sprite = (function () {
  26784. function Sprite(name, manager) {
  26785. this.name = name;
  26786. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26787. this.width = 1.0;
  26788. this.height = 1.0;
  26789. this.angle = 0;
  26790. this.cellIndex = 0;
  26791. this.invertU = 0;
  26792. this.invertV = 0;
  26793. this.animations = new Array();
  26794. this.isPickable = false;
  26795. this._animationStarted = false;
  26796. this._loopAnimation = false;
  26797. this._fromIndex = 0;
  26798. this._toIndex = 0;
  26799. this._delay = 0;
  26800. this._direction = 1;
  26801. this._frameCount = 0;
  26802. this._time = 0;
  26803. this._manager = manager;
  26804. this._manager.sprites.push(this);
  26805. this.position = BABYLON.Vector3.Zero();
  26806. }
  26807. Object.defineProperty(Sprite.prototype, "size", {
  26808. get: function () {
  26809. return this.width;
  26810. },
  26811. set: function (value) {
  26812. this.width = value;
  26813. this.height = value;
  26814. },
  26815. enumerable: true,
  26816. configurable: true
  26817. });
  26818. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  26819. this._fromIndex = from;
  26820. this._toIndex = to;
  26821. this._loopAnimation = loop;
  26822. this._delay = delay;
  26823. this._animationStarted = true;
  26824. this._direction = from < to ? 1 : -1;
  26825. this.cellIndex = from;
  26826. this._time = 0;
  26827. this._onAnimationEnd = onAnimationEnd;
  26828. };
  26829. Sprite.prototype.stopAnimation = function () {
  26830. this._animationStarted = false;
  26831. };
  26832. Sprite.prototype._animate = function (deltaTime) {
  26833. if (!this._animationStarted)
  26834. return;
  26835. this._time += deltaTime;
  26836. if (this._time > this._delay) {
  26837. this._time = this._time % this._delay;
  26838. this.cellIndex += this._direction;
  26839. if (this.cellIndex === this._toIndex) {
  26840. if (this._loopAnimation) {
  26841. this.cellIndex = this._fromIndex;
  26842. }
  26843. else {
  26844. this._animationStarted = false;
  26845. if (this._onAnimationEnd) {
  26846. this._onAnimationEnd();
  26847. }
  26848. if (this.disposeWhenFinishedAnimating) {
  26849. this.dispose();
  26850. }
  26851. }
  26852. }
  26853. }
  26854. };
  26855. Sprite.prototype.dispose = function () {
  26856. for (var i = 0; i < this._manager.sprites.length; i++) {
  26857. if (this._manager.sprites[i] == this) {
  26858. this._manager.sprites.splice(i, 1);
  26859. }
  26860. }
  26861. };
  26862. return Sprite;
  26863. })();
  26864. BABYLON.Sprite = Sprite;
  26865. })(BABYLON || (BABYLON = {}));
  26866. var BABYLON;
  26867. (function (BABYLON) {
  26868. var Layer = (function () {
  26869. function Layer(name, imgUrl, scene, isBackground, color) {
  26870. this.name = name;
  26871. this.scale = new BABYLON.Vector2(1, 1);
  26872. this.offset = new BABYLON.Vector2(0, 0);
  26873. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  26874. this._vertexBuffers = {};
  26875. // Events
  26876. /**
  26877. * An event triggered when the layer is disposed.
  26878. * @type {BABYLON.Observable}
  26879. */
  26880. this.onDisposeObservable = new BABYLON.Observable();
  26881. /**
  26882. * An event triggered before rendering the scene
  26883. * @type {BABYLON.Observable}
  26884. */
  26885. this.onBeforeRenderObservable = new BABYLON.Observable();
  26886. /**
  26887. * An event triggered after rendering the scene
  26888. * @type {BABYLON.Observable}
  26889. */
  26890. this.onAfterRenderObservable = new BABYLON.Observable();
  26891. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  26892. this.isBackground = isBackground === undefined ? true : isBackground;
  26893. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  26894. this._scene = scene;
  26895. this._scene.layers.push(this);
  26896. var engine = scene.getEngine();
  26897. // VBO
  26898. var vertices = [];
  26899. vertices.push(1, 1);
  26900. vertices.push(-1, 1);
  26901. vertices.push(-1, -1);
  26902. vertices.push(1, -1);
  26903. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  26904. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  26905. // Indices
  26906. var indices = [];
  26907. indices.push(0);
  26908. indices.push(1);
  26909. indices.push(2);
  26910. indices.push(0);
  26911. indices.push(2);
  26912. indices.push(3);
  26913. this._indexBuffer = engine.createIndexBuffer(indices);
  26914. // Effects
  26915. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  26916. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  26917. }
  26918. Object.defineProperty(Layer.prototype, "onDispose", {
  26919. set: function (callback) {
  26920. if (this._onDisposeObserver) {
  26921. this.onDisposeObservable.remove(this._onDisposeObserver);
  26922. }
  26923. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26924. },
  26925. enumerable: true,
  26926. configurable: true
  26927. });
  26928. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  26929. set: function (callback) {
  26930. if (this._onBeforeRenderObserver) {
  26931. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26932. }
  26933. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26934. },
  26935. enumerable: true,
  26936. configurable: true
  26937. });
  26938. Object.defineProperty(Layer.prototype, "onAfterRender", {
  26939. set: function (callback) {
  26940. if (this._onAfterRenderObserver) {
  26941. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26942. }
  26943. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26944. },
  26945. enumerable: true,
  26946. configurable: true
  26947. });
  26948. Layer.prototype.render = function () {
  26949. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  26950. // Check
  26951. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  26952. return;
  26953. var engine = this._scene.getEngine();
  26954. this.onBeforeRenderObservable.notifyObservers(this);
  26955. // Render
  26956. engine.enableEffect(currentEffect);
  26957. engine.setState(false);
  26958. // Texture
  26959. currentEffect.setTexture("textureSampler", this.texture);
  26960. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  26961. // Color
  26962. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  26963. // Scale / offset
  26964. currentEffect.setVector2("offset", this.offset);
  26965. currentEffect.setVector2("scale", this.scale);
  26966. // VBOs
  26967. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  26968. // Draw order
  26969. if (!this._alphaTestEffect) {
  26970. engine.setAlphaMode(this.alphaBlendingMode);
  26971. engine.draw(true, 0, 6);
  26972. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26973. }
  26974. else {
  26975. engine.draw(true, 0, 6);
  26976. }
  26977. this.onAfterRenderObservable.notifyObservers(this);
  26978. };
  26979. Layer.prototype.dispose = function () {
  26980. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  26981. if (vertexBuffer) {
  26982. vertexBuffer.dispose();
  26983. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  26984. }
  26985. if (this._indexBuffer) {
  26986. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26987. this._indexBuffer = null;
  26988. }
  26989. if (this.texture) {
  26990. this.texture.dispose();
  26991. this.texture = null;
  26992. }
  26993. // Remove from scene
  26994. var index = this._scene.layers.indexOf(this);
  26995. this._scene.layers.splice(index, 1);
  26996. // Callback
  26997. this.onDisposeObservable.notifyObservers(this);
  26998. this.onDisposeObservable.clear();
  26999. this.onAfterRenderObservable.clear();
  27000. this.onBeforeRenderObservable.clear();
  27001. };
  27002. return Layer;
  27003. })();
  27004. BABYLON.Layer = Layer;
  27005. })(BABYLON || (BABYLON = {}));
  27006. var BABYLON;
  27007. (function (BABYLON) {
  27008. var Particle = (function () {
  27009. function Particle() {
  27010. this.position = BABYLON.Vector3.Zero();
  27011. this.direction = BABYLON.Vector3.Zero();
  27012. this.color = new BABYLON.Color4(0, 0, 0, 0);
  27013. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  27014. this.lifeTime = 1.0;
  27015. this.age = 0;
  27016. this.size = 0;
  27017. this.angle = 0;
  27018. this.angularSpeed = 0;
  27019. }
  27020. Particle.prototype.copyTo = function (other) {
  27021. other.position.copyFrom(this.position);
  27022. other.direction.copyFrom(this.direction);
  27023. other.color.copyFrom(this.color);
  27024. other.colorStep.copyFrom(this.colorStep);
  27025. other.lifeTime = this.lifeTime;
  27026. other.age = this.age;
  27027. other.size = this.size;
  27028. other.angle = this.angle;
  27029. other.angularSpeed = this.angularSpeed;
  27030. };
  27031. return Particle;
  27032. })();
  27033. BABYLON.Particle = Particle;
  27034. })(BABYLON || (BABYLON = {}));
  27035. var BABYLON;
  27036. (function (BABYLON) {
  27037. var randomNumber = function (min, max) {
  27038. if (min === max) {
  27039. return (min);
  27040. }
  27041. var random = Math.random();
  27042. return ((random * (max - min)) + min);
  27043. };
  27044. var ParticleSystem = (function () {
  27045. function ParticleSystem(name, capacity, scene, customEffect) {
  27046. var _this = this;
  27047. this.name = name;
  27048. // Members
  27049. this.animations = [];
  27050. this.renderingGroupId = 0;
  27051. this.emitter = null;
  27052. this.emitRate = 10;
  27053. this.manualEmitCount = -1;
  27054. this.updateSpeed = 0.01;
  27055. this.targetStopDuration = 0;
  27056. this.disposeOnStop = false;
  27057. this.minEmitPower = 1;
  27058. this.maxEmitPower = 1;
  27059. this.minLifeTime = 1;
  27060. this.maxLifeTime = 1;
  27061. this.minSize = 1;
  27062. this.maxSize = 1;
  27063. this.minAngularSpeed = 0;
  27064. this.maxAngularSpeed = 0;
  27065. this.layerMask = 0x0FFFFFFF;
  27066. /**
  27067. * An event triggered when the system is disposed.
  27068. * @type {BABYLON.Observable}
  27069. */
  27070. this.onDisposeObservable = new BABYLON.Observable();
  27071. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  27072. this.forceDepthWrite = false;
  27073. this.gravity = BABYLON.Vector3.Zero();
  27074. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  27075. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  27076. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  27077. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  27078. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27079. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27080. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  27081. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27082. this.particles = new Array();
  27083. this._stockParticles = new Array();
  27084. this._newPartsExcess = 0;
  27085. this._vertexBuffers = {};
  27086. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  27087. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  27088. this._scaledDirection = BABYLON.Vector3.Zero();
  27089. this._scaledGravity = BABYLON.Vector3.Zero();
  27090. this._currentRenderId = -1;
  27091. this._started = false;
  27092. this._stopped = false;
  27093. this._actualFrame = 0;
  27094. this.id = name;
  27095. this._capacity = capacity;
  27096. this._scene = scene;
  27097. this._customEffect = customEffect;
  27098. scene.particleSystems.push(this);
  27099. var indices = [];
  27100. var index = 0;
  27101. for (var count = 0; count < capacity; count++) {
  27102. indices.push(index);
  27103. indices.push(index + 1);
  27104. indices.push(index + 2);
  27105. indices.push(index);
  27106. indices.push(index + 2);
  27107. indices.push(index + 3);
  27108. index += 4;
  27109. }
  27110. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27111. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  27112. this._vertexData = new Float32Array(capacity * 11 * 4);
  27113. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  27114. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  27115. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  27116. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  27117. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27118. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27119. this._vertexBuffers["options"] = options;
  27120. // Default behaviors
  27121. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  27122. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  27123. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  27124. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  27125. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  27126. };
  27127. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  27128. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  27129. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  27130. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  27131. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  27132. };
  27133. this.updateFunction = function (particles) {
  27134. for (var index = 0; index < particles.length; index++) {
  27135. var particle = particles[index];
  27136. particle.age += _this._scaledUpdateSpeed;
  27137. if (particle.age >= particle.lifeTime) {
  27138. _this.recycleParticle(particle);
  27139. index--;
  27140. continue;
  27141. }
  27142. else {
  27143. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  27144. particle.color.addInPlace(_this._scaledColorStep);
  27145. if (particle.color.a < 0)
  27146. particle.color.a = 0;
  27147. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  27148. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  27149. particle.position.addInPlace(_this._scaledDirection);
  27150. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  27151. particle.direction.addInPlace(_this._scaledGravity);
  27152. }
  27153. }
  27154. };
  27155. }
  27156. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  27157. set: function (callback) {
  27158. if (this._onDisposeObserver) {
  27159. this.onDisposeObservable.remove(this._onDisposeObserver);
  27160. }
  27161. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27162. },
  27163. enumerable: true,
  27164. configurable: true
  27165. });
  27166. ParticleSystem.prototype.recycleParticle = function (particle) {
  27167. var lastParticle = this.particles.pop();
  27168. if (lastParticle !== particle) {
  27169. lastParticle.copyTo(particle);
  27170. this._stockParticles.push(lastParticle);
  27171. }
  27172. };
  27173. ParticleSystem.prototype.getCapacity = function () {
  27174. return this._capacity;
  27175. };
  27176. ParticleSystem.prototype.isAlive = function () {
  27177. return this._alive;
  27178. };
  27179. ParticleSystem.prototype.isStarted = function () {
  27180. return this._started;
  27181. };
  27182. ParticleSystem.prototype.start = function () {
  27183. this._started = true;
  27184. this._stopped = false;
  27185. this._actualFrame = 0;
  27186. };
  27187. ParticleSystem.prototype.stop = function () {
  27188. this._stopped = true;
  27189. };
  27190. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  27191. var offset = index * 11;
  27192. this._vertexData[offset] = particle.position.x;
  27193. this._vertexData[offset + 1] = particle.position.y;
  27194. this._vertexData[offset + 2] = particle.position.z;
  27195. this._vertexData[offset + 3] = particle.color.r;
  27196. this._vertexData[offset + 4] = particle.color.g;
  27197. this._vertexData[offset + 5] = particle.color.b;
  27198. this._vertexData[offset + 6] = particle.color.a;
  27199. this._vertexData[offset + 7] = particle.angle;
  27200. this._vertexData[offset + 8] = particle.size;
  27201. this._vertexData[offset + 9] = offsetX;
  27202. this._vertexData[offset + 10] = offsetY;
  27203. };
  27204. ParticleSystem.prototype._update = function (newParticles) {
  27205. // Update current
  27206. this._alive = this.particles.length > 0;
  27207. this.updateFunction(this.particles);
  27208. // Add new ones
  27209. var worldMatrix;
  27210. if (this.emitter.position) {
  27211. worldMatrix = this.emitter.getWorldMatrix();
  27212. }
  27213. else {
  27214. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  27215. }
  27216. var particle;
  27217. for (var index = 0; index < newParticles; index++) {
  27218. if (this.particles.length === this._capacity) {
  27219. break;
  27220. }
  27221. if (this._stockParticles.length !== 0) {
  27222. particle = this._stockParticles.pop();
  27223. particle.age = 0;
  27224. }
  27225. else {
  27226. particle = new BABYLON.Particle();
  27227. }
  27228. this.particles.push(particle);
  27229. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  27230. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  27231. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  27232. particle.size = randomNumber(this.minSize, this.maxSize);
  27233. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  27234. this.startPositionFunction(worldMatrix, particle.position, particle);
  27235. var step = randomNumber(0, 1.0);
  27236. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  27237. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  27238. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  27239. }
  27240. };
  27241. ParticleSystem.prototype._getEffect = function () {
  27242. if (this._customEffect) {
  27243. return this._customEffect;
  27244. }
  27245. ;
  27246. var defines = [];
  27247. if (this._scene.clipPlane) {
  27248. defines.push("#define CLIPPLANE");
  27249. }
  27250. // Effect
  27251. var join = defines.join("\n");
  27252. if (this._cachedDefines !== join) {
  27253. this._cachedDefines = join;
  27254. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  27255. }
  27256. return this._effect;
  27257. };
  27258. ParticleSystem.prototype.animate = function () {
  27259. if (!this._started)
  27260. return;
  27261. var effect = this._getEffect();
  27262. // Check
  27263. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  27264. return;
  27265. if (this._currentRenderId === this._scene.getRenderId()) {
  27266. return;
  27267. }
  27268. this._currentRenderId = this._scene.getRenderId();
  27269. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  27270. // determine the number of particles we need to create
  27271. var newParticles;
  27272. if (this.manualEmitCount > -1) {
  27273. newParticles = this.manualEmitCount;
  27274. this._newPartsExcess = 0;
  27275. this.manualEmitCount = 0;
  27276. }
  27277. else {
  27278. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  27279. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  27280. }
  27281. if (this._newPartsExcess > 1.0) {
  27282. newParticles += this._newPartsExcess >> 0;
  27283. this._newPartsExcess -= this._newPartsExcess >> 0;
  27284. }
  27285. this._alive = false;
  27286. if (!this._stopped) {
  27287. this._actualFrame += this._scaledUpdateSpeed;
  27288. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  27289. this.stop();
  27290. }
  27291. else {
  27292. newParticles = 0;
  27293. }
  27294. this._update(newParticles);
  27295. // Stopped?
  27296. if (this._stopped) {
  27297. if (!this._alive) {
  27298. this._started = false;
  27299. if (this.disposeOnStop) {
  27300. this._scene._toBeDisposed.push(this);
  27301. }
  27302. }
  27303. }
  27304. // Update VBO
  27305. var offset = 0;
  27306. for (var index = 0; index < this.particles.length; index++) {
  27307. var particle = this.particles[index];
  27308. this._appendParticleVertex(offset++, particle, 0, 0);
  27309. this._appendParticleVertex(offset++, particle, 1, 0);
  27310. this._appendParticleVertex(offset++, particle, 1, 1);
  27311. this._appendParticleVertex(offset++, particle, 0, 1);
  27312. }
  27313. this._vertexBuffer.update(this._vertexData);
  27314. };
  27315. ParticleSystem.prototype.render = function () {
  27316. var effect = this._getEffect();
  27317. // Check
  27318. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  27319. return 0;
  27320. var engine = this._scene.getEngine();
  27321. // Render
  27322. engine.enableEffect(effect);
  27323. engine.setState(false);
  27324. var viewMatrix = this._scene.getViewMatrix();
  27325. effect.setTexture("diffuseSampler", this.particleTexture);
  27326. effect.setMatrix("view", viewMatrix);
  27327. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27328. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  27329. if (this._scene.clipPlane) {
  27330. var clipPlane = this._scene.clipPlane;
  27331. var invView = viewMatrix.clone();
  27332. invView.invert();
  27333. effect.setMatrix("invView", invView);
  27334. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27335. }
  27336. // VBOs
  27337. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27338. // Draw order
  27339. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  27340. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  27341. }
  27342. else {
  27343. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27344. }
  27345. if (this.forceDepthWrite) {
  27346. engine.setDepthWrite(true);
  27347. }
  27348. engine.draw(true, 0, this.particles.length * 6);
  27349. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27350. return this.particles.length;
  27351. };
  27352. ParticleSystem.prototype.dispose = function () {
  27353. if (this._vertexBuffer) {
  27354. this._vertexBuffer.dispose();
  27355. this._vertexBuffer = null;
  27356. }
  27357. if (this._indexBuffer) {
  27358. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27359. this._indexBuffer = null;
  27360. }
  27361. if (this.particleTexture) {
  27362. this.particleTexture.dispose();
  27363. this.particleTexture = null;
  27364. }
  27365. // Remove from scene
  27366. var index = this._scene.particleSystems.indexOf(this);
  27367. this._scene.particleSystems.splice(index, 1);
  27368. // Callback
  27369. this.onDisposeObservable.notifyObservers(this);
  27370. this.onDisposeObservable.clear();
  27371. };
  27372. // Clone
  27373. ParticleSystem.prototype.clone = function (name, newEmitter) {
  27374. var result = new ParticleSystem(name, this._capacity, this._scene);
  27375. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  27376. if (newEmitter === undefined) {
  27377. newEmitter = this.emitter;
  27378. }
  27379. result.emitter = newEmitter;
  27380. if (this.particleTexture) {
  27381. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  27382. }
  27383. result.start();
  27384. return result;
  27385. };
  27386. ParticleSystem.prototype.serialize = function () {
  27387. var serializationObject = {};
  27388. serializationObject.name = this.name;
  27389. serializationObject.id = this.id;
  27390. // Emitter
  27391. if (this.emitter.position) {
  27392. serializationObject.emitterId = this.emitter.id;
  27393. }
  27394. else {
  27395. serializationObject.emitter = this.emitter.asArray();
  27396. }
  27397. serializationObject.capacity = this.getCapacity();
  27398. if (this.particleTexture) {
  27399. serializationObject.textureName = this.particleTexture.name;
  27400. }
  27401. // Animations
  27402. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27403. // Particle system
  27404. serializationObject.minAngularSpeed = this.minAngularSpeed;
  27405. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  27406. serializationObject.minSize = this.minSize;
  27407. serializationObject.maxSize = this.maxSize;
  27408. serializationObject.minEmitPower = this.minEmitPower;
  27409. serializationObject.maxEmitPower = this.maxEmitPower;
  27410. serializationObject.minLifeTime = this.minLifeTime;
  27411. serializationObject.maxLifeTime = this.maxLifeTime;
  27412. serializationObject.emitRate = this.emitRate;
  27413. serializationObject.minEmitBox = this.minEmitBox.asArray();
  27414. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  27415. serializationObject.gravity = this.gravity.asArray();
  27416. serializationObject.direction1 = this.direction1.asArray();
  27417. serializationObject.direction2 = this.direction2.asArray();
  27418. serializationObject.color1 = this.color1.asArray();
  27419. serializationObject.color2 = this.color2.asArray();
  27420. serializationObject.colorDead = this.colorDead.asArray();
  27421. serializationObject.updateSpeed = this.updateSpeed;
  27422. serializationObject.targetStopDuration = this.targetStopDuration;
  27423. serializationObject.textureMask = this.textureMask.asArray();
  27424. serializationObject.blendMode = this.blendMode;
  27425. return serializationObject;
  27426. };
  27427. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  27428. var name = parsedParticleSystem.name;
  27429. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  27430. if (parsedParticleSystem.id) {
  27431. particleSystem.id = parsedParticleSystem.id;
  27432. }
  27433. // Texture
  27434. if (parsedParticleSystem.textureName) {
  27435. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  27436. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  27437. }
  27438. // Emitter
  27439. if (parsedParticleSystem.emitterId) {
  27440. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  27441. }
  27442. else {
  27443. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  27444. }
  27445. // Animations
  27446. if (parsedParticleSystem.animations) {
  27447. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  27448. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  27449. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27450. }
  27451. }
  27452. if (parsedParticleSystem.autoAnimate) {
  27453. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  27454. }
  27455. // Particle system
  27456. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  27457. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  27458. particleSystem.minSize = parsedParticleSystem.minSize;
  27459. particleSystem.maxSize = parsedParticleSystem.maxSize;
  27460. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  27461. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  27462. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  27463. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  27464. particleSystem.emitRate = parsedParticleSystem.emitRate;
  27465. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  27466. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  27467. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  27468. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  27469. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  27470. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  27471. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  27472. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  27473. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  27474. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  27475. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  27476. particleSystem.blendMode = parsedParticleSystem.blendMode;
  27477. if (!parsedParticleSystem.preventAutoStart) {
  27478. particleSystem.start();
  27479. }
  27480. return particleSystem;
  27481. };
  27482. // Statics
  27483. ParticleSystem.BLENDMODE_ONEONE = 0;
  27484. ParticleSystem.BLENDMODE_STANDARD = 1;
  27485. return ParticleSystem;
  27486. })();
  27487. BABYLON.ParticleSystem = ParticleSystem;
  27488. })(BABYLON || (BABYLON = {}));
  27489. var BABYLON;
  27490. (function (BABYLON) {
  27491. var AnimationRange = (function () {
  27492. function AnimationRange(name, from, to) {
  27493. this.name = name;
  27494. this.from = from;
  27495. this.to = to;
  27496. }
  27497. AnimationRange.prototype.clone = function () {
  27498. return new AnimationRange(this.name, this.from, this.to);
  27499. };
  27500. return AnimationRange;
  27501. })();
  27502. BABYLON.AnimationRange = AnimationRange;
  27503. /**
  27504. * Composed of a frame, and an action function
  27505. */
  27506. var AnimationEvent = (function () {
  27507. function AnimationEvent(frame, action, onlyOnce) {
  27508. this.frame = frame;
  27509. this.action = action;
  27510. this.onlyOnce = onlyOnce;
  27511. this.isDone = false;
  27512. }
  27513. return AnimationEvent;
  27514. })();
  27515. BABYLON.AnimationEvent = AnimationEvent;
  27516. var PathCursor = (function () {
  27517. function PathCursor(path) {
  27518. this.path = path;
  27519. this._onchange = new Array();
  27520. this.value = 0;
  27521. this.animations = new Array();
  27522. }
  27523. PathCursor.prototype.getPoint = function () {
  27524. var point = this.path.getPointAtLengthPosition(this.value);
  27525. return new BABYLON.Vector3(point.x, 0, point.y);
  27526. };
  27527. PathCursor.prototype.moveAhead = function (step) {
  27528. if (step === void 0) { step = 0.002; }
  27529. this.move(step);
  27530. return this;
  27531. };
  27532. PathCursor.prototype.moveBack = function (step) {
  27533. if (step === void 0) { step = 0.002; }
  27534. this.move(-step);
  27535. return this;
  27536. };
  27537. PathCursor.prototype.move = function (step) {
  27538. if (Math.abs(step) > 1) {
  27539. throw "step size should be less than 1.";
  27540. }
  27541. this.value += step;
  27542. this.ensureLimits();
  27543. this.raiseOnChange();
  27544. return this;
  27545. };
  27546. PathCursor.prototype.ensureLimits = function () {
  27547. while (this.value > 1) {
  27548. this.value -= 1;
  27549. }
  27550. while (this.value < 0) {
  27551. this.value += 1;
  27552. }
  27553. return this;
  27554. };
  27555. // used by animation engine
  27556. PathCursor.prototype.markAsDirty = function (propertyName) {
  27557. this.ensureLimits();
  27558. this.raiseOnChange();
  27559. return this;
  27560. };
  27561. PathCursor.prototype.raiseOnChange = function () {
  27562. var _this = this;
  27563. this._onchange.forEach(function (f) { return f(_this); });
  27564. return this;
  27565. };
  27566. PathCursor.prototype.onchange = function (f) {
  27567. this._onchange.push(f);
  27568. return this;
  27569. };
  27570. return PathCursor;
  27571. })();
  27572. BABYLON.PathCursor = PathCursor;
  27573. var Animation = (function () {
  27574. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  27575. this.name = name;
  27576. this.targetProperty = targetProperty;
  27577. this.framePerSecond = framePerSecond;
  27578. this.dataType = dataType;
  27579. this.loopMode = loopMode;
  27580. this.enableBlending = enableBlending;
  27581. this._offsetsCache = {};
  27582. this._highLimitsCache = {};
  27583. this._stopped = false;
  27584. this._blendingFactor = 0;
  27585. // The set of event that will be linked to this animation
  27586. this._events = new Array();
  27587. this.allowMatricesInterpolation = false;
  27588. this.blendingSpeed = 0.01;
  27589. this._ranges = {};
  27590. this.targetPropertyPath = targetProperty.split(".");
  27591. this.dataType = dataType;
  27592. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  27593. }
  27594. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  27595. var dataType = undefined;
  27596. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  27597. dataType = Animation.ANIMATIONTYPE_FLOAT;
  27598. }
  27599. else if (from instanceof BABYLON.Quaternion) {
  27600. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  27601. }
  27602. else if (from instanceof BABYLON.Vector3) {
  27603. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  27604. }
  27605. else if (from instanceof BABYLON.Vector2) {
  27606. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  27607. }
  27608. else if (from instanceof BABYLON.Color3) {
  27609. dataType = Animation.ANIMATIONTYPE_COLOR3;
  27610. }
  27611. else if (from instanceof BABYLON.Size) {
  27612. dataType = Animation.ANIMATIONTYPE_SIZE;
  27613. }
  27614. if (dataType == undefined) {
  27615. return null;
  27616. }
  27617. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  27618. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  27619. animation.setKeys(keys);
  27620. if (easingFunction !== undefined) {
  27621. animation.setEasingFunction(easingFunction);
  27622. }
  27623. return animation;
  27624. };
  27625. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27626. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27627. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27628. };
  27629. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27630. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27631. node.animations.push(animation);
  27632. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27633. };
  27634. // Methods
  27635. /**
  27636. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27637. */
  27638. Animation.prototype.toString = function (fullDetails) {
  27639. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  27640. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  27641. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  27642. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  27643. if (fullDetails) {
  27644. ret += ", Ranges: {";
  27645. var first = true;
  27646. for (var name in this._ranges) {
  27647. if (first) {
  27648. ret += ", ";
  27649. first = false;
  27650. }
  27651. ret += name;
  27652. }
  27653. ret += "}";
  27654. }
  27655. return ret;
  27656. };
  27657. /**
  27658. * Add an event to this animation.
  27659. */
  27660. Animation.prototype.addEvent = function (event) {
  27661. this._events.push(event);
  27662. };
  27663. /**
  27664. * Remove all events found at the given frame
  27665. * @param frame
  27666. */
  27667. Animation.prototype.removeEvents = function (frame) {
  27668. for (var index = 0; index < this._events.length; index++) {
  27669. if (this._events[index].frame === frame) {
  27670. this._events.splice(index, 1);
  27671. index--;
  27672. }
  27673. }
  27674. };
  27675. Animation.prototype.createRange = function (name, from, to) {
  27676. // check name not already in use; could happen for bones after serialized
  27677. if (!this._ranges[name]) {
  27678. this._ranges[name] = new AnimationRange(name, from, to);
  27679. }
  27680. };
  27681. Animation.prototype.deleteRange = function (name, deleteFrames) {
  27682. if (deleteFrames === void 0) { deleteFrames = true; }
  27683. if (this._ranges[name]) {
  27684. if (deleteFrames) {
  27685. var from = this._ranges[name].from;
  27686. var to = this._ranges[name].to;
  27687. // this loop MUST go high to low for multiple splices to work
  27688. for (var key = this._keys.length - 1; key >= 0; key--) {
  27689. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  27690. this._keys.splice(key, 1);
  27691. }
  27692. }
  27693. }
  27694. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  27695. }
  27696. };
  27697. Animation.prototype.getRange = function (name) {
  27698. return this._ranges[name];
  27699. };
  27700. Animation.prototype.reset = function () {
  27701. this._offsetsCache = {};
  27702. this._highLimitsCache = {};
  27703. this.currentFrame = 0;
  27704. this._blendingFactor = 0;
  27705. this._originalBlendValue = null;
  27706. };
  27707. Animation.prototype.isStopped = function () {
  27708. return this._stopped;
  27709. };
  27710. Animation.prototype.getKeys = function () {
  27711. return this._keys;
  27712. };
  27713. Animation.prototype.getHighestFrame = function () {
  27714. var ret = 0;
  27715. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  27716. if (ret < this._keys[key].frame) {
  27717. ret = this._keys[key].frame;
  27718. }
  27719. }
  27720. return ret;
  27721. };
  27722. Animation.prototype.getEasingFunction = function () {
  27723. return this._easingFunction;
  27724. };
  27725. Animation.prototype.setEasingFunction = function (easingFunction) {
  27726. this._easingFunction = easingFunction;
  27727. };
  27728. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  27729. return startValue + (endValue - startValue) * gradient;
  27730. };
  27731. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  27732. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  27733. };
  27734. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  27735. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  27736. };
  27737. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  27738. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  27739. };
  27740. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  27741. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  27742. };
  27743. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  27744. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  27745. };
  27746. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  27747. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  27748. };
  27749. Animation.prototype.clone = function () {
  27750. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  27751. if (this._keys) {
  27752. clone.setKeys(this._keys);
  27753. }
  27754. if (this._ranges) {
  27755. clone._ranges = {};
  27756. for (var name in this._ranges) {
  27757. clone._ranges[name] = this._ranges[name].clone();
  27758. }
  27759. }
  27760. return clone;
  27761. };
  27762. Animation.prototype.setKeys = function (values) {
  27763. this._keys = values.slice(0);
  27764. this._offsetsCache = {};
  27765. this._highLimitsCache = {};
  27766. };
  27767. Animation.prototype._getKeyValue = function (value) {
  27768. if (typeof value === "function") {
  27769. return value();
  27770. }
  27771. return value;
  27772. };
  27773. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  27774. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  27775. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  27776. }
  27777. this.currentFrame = currentFrame;
  27778. // Try to get a hash to find the right key
  27779. 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));
  27780. if (this._keys[startKey].frame >= currentFrame) {
  27781. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  27782. startKey--;
  27783. }
  27784. }
  27785. for (var key = startKey; key < this._keys.length; key++) {
  27786. if (this._keys[key + 1].frame >= currentFrame) {
  27787. var startValue = this._getKeyValue(this._keys[key].value);
  27788. var endValue = this._getKeyValue(this._keys[key + 1].value);
  27789. // gradient : percent of currentFrame between the frame inf and the frame sup
  27790. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  27791. // check for easingFunction and correction of gradient
  27792. if (this._easingFunction != null) {
  27793. gradient = this._easingFunction.ease(gradient);
  27794. }
  27795. switch (this.dataType) {
  27796. // Float
  27797. case Animation.ANIMATIONTYPE_FLOAT:
  27798. switch (loopMode) {
  27799. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27800. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27801. return this.floatInterpolateFunction(startValue, endValue, gradient);
  27802. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27803. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  27804. }
  27805. break;
  27806. // Quaternion
  27807. case Animation.ANIMATIONTYPE_QUATERNION:
  27808. var quaternion = null;
  27809. switch (loopMode) {
  27810. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27811. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27812. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  27813. break;
  27814. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27815. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27816. break;
  27817. }
  27818. return quaternion;
  27819. // Vector3
  27820. case Animation.ANIMATIONTYPE_VECTOR3:
  27821. switch (loopMode) {
  27822. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27823. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27824. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  27825. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27826. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27827. }
  27828. // Vector2
  27829. case Animation.ANIMATIONTYPE_VECTOR2:
  27830. switch (loopMode) {
  27831. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27832. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27833. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  27834. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27835. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27836. }
  27837. // Size
  27838. case Animation.ANIMATIONTYPE_SIZE:
  27839. switch (loopMode) {
  27840. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27841. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27842. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  27843. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27844. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27845. }
  27846. // Color3
  27847. case Animation.ANIMATIONTYPE_COLOR3:
  27848. switch (loopMode) {
  27849. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27850. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27851. return this.color3InterpolateFunction(startValue, endValue, gradient);
  27852. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27853. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27854. }
  27855. // Matrix
  27856. case Animation.ANIMATIONTYPE_MATRIX:
  27857. switch (loopMode) {
  27858. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27859. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27860. if (this.allowMatricesInterpolation) {
  27861. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  27862. }
  27863. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27864. return startValue;
  27865. }
  27866. default:
  27867. break;
  27868. }
  27869. break;
  27870. }
  27871. }
  27872. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  27873. };
  27874. Animation.prototype.setValue = function (currentValue, blend) {
  27875. if (blend === void 0) { blend = false; }
  27876. // Set value
  27877. var path;
  27878. var destination;
  27879. if (this.targetPropertyPath.length > 1) {
  27880. var property = this._target[this.targetPropertyPath[0]];
  27881. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  27882. property = property[this.targetPropertyPath[index]];
  27883. }
  27884. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  27885. destination = property;
  27886. }
  27887. else {
  27888. path = this.targetPropertyPath[0];
  27889. destination = this._target;
  27890. }
  27891. // Blending
  27892. if (this.enableBlending && this._blendingFactor <= 1.0) {
  27893. if (!this._originalBlendValue) {
  27894. if (destination[path].clone) {
  27895. this._originalBlendValue = destination[path].clone();
  27896. }
  27897. else {
  27898. this._originalBlendValue = destination[path];
  27899. }
  27900. }
  27901. if (this._originalBlendValue.prototype) {
  27902. if (this._originalBlendValue.prototype.Lerp) {
  27903. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  27904. }
  27905. else {
  27906. destination[path] = currentValue;
  27907. }
  27908. }
  27909. else if (this._originalBlendValue.m) {
  27910. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  27911. }
  27912. else {
  27913. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  27914. }
  27915. this._blendingFactor += this.blendingSpeed;
  27916. }
  27917. else {
  27918. destination[path] = currentValue;
  27919. }
  27920. if (this._target.markAsDirty) {
  27921. this._target.markAsDirty(this.targetProperty);
  27922. }
  27923. };
  27924. Animation.prototype.goToFrame = function (frame) {
  27925. if (frame < this._keys[0].frame) {
  27926. frame = this._keys[0].frame;
  27927. }
  27928. else if (frame > this._keys[this._keys.length - 1].frame) {
  27929. frame = this._keys[this._keys.length - 1].frame;
  27930. }
  27931. var currentValue = this._interpolate(frame, 0, this.loopMode);
  27932. this.setValue(currentValue);
  27933. };
  27934. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  27935. if (blend === void 0) { blend = false; }
  27936. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  27937. this._stopped = true;
  27938. return false;
  27939. }
  27940. var returnValue = true;
  27941. // Adding a start key at frame 0 if missing
  27942. if (this._keys[0].frame !== 0) {
  27943. var newKey = { frame: 0, value: this._keys[0].value };
  27944. this._keys.splice(0, 0, newKey);
  27945. }
  27946. // Check limits
  27947. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  27948. from = this._keys[0].frame;
  27949. }
  27950. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  27951. to = this._keys[this._keys.length - 1].frame;
  27952. }
  27953. // Compute ratio
  27954. var range = to - from;
  27955. var offsetValue;
  27956. // ratio represents the frame delta between from and to
  27957. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  27958. var highLimitValue = 0;
  27959. if (ratio > range && !loop) {
  27960. returnValue = false;
  27961. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  27962. }
  27963. else {
  27964. // Get max value if required
  27965. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  27966. var keyOffset = to.toString() + from.toString();
  27967. if (!this._offsetsCache[keyOffset]) {
  27968. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27969. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27970. switch (this.dataType) {
  27971. // Float
  27972. case Animation.ANIMATIONTYPE_FLOAT:
  27973. this._offsetsCache[keyOffset] = toValue - fromValue;
  27974. break;
  27975. // Quaternion
  27976. case Animation.ANIMATIONTYPE_QUATERNION:
  27977. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27978. break;
  27979. // Vector3
  27980. case Animation.ANIMATIONTYPE_VECTOR3:
  27981. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27982. // Vector2
  27983. case Animation.ANIMATIONTYPE_VECTOR2:
  27984. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27985. // Size
  27986. case Animation.ANIMATIONTYPE_SIZE:
  27987. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27988. // Color3
  27989. case Animation.ANIMATIONTYPE_COLOR3:
  27990. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27991. default:
  27992. break;
  27993. }
  27994. this._highLimitsCache[keyOffset] = toValue;
  27995. }
  27996. highLimitValue = this._highLimitsCache[keyOffset];
  27997. offsetValue = this._offsetsCache[keyOffset];
  27998. }
  27999. }
  28000. if (offsetValue === undefined) {
  28001. switch (this.dataType) {
  28002. // Float
  28003. case Animation.ANIMATIONTYPE_FLOAT:
  28004. offsetValue = 0;
  28005. break;
  28006. // Quaternion
  28007. case Animation.ANIMATIONTYPE_QUATERNION:
  28008. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28009. break;
  28010. // Vector3
  28011. case Animation.ANIMATIONTYPE_VECTOR3:
  28012. offsetValue = BABYLON.Vector3.Zero();
  28013. break;
  28014. // Vector2
  28015. case Animation.ANIMATIONTYPE_VECTOR2:
  28016. offsetValue = BABYLON.Vector2.Zero();
  28017. break;
  28018. // Size
  28019. case Animation.ANIMATIONTYPE_SIZE:
  28020. offsetValue = BABYLON.Size.Zero();
  28021. break;
  28022. // Color3
  28023. case Animation.ANIMATIONTYPE_COLOR3:
  28024. offsetValue = BABYLON.Color3.Black();
  28025. }
  28026. }
  28027. // Compute value
  28028. var repeatCount = (ratio / range) >> 0;
  28029. var currentFrame = returnValue ? from + ratio % range : to;
  28030. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28031. // Set value
  28032. this.setValue(currentValue);
  28033. // Check events
  28034. for (var index = 0; index < this._events.length; index++) {
  28035. if (currentFrame >= this._events[index].frame) {
  28036. var event = this._events[index];
  28037. if (!event.isDone) {
  28038. // If event should be done only once, remove it.
  28039. if (event.onlyOnce) {
  28040. this._events.splice(index, 1);
  28041. index--;
  28042. }
  28043. event.isDone = true;
  28044. event.action();
  28045. } // Don't do anything if the event has already be done.
  28046. }
  28047. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28048. // reset event, the animation is looping
  28049. this._events[index].isDone = false;
  28050. }
  28051. }
  28052. if (!returnValue) {
  28053. this._stopped = true;
  28054. }
  28055. return returnValue;
  28056. };
  28057. Animation.prototype.serialize = function () {
  28058. var serializationObject = {};
  28059. serializationObject.name = this.name;
  28060. serializationObject.property = this.targetProperty;
  28061. serializationObject.framePerSecond = this.framePerSecond;
  28062. serializationObject.dataType = this.dataType;
  28063. serializationObject.loopBehavior = this.loopMode;
  28064. var dataType = this.dataType;
  28065. serializationObject.keys = [];
  28066. var keys = this.getKeys();
  28067. for (var index = 0; index < keys.length; index++) {
  28068. var animationKey = keys[index];
  28069. var key = {};
  28070. key.frame = animationKey.frame;
  28071. switch (dataType) {
  28072. case Animation.ANIMATIONTYPE_FLOAT:
  28073. key.values = [animationKey.value];
  28074. break;
  28075. case Animation.ANIMATIONTYPE_QUATERNION:
  28076. case Animation.ANIMATIONTYPE_MATRIX:
  28077. case Animation.ANIMATIONTYPE_VECTOR3:
  28078. case Animation.ANIMATIONTYPE_COLOR3:
  28079. key.values = animationKey.value.asArray();
  28080. break;
  28081. }
  28082. serializationObject.keys.push(key);
  28083. }
  28084. serializationObject.ranges = [];
  28085. for (var name in this._ranges) {
  28086. var range = {};
  28087. range.name = name;
  28088. range.from = this._ranges[name].from;
  28089. range.to = this._ranges[name].to;
  28090. serializationObject.ranges.push(range);
  28091. }
  28092. return serializationObject;
  28093. };
  28094. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28095. get: function () {
  28096. return Animation._ANIMATIONTYPE_FLOAT;
  28097. },
  28098. enumerable: true,
  28099. configurable: true
  28100. });
  28101. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28102. get: function () {
  28103. return Animation._ANIMATIONTYPE_VECTOR3;
  28104. },
  28105. enumerable: true,
  28106. configurable: true
  28107. });
  28108. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  28109. get: function () {
  28110. return Animation._ANIMATIONTYPE_VECTOR2;
  28111. },
  28112. enumerable: true,
  28113. configurable: true
  28114. });
  28115. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  28116. get: function () {
  28117. return Animation._ANIMATIONTYPE_SIZE;
  28118. },
  28119. enumerable: true,
  28120. configurable: true
  28121. });
  28122. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  28123. get: function () {
  28124. return Animation._ANIMATIONTYPE_QUATERNION;
  28125. },
  28126. enumerable: true,
  28127. configurable: true
  28128. });
  28129. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  28130. get: function () {
  28131. return Animation._ANIMATIONTYPE_MATRIX;
  28132. },
  28133. enumerable: true,
  28134. configurable: true
  28135. });
  28136. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  28137. get: function () {
  28138. return Animation._ANIMATIONTYPE_COLOR3;
  28139. },
  28140. enumerable: true,
  28141. configurable: true
  28142. });
  28143. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28144. get: function () {
  28145. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28146. },
  28147. enumerable: true,
  28148. configurable: true
  28149. });
  28150. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28151. get: function () {
  28152. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28153. },
  28154. enumerable: true,
  28155. configurable: true
  28156. });
  28157. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28158. get: function () {
  28159. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28160. },
  28161. enumerable: true,
  28162. configurable: true
  28163. });
  28164. Animation.Parse = function (parsedAnimation) {
  28165. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28166. var dataType = parsedAnimation.dataType;
  28167. var keys = [];
  28168. var data;
  28169. var index;
  28170. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28171. var key = parsedAnimation.keys[index];
  28172. switch (dataType) {
  28173. case Animation.ANIMATIONTYPE_FLOAT:
  28174. data = key.values[0];
  28175. break;
  28176. case Animation.ANIMATIONTYPE_QUATERNION:
  28177. data = BABYLON.Quaternion.FromArray(key.values);
  28178. break;
  28179. case Animation.ANIMATIONTYPE_MATRIX:
  28180. data = BABYLON.Matrix.FromArray(key.values);
  28181. break;
  28182. case Animation.ANIMATIONTYPE_COLOR3:
  28183. data = BABYLON.Color3.FromArray(key.values);
  28184. break;
  28185. case Animation.ANIMATIONTYPE_VECTOR3:
  28186. default:
  28187. data = BABYLON.Vector3.FromArray(key.values);
  28188. break;
  28189. }
  28190. keys.push({
  28191. frame: key.frame,
  28192. value: data
  28193. });
  28194. }
  28195. animation.setKeys(keys);
  28196. if (parsedAnimation.ranges) {
  28197. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  28198. data = parsedAnimation.ranges[index];
  28199. animation.createRange(data.name, data.from, data.to);
  28200. }
  28201. }
  28202. return animation;
  28203. };
  28204. Animation.AppendSerializedAnimations = function (source, destination) {
  28205. if (source.animations) {
  28206. destination.animations = [];
  28207. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28208. var animation = source.animations[animationIndex];
  28209. destination.animations.push(animation.serialize());
  28210. }
  28211. }
  28212. };
  28213. // Statics
  28214. Animation._ANIMATIONTYPE_FLOAT = 0;
  28215. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  28216. Animation._ANIMATIONTYPE_QUATERNION = 2;
  28217. Animation._ANIMATIONTYPE_MATRIX = 3;
  28218. Animation._ANIMATIONTYPE_COLOR3 = 4;
  28219. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  28220. Animation._ANIMATIONTYPE_SIZE = 6;
  28221. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  28222. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  28223. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  28224. return Animation;
  28225. })();
  28226. BABYLON.Animation = Animation;
  28227. })(BABYLON || (BABYLON = {}));
  28228. var BABYLON;
  28229. (function (BABYLON) {
  28230. var Animatable = (function () {
  28231. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  28232. if (fromFrame === void 0) { fromFrame = 0; }
  28233. if (toFrame === void 0) { toFrame = 100; }
  28234. if (loopAnimation === void 0) { loopAnimation = false; }
  28235. if (speedRatio === void 0) { speedRatio = 1.0; }
  28236. this.target = target;
  28237. this.fromFrame = fromFrame;
  28238. this.toFrame = toFrame;
  28239. this.loopAnimation = loopAnimation;
  28240. this.speedRatio = speedRatio;
  28241. this.onAnimationEnd = onAnimationEnd;
  28242. this._animations = new Array();
  28243. this._paused = false;
  28244. this.animationStarted = false;
  28245. if (animations) {
  28246. this.appendAnimations(target, animations);
  28247. }
  28248. this._scene = scene;
  28249. scene._activeAnimatables.push(this);
  28250. }
  28251. // Methods
  28252. Animatable.prototype.getAnimations = function () {
  28253. return this._animations;
  28254. };
  28255. Animatable.prototype.appendAnimations = function (target, animations) {
  28256. for (var index = 0; index < animations.length; index++) {
  28257. var animation = animations[index];
  28258. animation._target = target;
  28259. this._animations.push(animation);
  28260. }
  28261. };
  28262. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  28263. var animations = this._animations;
  28264. for (var index = 0; index < animations.length; index++) {
  28265. if (animations[index].targetProperty === property) {
  28266. return animations[index];
  28267. }
  28268. }
  28269. return null;
  28270. };
  28271. Animatable.prototype.reset = function () {
  28272. var animations = this._animations;
  28273. for (var index = 0; index < animations.length; index++) {
  28274. animations[index].reset();
  28275. }
  28276. this._localDelayOffset = null;
  28277. this._pausedDelay = null;
  28278. };
  28279. Animatable.prototype.enableBlending = function (blendingSpeed) {
  28280. var animations = this._animations;
  28281. for (var index = 0; index < animations.length; index++) {
  28282. animations[index].enableBlending = true;
  28283. animations[index].blendingSpeed = blendingSpeed;
  28284. }
  28285. };
  28286. Animatable.prototype.disableBlending = function () {
  28287. var animations = this._animations;
  28288. for (var index = 0; index < animations.length; index++) {
  28289. animations[index].enableBlending = false;
  28290. }
  28291. };
  28292. Animatable.prototype.goToFrame = function (frame) {
  28293. var animations = this._animations;
  28294. for (var index = 0; index < animations.length; index++) {
  28295. animations[index].goToFrame(frame);
  28296. }
  28297. };
  28298. Animatable.prototype.pause = function () {
  28299. if (this._paused) {
  28300. return;
  28301. }
  28302. this._paused = true;
  28303. };
  28304. Animatable.prototype.restart = function () {
  28305. this._paused = false;
  28306. };
  28307. Animatable.prototype.stop = function () {
  28308. var index = this._scene._activeAnimatables.indexOf(this);
  28309. if (index > -1) {
  28310. this._scene._activeAnimatables.splice(index, 1);
  28311. var animations = this._animations;
  28312. for (var index = 0; index < animations.length; index++) {
  28313. animations[index].reset();
  28314. }
  28315. if (this.onAnimationEnd) {
  28316. this.onAnimationEnd();
  28317. }
  28318. }
  28319. };
  28320. Animatable.prototype._animate = function (delay) {
  28321. if (this._paused) {
  28322. this.animationStarted = false;
  28323. if (!this._pausedDelay) {
  28324. this._pausedDelay = delay;
  28325. }
  28326. return true;
  28327. }
  28328. if (!this._localDelayOffset) {
  28329. this._localDelayOffset = delay;
  28330. }
  28331. else if (this._pausedDelay) {
  28332. this._localDelayOffset += delay - this._pausedDelay;
  28333. this._pausedDelay = null;
  28334. }
  28335. // Animating
  28336. var running = false;
  28337. var animations = this._animations;
  28338. var index;
  28339. for (index = 0; index < animations.length; index++) {
  28340. var animation = animations[index];
  28341. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  28342. running = running || isRunning;
  28343. }
  28344. this.animationStarted = running;
  28345. if (!running) {
  28346. // Remove from active animatables
  28347. index = this._scene._activeAnimatables.indexOf(this);
  28348. this._scene._activeAnimatables.splice(index, 1);
  28349. }
  28350. if (!running && this.onAnimationEnd) {
  28351. this.onAnimationEnd();
  28352. this.onAnimationEnd = null;
  28353. }
  28354. return running;
  28355. };
  28356. return Animatable;
  28357. })();
  28358. BABYLON.Animatable = Animatable;
  28359. })(BABYLON || (BABYLON = {}));
  28360. var BABYLON;
  28361. (function (BABYLON) {
  28362. var EasingFunction = (function () {
  28363. function EasingFunction() {
  28364. // Properties
  28365. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  28366. }
  28367. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  28368. get: function () {
  28369. return EasingFunction._EASINGMODE_EASEIN;
  28370. },
  28371. enumerable: true,
  28372. configurable: true
  28373. });
  28374. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  28375. get: function () {
  28376. return EasingFunction._EASINGMODE_EASEOUT;
  28377. },
  28378. enumerable: true,
  28379. configurable: true
  28380. });
  28381. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  28382. get: function () {
  28383. return EasingFunction._EASINGMODE_EASEINOUT;
  28384. },
  28385. enumerable: true,
  28386. configurable: true
  28387. });
  28388. EasingFunction.prototype.setEasingMode = function (easingMode) {
  28389. var n = Math.min(Math.max(easingMode, 0), 2);
  28390. this._easingMode = n;
  28391. };
  28392. EasingFunction.prototype.getEasingMode = function () {
  28393. return this._easingMode;
  28394. };
  28395. EasingFunction.prototype.easeInCore = function (gradient) {
  28396. throw new Error('You must implement this method');
  28397. };
  28398. EasingFunction.prototype.ease = function (gradient) {
  28399. switch (this._easingMode) {
  28400. case EasingFunction.EASINGMODE_EASEIN:
  28401. return this.easeInCore(gradient);
  28402. case EasingFunction.EASINGMODE_EASEOUT:
  28403. return (1 - this.easeInCore(1 - gradient));
  28404. }
  28405. if (gradient >= 0.5) {
  28406. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  28407. }
  28408. return (this.easeInCore(gradient * 2) * 0.5);
  28409. };
  28410. //Statics
  28411. EasingFunction._EASINGMODE_EASEIN = 0;
  28412. EasingFunction._EASINGMODE_EASEOUT = 1;
  28413. EasingFunction._EASINGMODE_EASEINOUT = 2;
  28414. return EasingFunction;
  28415. })();
  28416. BABYLON.EasingFunction = EasingFunction;
  28417. var CircleEase = (function (_super) {
  28418. __extends(CircleEase, _super);
  28419. function CircleEase() {
  28420. _super.apply(this, arguments);
  28421. }
  28422. CircleEase.prototype.easeInCore = function (gradient) {
  28423. gradient = Math.max(0, Math.min(1, gradient));
  28424. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  28425. };
  28426. return CircleEase;
  28427. })(EasingFunction);
  28428. BABYLON.CircleEase = CircleEase;
  28429. var BackEase = (function (_super) {
  28430. __extends(BackEase, _super);
  28431. function BackEase(amplitude) {
  28432. if (amplitude === void 0) { amplitude = 1; }
  28433. _super.call(this);
  28434. this.amplitude = amplitude;
  28435. }
  28436. BackEase.prototype.easeInCore = function (gradient) {
  28437. var num = Math.max(0, this.amplitude);
  28438. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  28439. };
  28440. return BackEase;
  28441. })(EasingFunction);
  28442. BABYLON.BackEase = BackEase;
  28443. var BounceEase = (function (_super) {
  28444. __extends(BounceEase, _super);
  28445. function BounceEase(bounces, bounciness) {
  28446. if (bounces === void 0) { bounces = 3; }
  28447. if (bounciness === void 0) { bounciness = 2; }
  28448. _super.call(this);
  28449. this.bounces = bounces;
  28450. this.bounciness = bounciness;
  28451. }
  28452. BounceEase.prototype.easeInCore = function (gradient) {
  28453. var y = Math.max(0.0, this.bounces);
  28454. var bounciness = this.bounciness;
  28455. if (bounciness <= 1.0) {
  28456. bounciness = 1.001;
  28457. }
  28458. var num9 = Math.pow(bounciness, y);
  28459. var num5 = 1.0 - bounciness;
  28460. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  28461. var num15 = gradient * num4;
  28462. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  28463. var num3 = Math.floor(num65);
  28464. var num13 = num3 + 1.0;
  28465. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  28466. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  28467. var num7 = (num8 + num12) * 0.5;
  28468. var num6 = gradient - num7;
  28469. var num2 = num7 - num8;
  28470. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  28471. };
  28472. return BounceEase;
  28473. })(EasingFunction);
  28474. BABYLON.BounceEase = BounceEase;
  28475. var CubicEase = (function (_super) {
  28476. __extends(CubicEase, _super);
  28477. function CubicEase() {
  28478. _super.apply(this, arguments);
  28479. }
  28480. CubicEase.prototype.easeInCore = function (gradient) {
  28481. return (gradient * gradient * gradient);
  28482. };
  28483. return CubicEase;
  28484. })(EasingFunction);
  28485. BABYLON.CubicEase = CubicEase;
  28486. var ElasticEase = (function (_super) {
  28487. __extends(ElasticEase, _super);
  28488. function ElasticEase(oscillations, springiness) {
  28489. if (oscillations === void 0) { oscillations = 3; }
  28490. if (springiness === void 0) { springiness = 3; }
  28491. _super.call(this);
  28492. this.oscillations = oscillations;
  28493. this.springiness = springiness;
  28494. }
  28495. ElasticEase.prototype.easeInCore = function (gradient) {
  28496. var num2;
  28497. var num3 = Math.max(0.0, this.oscillations);
  28498. var num = Math.max(0.0, this.springiness);
  28499. if (num == 0) {
  28500. num2 = gradient;
  28501. }
  28502. else {
  28503. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  28504. }
  28505. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  28506. };
  28507. return ElasticEase;
  28508. })(EasingFunction);
  28509. BABYLON.ElasticEase = ElasticEase;
  28510. var ExponentialEase = (function (_super) {
  28511. __extends(ExponentialEase, _super);
  28512. function ExponentialEase(exponent) {
  28513. if (exponent === void 0) { exponent = 2; }
  28514. _super.call(this);
  28515. this.exponent = exponent;
  28516. }
  28517. ExponentialEase.prototype.easeInCore = function (gradient) {
  28518. if (this.exponent <= 0) {
  28519. return gradient;
  28520. }
  28521. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  28522. };
  28523. return ExponentialEase;
  28524. })(EasingFunction);
  28525. BABYLON.ExponentialEase = ExponentialEase;
  28526. var PowerEase = (function (_super) {
  28527. __extends(PowerEase, _super);
  28528. function PowerEase(power) {
  28529. if (power === void 0) { power = 2; }
  28530. _super.call(this);
  28531. this.power = power;
  28532. }
  28533. PowerEase.prototype.easeInCore = function (gradient) {
  28534. var y = Math.max(0.0, this.power);
  28535. return Math.pow(gradient, y);
  28536. };
  28537. return PowerEase;
  28538. })(EasingFunction);
  28539. BABYLON.PowerEase = PowerEase;
  28540. var QuadraticEase = (function (_super) {
  28541. __extends(QuadraticEase, _super);
  28542. function QuadraticEase() {
  28543. _super.apply(this, arguments);
  28544. }
  28545. QuadraticEase.prototype.easeInCore = function (gradient) {
  28546. return (gradient * gradient);
  28547. };
  28548. return QuadraticEase;
  28549. })(EasingFunction);
  28550. BABYLON.QuadraticEase = QuadraticEase;
  28551. var QuarticEase = (function (_super) {
  28552. __extends(QuarticEase, _super);
  28553. function QuarticEase() {
  28554. _super.apply(this, arguments);
  28555. }
  28556. QuarticEase.prototype.easeInCore = function (gradient) {
  28557. return (gradient * gradient * gradient * gradient);
  28558. };
  28559. return QuarticEase;
  28560. })(EasingFunction);
  28561. BABYLON.QuarticEase = QuarticEase;
  28562. var QuinticEase = (function (_super) {
  28563. __extends(QuinticEase, _super);
  28564. function QuinticEase() {
  28565. _super.apply(this, arguments);
  28566. }
  28567. QuinticEase.prototype.easeInCore = function (gradient) {
  28568. return (gradient * gradient * gradient * gradient * gradient);
  28569. };
  28570. return QuinticEase;
  28571. })(EasingFunction);
  28572. BABYLON.QuinticEase = QuinticEase;
  28573. var SineEase = (function (_super) {
  28574. __extends(SineEase, _super);
  28575. function SineEase() {
  28576. _super.apply(this, arguments);
  28577. }
  28578. SineEase.prototype.easeInCore = function (gradient) {
  28579. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  28580. };
  28581. return SineEase;
  28582. })(EasingFunction);
  28583. BABYLON.SineEase = SineEase;
  28584. var BezierCurveEase = (function (_super) {
  28585. __extends(BezierCurveEase, _super);
  28586. function BezierCurveEase(x1, y1, x2, y2) {
  28587. if (x1 === void 0) { x1 = 0; }
  28588. if (y1 === void 0) { y1 = 0; }
  28589. if (x2 === void 0) { x2 = 1; }
  28590. if (y2 === void 0) { y2 = 1; }
  28591. _super.call(this);
  28592. this.x1 = x1;
  28593. this.y1 = y1;
  28594. this.x2 = x2;
  28595. this.y2 = y2;
  28596. }
  28597. BezierCurveEase.prototype.easeInCore = function (gradient) {
  28598. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  28599. };
  28600. return BezierCurveEase;
  28601. })(EasingFunction);
  28602. BABYLON.BezierCurveEase = BezierCurveEase;
  28603. })(BABYLON || (BABYLON = {}));
  28604. var BABYLON;
  28605. (function (BABYLON) {
  28606. var Bone = (function (_super) {
  28607. __extends(Bone, _super);
  28608. function Bone(name, skeleton, parentBone, matrix, restPose) {
  28609. _super.call(this, name, skeleton.getScene());
  28610. this.name = name;
  28611. this.children = new Array();
  28612. this.animations = new Array();
  28613. this._worldTransform = new BABYLON.Matrix();
  28614. this._absoluteTransform = new BABYLON.Matrix();
  28615. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  28616. this._skeleton = skeleton;
  28617. this._matrix = matrix;
  28618. this._baseMatrix = matrix;
  28619. this._restPose = restPose ? restPose : matrix.clone();
  28620. skeleton.bones.push(this);
  28621. if (parentBone) {
  28622. this._parent = parentBone;
  28623. parentBone.children.push(this);
  28624. }
  28625. else {
  28626. this._parent = null;
  28627. }
  28628. this._updateDifferenceMatrix();
  28629. }
  28630. // Members
  28631. Bone.prototype.getParent = function () {
  28632. return this._parent;
  28633. };
  28634. Bone.prototype.getLocalMatrix = function () {
  28635. return this._matrix;
  28636. };
  28637. Bone.prototype.getBaseMatrix = function () {
  28638. return this._baseMatrix;
  28639. };
  28640. Bone.prototype.getRestPose = function () {
  28641. return this._restPose;
  28642. };
  28643. Bone.prototype.returnToRest = function () {
  28644. this.updateMatrix(this._restPose.clone());
  28645. };
  28646. Bone.prototype.getWorldMatrix = function () {
  28647. return this._worldTransform;
  28648. };
  28649. Bone.prototype.getInvertedAbsoluteTransform = function () {
  28650. return this._invertedAbsoluteTransform;
  28651. };
  28652. Bone.prototype.getAbsoluteTransform = function () {
  28653. return this._absoluteTransform;
  28654. };
  28655. // Methods
  28656. Bone.prototype.updateMatrix = function (matrix) {
  28657. this._baseMatrix = matrix.clone();
  28658. this._matrix = matrix.clone();
  28659. this._skeleton._markAsDirty();
  28660. this._updateDifferenceMatrix();
  28661. };
  28662. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  28663. if (!rootMatrix) {
  28664. rootMatrix = this._baseMatrix;
  28665. }
  28666. if (this._parent) {
  28667. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  28668. }
  28669. else {
  28670. this._absoluteTransform.copyFrom(rootMatrix);
  28671. }
  28672. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  28673. for (var index = 0; index < this.children.length; index++) {
  28674. this.children[index]._updateDifferenceMatrix();
  28675. }
  28676. };
  28677. Bone.prototype.markAsDirty = function () {
  28678. this._currentRenderId++;
  28679. this._skeleton._markAsDirty();
  28680. };
  28681. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  28682. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28683. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  28684. // all animation may be coming from a library skeleton, so may need to create animation
  28685. if (this.animations.length === 0) {
  28686. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  28687. this.animations[0].setKeys([]);
  28688. }
  28689. // get animation info / verify there is such a range from the source bone
  28690. var sourceRange = source.animations[0].getRange(rangeName);
  28691. if (!sourceRange) {
  28692. return false;
  28693. }
  28694. var from = sourceRange.from;
  28695. var to = sourceRange.to;
  28696. var sourceKeys = source.animations[0].getKeys();
  28697. // rescaling prep
  28698. var sourceBoneLength = source.length;
  28699. var sourceParent = source.getParent();
  28700. var parent = this.getParent();
  28701. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  28702. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  28703. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  28704. var destKeys = this.animations[0].getKeys();
  28705. // loop vars declaration
  28706. var orig;
  28707. var origTranslation;
  28708. var mat;
  28709. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  28710. orig = sourceKeys[key];
  28711. if (orig.frame >= from && orig.frame <= to) {
  28712. if (rescaleAsRequired) {
  28713. mat = orig.value.clone();
  28714. // scale based on parent ratio, when bone has parent
  28715. if (parentScalingReqd) {
  28716. origTranslation = mat.getTranslation();
  28717. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  28718. }
  28719. else if (dimensionsScalingReqd) {
  28720. origTranslation = mat.getTranslation();
  28721. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  28722. }
  28723. else {
  28724. mat = orig.value;
  28725. }
  28726. }
  28727. else {
  28728. mat = orig.value;
  28729. }
  28730. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  28731. }
  28732. }
  28733. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  28734. return true;
  28735. };
  28736. return Bone;
  28737. })(BABYLON.Node);
  28738. BABYLON.Bone = Bone;
  28739. })(BABYLON || (BABYLON = {}));
  28740. var BABYLON;
  28741. (function (BABYLON) {
  28742. var Skeleton = (function () {
  28743. function Skeleton(name, id, scene) {
  28744. this.name = name;
  28745. this.id = id;
  28746. this.bones = new Array();
  28747. this.needInitialSkinMatrix = false;
  28748. this._isDirty = true;
  28749. this._meshesWithPoseMatrix = new Array();
  28750. this._identity = BABYLON.Matrix.Identity();
  28751. this._ranges = {};
  28752. this.bones = [];
  28753. this._scene = scene;
  28754. scene.skeletons.push(this);
  28755. //make sure it will recalculate the matrix next time prepare is called.
  28756. this._isDirty = true;
  28757. }
  28758. // Members
  28759. Skeleton.prototype.getTransformMatrices = function (mesh) {
  28760. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  28761. return mesh._bonesTransformMatrices;
  28762. }
  28763. return this._transformMatrices;
  28764. };
  28765. Skeleton.prototype.getScene = function () {
  28766. return this._scene;
  28767. };
  28768. // Methods
  28769. /**
  28770. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28771. */
  28772. Skeleton.prototype.toString = function (fullDetails) {
  28773. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  28774. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28775. if (fullDetails) {
  28776. ret += ", Ranges: {";
  28777. var first = true;
  28778. for (var name_1 in this._ranges) {
  28779. if (first) {
  28780. ret += ", ";
  28781. first = false;
  28782. }
  28783. ret += name_1;
  28784. }
  28785. ret += "}";
  28786. }
  28787. return ret;
  28788. };
  28789. /**
  28790. * Get bone's index searching by name
  28791. * @param {string} name is bone's name to search for
  28792. * @return {number} Indice of the bone. Returns -1 if not found
  28793. */
  28794. Skeleton.prototype.getBoneIndexByName = function (name) {
  28795. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  28796. if (this.bones[boneIndex].name === name) {
  28797. return boneIndex;
  28798. }
  28799. }
  28800. return -1;
  28801. };
  28802. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  28803. // check name not already in use
  28804. if (!this._ranges[name]) {
  28805. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  28806. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28807. if (this.bones[i].animations[0]) {
  28808. this.bones[i].animations[0].createRange(name, from, to);
  28809. }
  28810. }
  28811. }
  28812. };
  28813. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  28814. if (deleteFrames === void 0) { deleteFrames = true; }
  28815. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28816. if (this.bones[i].animations[0]) {
  28817. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  28818. }
  28819. }
  28820. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28821. };
  28822. Skeleton.prototype.getAnimationRange = function (name) {
  28823. return this._ranges[name];
  28824. };
  28825. /**
  28826. * Returns as an Array, all AnimationRanges defined on this skeleton
  28827. */
  28828. Skeleton.prototype.getAnimationRanges = function () {
  28829. var animationRanges = [];
  28830. var name;
  28831. var i = 0;
  28832. for (name in this._ranges) {
  28833. animationRanges[i] = this._ranges[name];
  28834. i++;
  28835. }
  28836. return animationRanges;
  28837. };
  28838. /**
  28839. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  28840. */
  28841. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  28842. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28843. if (this._ranges[name] || !source.getAnimationRange(name)) {
  28844. return false;
  28845. }
  28846. var ret = true;
  28847. var frameOffset = this._getHighestAnimationFrame() + 1;
  28848. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  28849. var boneDict = {};
  28850. var sourceBones = source.bones;
  28851. var nBones;
  28852. var i;
  28853. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  28854. boneDict[sourceBones[i].name] = sourceBones[i];
  28855. }
  28856. if (this.bones.length !== sourceBones.length) {
  28857. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  28858. ret = false;
  28859. }
  28860. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  28861. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  28862. var boneName = this.bones[i].name;
  28863. var sourceBone = boneDict[boneName];
  28864. if (sourceBone) {
  28865. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  28866. }
  28867. else {
  28868. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  28869. ret = false;
  28870. }
  28871. }
  28872. // do not call createAnimationRange(), since it also is done to bones, which was already done
  28873. var range = source.getAnimationRange(name);
  28874. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  28875. return ret;
  28876. };
  28877. Skeleton.prototype.returnToRest = function () {
  28878. for (var index = 0; index < this.bones.length; index++) {
  28879. this.bones[index].returnToRest();
  28880. }
  28881. };
  28882. Skeleton.prototype._getHighestAnimationFrame = function () {
  28883. var ret = 0;
  28884. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28885. if (this.bones[i].animations[0]) {
  28886. var highest = this.bones[i].animations[0].getHighestFrame();
  28887. if (ret < highest) {
  28888. ret = highest;
  28889. }
  28890. }
  28891. }
  28892. return ret;
  28893. };
  28894. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  28895. var range = this.getAnimationRange(name);
  28896. if (!range) {
  28897. return null;
  28898. }
  28899. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  28900. };
  28901. Skeleton.prototype._markAsDirty = function () {
  28902. this._isDirty = true;
  28903. };
  28904. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  28905. this._meshesWithPoseMatrix.push(mesh);
  28906. };
  28907. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  28908. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  28909. if (index > -1) {
  28910. this._meshesWithPoseMatrix.splice(index, 1);
  28911. }
  28912. };
  28913. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  28914. for (var index = 0; index < this.bones.length; index++) {
  28915. var bone = this.bones[index];
  28916. var parentBone = bone.getParent();
  28917. if (parentBone) {
  28918. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  28919. }
  28920. else {
  28921. if (initialSkinMatrix) {
  28922. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  28923. }
  28924. else {
  28925. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  28926. }
  28927. }
  28928. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  28929. }
  28930. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  28931. };
  28932. Skeleton.prototype.prepare = function () {
  28933. if (!this._isDirty) {
  28934. return;
  28935. }
  28936. if (this.needInitialSkinMatrix) {
  28937. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  28938. var mesh = this._meshesWithPoseMatrix[index];
  28939. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  28940. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28941. }
  28942. var poseMatrix = mesh.getPoseMatrix();
  28943. // Prepare bones
  28944. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  28945. var bone = this.bones[boneIndex];
  28946. if (!bone.getParent()) {
  28947. var matrix = bone.getBaseMatrix();
  28948. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  28949. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  28950. }
  28951. }
  28952. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  28953. }
  28954. }
  28955. else {
  28956. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  28957. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28958. }
  28959. this._computeTransformMatrices(this._transformMatrices, null);
  28960. }
  28961. this._isDirty = false;
  28962. this._scene._activeBones.addCount(this.bones.length, false);
  28963. };
  28964. Skeleton.prototype.getAnimatables = function () {
  28965. if (!this._animatables || this._animatables.length !== this.bones.length) {
  28966. this._animatables = [];
  28967. for (var index = 0; index < this.bones.length; index++) {
  28968. this._animatables.push(this.bones[index]);
  28969. }
  28970. }
  28971. return this._animatables;
  28972. };
  28973. Skeleton.prototype.clone = function (name, id) {
  28974. var result = new Skeleton(name, id || name, this._scene);
  28975. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28976. for (var index = 0; index < this.bones.length; index++) {
  28977. var source = this.bones[index];
  28978. var parentBone = null;
  28979. if (source.getParent()) {
  28980. var parentIndex = this.bones.indexOf(source.getParent());
  28981. parentBone = result.bones[parentIndex];
  28982. }
  28983. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  28984. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  28985. }
  28986. if (this._ranges) {
  28987. result._ranges = {};
  28988. for (var rangeName in this._ranges) {
  28989. result._ranges[rangeName] = this._ranges[rangeName].clone();
  28990. }
  28991. }
  28992. this._isDirty = true;
  28993. return result;
  28994. };
  28995. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  28996. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  28997. this.bones.forEach(function (bone) {
  28998. bone.animations.forEach(function (animation) {
  28999. animation.enableBlending = true;
  29000. animation.blendingSpeed = blendingSpeed;
  29001. });
  29002. });
  29003. };
  29004. Skeleton.prototype.dispose = function () {
  29005. this._meshesWithPoseMatrix = [];
  29006. // Animations
  29007. this.getScene().stopAnimation(this);
  29008. // Remove from scene
  29009. this.getScene().removeSkeleton(this);
  29010. };
  29011. Skeleton.prototype.serialize = function () {
  29012. var serializationObject = {};
  29013. serializationObject.name = this.name;
  29014. serializationObject.id = this.id;
  29015. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  29016. serializationObject.bones = [];
  29017. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29018. for (var index = 0; index < this.bones.length; index++) {
  29019. var bone = this.bones[index];
  29020. var serializedBone = {
  29021. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  29022. name: bone.name,
  29023. matrix: bone.getLocalMatrix().toArray(),
  29024. rest: bone.getRestPose().toArray()
  29025. };
  29026. serializationObject.bones.push(serializedBone);
  29027. if (bone.length) {
  29028. serializedBone.length = bone.length;
  29029. }
  29030. if (bone.animations && bone.animations.length > 0) {
  29031. serializedBone.animation = bone.animations[0].serialize();
  29032. }
  29033. serializationObject.ranges = [];
  29034. for (var name in this._ranges) {
  29035. var range = {};
  29036. range.name = name;
  29037. range.from = this._ranges[name].from;
  29038. range.to = this._ranges[name].to;
  29039. serializationObject.ranges.push(range);
  29040. }
  29041. }
  29042. return serializationObject;
  29043. };
  29044. Skeleton.Parse = function (parsedSkeleton, scene) {
  29045. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  29046. if (parsedSkeleton.dimensionsAtRest) {
  29047. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  29048. }
  29049. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  29050. var index;
  29051. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  29052. var parsedBone = parsedSkeleton.bones[index];
  29053. var parentBone = null;
  29054. if (parsedBone.parentBoneIndex > -1) {
  29055. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  29056. }
  29057. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  29058. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  29059. if (parsedBone.length) {
  29060. bone.length = parsedBone.length;
  29061. }
  29062. if (parsedBone.animation) {
  29063. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  29064. }
  29065. }
  29066. // placed after bones, so createAnimationRange can cascade down
  29067. if (parsedSkeleton.ranges) {
  29068. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  29069. var data = parsedSkeleton.ranges[index];
  29070. skeleton.createAnimationRange(data.name, data.from, data.to);
  29071. }
  29072. }
  29073. return skeleton;
  29074. };
  29075. return Skeleton;
  29076. })();
  29077. BABYLON.Skeleton = Skeleton;
  29078. })(BABYLON || (BABYLON = {}));
  29079. var BABYLON;
  29080. (function (BABYLON) {
  29081. var PostProcess = (function () {
  29082. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  29083. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  29084. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  29085. this.name = name;
  29086. this.width = -1;
  29087. this.height = -1;
  29088. /*
  29089. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  29090. Can only be used on a single postprocess or on the last one of a chain.
  29091. */
  29092. this.enablePixelPerfectMode = false;
  29093. this._reusable = false;
  29094. this._textures = new BABYLON.SmartArray(2);
  29095. this._currentRenderTextureInd = 0;
  29096. this._scaleRatio = new BABYLON.Vector2(1, 1);
  29097. // Events
  29098. /**
  29099. * An event triggered when the postprocess is activated.
  29100. * @type {BABYLON.Observable}
  29101. */
  29102. this.onActivateObservable = new BABYLON.Observable();
  29103. /**
  29104. * An event triggered when the postprocess changes its size.
  29105. * @type {BABYLON.Observable}
  29106. */
  29107. this.onSizeChangedObservable = new BABYLON.Observable();
  29108. /**
  29109. * An event triggered when the postprocess applies its effect.
  29110. * @type {BABYLON.Observable}
  29111. */
  29112. this.onApplyObservable = new BABYLON.Observable();
  29113. /**
  29114. * An event triggered before rendering the postprocess
  29115. * @type {BABYLON.Observable}
  29116. */
  29117. this.onBeforeRenderObservable = new BABYLON.Observable();
  29118. /**
  29119. * An event triggered after rendering the postprocess
  29120. * @type {BABYLON.Observable}
  29121. */
  29122. this.onAfterRenderObservable = new BABYLON.Observable();
  29123. if (camera != null) {
  29124. this._camera = camera;
  29125. this._scene = camera.getScene();
  29126. camera.attachPostProcess(this);
  29127. this._engine = this._scene.getEngine();
  29128. }
  29129. else {
  29130. this._engine = engine;
  29131. }
  29132. this._options = options;
  29133. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  29134. this._reusable = reusable || false;
  29135. this._textureType = textureType;
  29136. this._samplers = samplers || [];
  29137. this._samplers.push("textureSampler");
  29138. this._fragmentUrl = fragmentUrl;
  29139. this._parameters = parameters || [];
  29140. this._parameters.push("scale");
  29141. this.updateEffect(defines);
  29142. }
  29143. Object.defineProperty(PostProcess.prototype, "onActivate", {
  29144. set: function (callback) {
  29145. if (this._onActivateObserver) {
  29146. this.onActivateObservable.remove(this._onActivateObserver);
  29147. }
  29148. this._onActivateObserver = this.onActivateObservable.add(callback);
  29149. },
  29150. enumerable: true,
  29151. configurable: true
  29152. });
  29153. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  29154. set: function (callback) {
  29155. if (this._onSizeChangedObserver) {
  29156. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  29157. }
  29158. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  29159. },
  29160. enumerable: true,
  29161. configurable: true
  29162. });
  29163. Object.defineProperty(PostProcess.prototype, "onApply", {
  29164. set: function (callback) {
  29165. if (this._onApplyObserver) {
  29166. this.onApplyObservable.remove(this._onApplyObserver);
  29167. }
  29168. this._onApplyObserver = this.onApplyObservable.add(callback);
  29169. },
  29170. enumerable: true,
  29171. configurable: true
  29172. });
  29173. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  29174. set: function (callback) {
  29175. if (this._onBeforeRenderObserver) {
  29176. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29177. }
  29178. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29179. },
  29180. enumerable: true,
  29181. configurable: true
  29182. });
  29183. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  29184. set: function (callback) {
  29185. if (this._onAfterRenderObserver) {
  29186. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29187. }
  29188. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29189. },
  29190. enumerable: true,
  29191. configurable: true
  29192. });
  29193. PostProcess.prototype.updateEffect = function (defines) {
  29194. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  29195. };
  29196. PostProcess.prototype.isReusable = function () {
  29197. return this._reusable;
  29198. };
  29199. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  29200. PostProcess.prototype.markTextureDirty = function () {
  29201. this.width = -1;
  29202. };
  29203. PostProcess.prototype.activate = function (camera, sourceTexture) {
  29204. camera = camera || this._camera;
  29205. var scene = camera.getScene();
  29206. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  29207. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  29208. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  29209. var desiredWidth = this._options.width || requiredWidth;
  29210. var desiredHeight = this._options.height || requiredHeight;
  29211. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  29212. if (!this._options.width) {
  29213. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  29214. }
  29215. if (!this._options.height) {
  29216. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  29217. }
  29218. }
  29219. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  29220. if (this._textures.length > 0) {
  29221. for (var i = 0; i < this._textures.length; i++) {
  29222. this._engine._releaseTexture(this._textures.data[i]);
  29223. }
  29224. this._textures.reset();
  29225. }
  29226. this.width = desiredWidth;
  29227. this.height = desiredHeight;
  29228. var textureSize = { width: this.width, height: this.height };
  29229. var textureOptions = {
  29230. generateMipMaps: false,
  29231. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  29232. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  29233. samplingMode: this.renderTargetSamplingMode,
  29234. type: this._textureType
  29235. };
  29236. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29237. if (this._reusable) {
  29238. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29239. }
  29240. this.onSizeChangedObservable.notifyObservers(this);
  29241. }
  29242. if (this.enablePixelPerfectMode) {
  29243. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  29244. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  29245. }
  29246. else {
  29247. this._scaleRatio.copyFromFloats(1, 1);
  29248. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  29249. }
  29250. this.onActivateObservable.notifyObservers(camera);
  29251. // Clear
  29252. if (this.clearColor) {
  29253. this._engine.clear(this.clearColor, true, true, true);
  29254. }
  29255. else {
  29256. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  29257. }
  29258. if (this._reusable) {
  29259. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  29260. }
  29261. };
  29262. Object.defineProperty(PostProcess.prototype, "isSupported", {
  29263. get: function () {
  29264. return this._effect.isSupported;
  29265. },
  29266. enumerable: true,
  29267. configurable: true
  29268. });
  29269. PostProcess.prototype.apply = function () {
  29270. // Check
  29271. if (!this._effect.isReady())
  29272. return null;
  29273. // States
  29274. this._engine.enableEffect(this._effect);
  29275. this._engine.setState(false);
  29276. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29277. this._engine.setDepthBuffer(false);
  29278. this._engine.setDepthWrite(false);
  29279. // Texture
  29280. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  29281. // Parameters
  29282. this._effect.setVector2("scale", this._scaleRatio);
  29283. this.onApplyObservable.notifyObservers(this._effect);
  29284. return this._effect;
  29285. };
  29286. PostProcess.prototype.dispose = function (camera) {
  29287. camera = camera || this._camera;
  29288. if (this._textures.length > 0) {
  29289. for (var i = 0; i < this._textures.length; i++) {
  29290. this._engine._releaseTexture(this._textures.data[i]);
  29291. }
  29292. this._textures.reset();
  29293. }
  29294. if (!camera) {
  29295. return;
  29296. }
  29297. camera.detachPostProcess(this);
  29298. var index = camera._postProcesses.indexOf(this);
  29299. if (index === 0 && camera._postProcesses.length > 0) {
  29300. this._camera._postProcesses[0].markTextureDirty();
  29301. }
  29302. this.onActivateObservable.clear();
  29303. this.onAfterRenderObservable.clear();
  29304. this.onApplyObservable.clear();
  29305. this.onBeforeRenderObservable.clear();
  29306. this.onSizeChangedObservable.clear();
  29307. };
  29308. return PostProcess;
  29309. })();
  29310. BABYLON.PostProcess = PostProcess;
  29311. })(BABYLON || (BABYLON = {}));
  29312. var BABYLON;
  29313. (function (BABYLON) {
  29314. var PostProcessManager = (function () {
  29315. function PostProcessManager(scene) {
  29316. this._vertexBuffers = {};
  29317. this._scene = scene;
  29318. }
  29319. PostProcessManager.prototype._prepareBuffers = function () {
  29320. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29321. return;
  29322. }
  29323. // VBO
  29324. var vertices = [];
  29325. vertices.push(1, 1);
  29326. vertices.push(-1, 1);
  29327. vertices.push(-1, -1);
  29328. vertices.push(1, -1);
  29329. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29330. // Indices
  29331. var indices = [];
  29332. indices.push(0);
  29333. indices.push(1);
  29334. indices.push(2);
  29335. indices.push(0);
  29336. indices.push(2);
  29337. indices.push(3);
  29338. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29339. };
  29340. // Methods
  29341. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  29342. var postProcesses = this._scene.activeCamera._postProcesses;
  29343. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29344. return false;
  29345. }
  29346. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  29347. return true;
  29348. };
  29349. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29350. var engine = this._scene.getEngine();
  29351. for (var index = 0; index < postProcesses.length; index++) {
  29352. if (index < postProcesses.length - 1) {
  29353. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29354. }
  29355. else {
  29356. if (targetTexture) {
  29357. engine.bindFramebuffer(targetTexture);
  29358. }
  29359. else {
  29360. engine.restoreDefaultFramebuffer();
  29361. }
  29362. }
  29363. var pp = postProcesses[index];
  29364. var effect = pp.apply();
  29365. if (effect) {
  29366. pp.onBeforeRenderObservable.notifyObservers(effect);
  29367. // VBOs
  29368. this._prepareBuffers();
  29369. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29370. // Draw order
  29371. engine.draw(true, 0, 6);
  29372. pp.onAfterRenderObservable.notifyObservers(effect);
  29373. }
  29374. }
  29375. // Restore depth buffer
  29376. engine.setDepthBuffer(true);
  29377. engine.setDepthWrite(true);
  29378. };
  29379. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29380. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29381. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29382. return;
  29383. }
  29384. var engine = this._scene.getEngine();
  29385. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29386. if (index < len - 1) {
  29387. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29388. }
  29389. else {
  29390. if (targetTexture) {
  29391. engine.bindFramebuffer(targetTexture, faceIndex);
  29392. }
  29393. else {
  29394. engine.restoreDefaultFramebuffer();
  29395. }
  29396. }
  29397. if (doNotPresent) {
  29398. break;
  29399. }
  29400. var pp = postProcesses[index];
  29401. var effect = pp.apply();
  29402. if (effect) {
  29403. pp.onBeforeRenderObservable.notifyObservers(effect);
  29404. // VBOs
  29405. this._prepareBuffers();
  29406. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29407. // Draw order
  29408. engine.draw(true, 0, 6);
  29409. pp.onAfterRenderObservable.notifyObservers(effect);
  29410. }
  29411. }
  29412. // Restore depth buffer
  29413. engine.setDepthBuffer(true);
  29414. engine.setDepthWrite(true);
  29415. };
  29416. PostProcessManager.prototype.dispose = function () {
  29417. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29418. if (buffer) {
  29419. buffer.dispose();
  29420. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29421. }
  29422. if (this._indexBuffer) {
  29423. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29424. this._indexBuffer = null;
  29425. }
  29426. };
  29427. return PostProcessManager;
  29428. })();
  29429. BABYLON.PostProcessManager = PostProcessManager;
  29430. })(BABYLON || (BABYLON = {}));
  29431. var BABYLON;
  29432. (function (BABYLON) {
  29433. var PassPostProcess = (function (_super) {
  29434. __extends(PassPostProcess, _super);
  29435. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  29436. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  29437. }
  29438. return PassPostProcess;
  29439. })(BABYLON.PostProcess);
  29440. BABYLON.PassPostProcess = PassPostProcess;
  29441. })(BABYLON || (BABYLON = {}));
  29442. var BABYLON;
  29443. (function (BABYLON) {
  29444. /**
  29445. * This is a holder class for the physics joint created by the physics plugin.
  29446. * It holds a set of functions to control the underlying joint.
  29447. */
  29448. var PhysicsJoint = (function () {
  29449. function PhysicsJoint(type, jointData) {
  29450. this.type = type;
  29451. this.jointData = jointData;
  29452. jointData.nativeParams = jointData.nativeParams || {};
  29453. }
  29454. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  29455. get: function () {
  29456. return this._physicsJoint;
  29457. },
  29458. set: function (newJoint) {
  29459. if (this._physicsJoint) {
  29460. }
  29461. this._physicsJoint = newJoint;
  29462. },
  29463. enumerable: true,
  29464. configurable: true
  29465. });
  29466. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  29467. set: function (physicsPlugin) {
  29468. this._physicsPlugin = physicsPlugin;
  29469. },
  29470. enumerable: true,
  29471. configurable: true
  29472. });
  29473. /**
  29474. * Execute a function that is physics-plugin specific.
  29475. * @param {Function} func the function that will be executed.
  29476. * It accepts two parameters: the physics world and the physics joint.
  29477. */
  29478. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  29479. func(this._physicsPlugin.world, this._physicsJoint);
  29480. };
  29481. //TODO check if the native joints are the same
  29482. //Joint Types
  29483. PhysicsJoint.DistanceJoint = 0;
  29484. PhysicsJoint.HingeJoint = 1;
  29485. PhysicsJoint.BallAndSocketJoint = 2;
  29486. PhysicsJoint.WheelJoint = 3;
  29487. PhysicsJoint.SliderJoint = 4;
  29488. //OIMO
  29489. PhysicsJoint.PrismaticJoint = 5;
  29490. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  29491. PhysicsJoint.UniversalJoint = 6;
  29492. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  29493. //Cannon
  29494. //Similar to a Ball-Joint. Different in params
  29495. PhysicsJoint.PointToPointJoint = 8;
  29496. //Cannon only at the moment
  29497. PhysicsJoint.SpringJoint = 9;
  29498. PhysicsJoint.LockJoint = 10;
  29499. return PhysicsJoint;
  29500. })();
  29501. BABYLON.PhysicsJoint = PhysicsJoint;
  29502. /**
  29503. * A class representing a physics distance joint.
  29504. */
  29505. var DistanceJoint = (function (_super) {
  29506. __extends(DistanceJoint, _super);
  29507. function DistanceJoint(jointData) {
  29508. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  29509. }
  29510. /**
  29511. * Update the predefined distance.
  29512. */
  29513. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  29514. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  29515. };
  29516. return DistanceJoint;
  29517. })(PhysicsJoint);
  29518. BABYLON.DistanceJoint = DistanceJoint;
  29519. var MotorEnabledJoint = (function (_super) {
  29520. __extends(MotorEnabledJoint, _super);
  29521. function MotorEnabledJoint(type, jointData) {
  29522. _super.call(this, type, jointData);
  29523. }
  29524. /**
  29525. * Set the motor values.
  29526. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29527. * @param {number} force the force to apply
  29528. * @param {number} maxForce max force for this motor.
  29529. */
  29530. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  29531. this._physicsPlugin.setMotor(this, force, maxForce);
  29532. };
  29533. /**
  29534. * Set the motor's limits.
  29535. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29536. */
  29537. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29538. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29539. };
  29540. return MotorEnabledJoint;
  29541. })(PhysicsJoint);
  29542. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  29543. /**
  29544. * This class represents a single hinge physics joint
  29545. */
  29546. var HingeJoint = (function (_super) {
  29547. __extends(HingeJoint, _super);
  29548. function HingeJoint(jointData) {
  29549. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  29550. }
  29551. /**
  29552. * Set the motor values.
  29553. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29554. * @param {number} force the force to apply
  29555. * @param {number} maxForce max force for this motor.
  29556. */
  29557. HingeJoint.prototype.setMotor = function (force, maxForce) {
  29558. this._physicsPlugin.setMotor(this, force, maxForce);
  29559. };
  29560. /**
  29561. * Set the motor's limits.
  29562. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29563. */
  29564. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29565. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29566. };
  29567. return HingeJoint;
  29568. })(MotorEnabledJoint);
  29569. BABYLON.HingeJoint = HingeJoint;
  29570. /**
  29571. * This class represents a dual hinge physics joint (same as wheel joint)
  29572. */
  29573. var Hinge2Joint = (function (_super) {
  29574. __extends(Hinge2Joint, _super);
  29575. function Hinge2Joint(jointData) {
  29576. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  29577. }
  29578. /**
  29579. * Set the motor values.
  29580. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29581. * @param {number} force the force to apply
  29582. * @param {number} maxForce max force for this motor.
  29583. * @param {motorIndex} the motor's index, 0 or 1.
  29584. */
  29585. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  29586. if (motorIndex === void 0) { motorIndex = 0; }
  29587. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  29588. };
  29589. /**
  29590. * Set the motor limits.
  29591. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29592. * @param {number} upperLimit the upper limit
  29593. * @param {number} lowerLimit lower limit
  29594. * @param {motorIndex} the motor's index, 0 or 1.
  29595. */
  29596. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  29597. if (motorIndex === void 0) { motorIndex = 0; }
  29598. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  29599. };
  29600. return Hinge2Joint;
  29601. })(MotorEnabledJoint);
  29602. BABYLON.Hinge2Joint = Hinge2Joint;
  29603. })(BABYLON || (BABYLON = {}));
  29604. var BABYLON;
  29605. (function (BABYLON) {
  29606. var PhysicsImpostor = (function () {
  29607. function PhysicsImpostor(object, type, _options, _scene) {
  29608. var _this = this;
  29609. if (_options === void 0) { _options = { mass: 0 }; }
  29610. this.object = object;
  29611. this.type = type;
  29612. this._options = _options;
  29613. this._scene = _scene;
  29614. this._bodyUpdateRequired = false;
  29615. this._onBeforePhysicsStepCallbacks = new Array();
  29616. this._onAfterPhysicsStepCallbacks = new Array();
  29617. this._onPhysicsCollideCallbacks = [];
  29618. this._deltaPosition = BABYLON.Vector3.Zero();
  29619. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  29620. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  29621. /**
  29622. * this function is executed by the physics engine.
  29623. */
  29624. this.beforeStep = function () {
  29625. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  29626. //conjugate deltaRotation
  29627. if (_this._deltaRotationConjugated) {
  29628. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  29629. }
  29630. else {
  29631. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  29632. }
  29633. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  29634. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  29635. func(_this);
  29636. });
  29637. };
  29638. /**
  29639. * this function is executed by the physics engine.
  29640. */
  29641. this.afterStep = function () {
  29642. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  29643. func(_this);
  29644. });
  29645. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  29646. _this.object.position.addInPlace(_this._deltaPosition);
  29647. if (_this._deltaRotation) {
  29648. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  29649. }
  29650. };
  29651. //event and body object due to cannon's event-based architecture.
  29652. this.onCollide = function (e) {
  29653. if (!_this._onPhysicsCollideCallbacks.length)
  29654. return;
  29655. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  29656. if (otherImpostor) {
  29657. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  29658. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  29659. }).forEach(function (obj) {
  29660. obj.callback(_this, otherImpostor);
  29661. });
  29662. }
  29663. };
  29664. //sanity check!
  29665. if (!this.object) {
  29666. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  29667. return;
  29668. }
  29669. //legacy support for old syntax.
  29670. if (!this._scene && object.getScene) {
  29671. this._scene = object.getScene();
  29672. }
  29673. this._physicsEngine = this._scene.getPhysicsEngine();
  29674. if (!this._physicsEngine) {
  29675. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  29676. }
  29677. else {
  29678. //set the object's quaternion, if not set
  29679. if (!this.object.rotationQuaternion) {
  29680. if (this.object.rotation) {
  29681. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  29682. }
  29683. else {
  29684. this.object.rotationQuaternion = new BABYLON.Quaternion();
  29685. }
  29686. }
  29687. //default options params
  29688. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  29689. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  29690. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  29691. this._joints = [];
  29692. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  29693. if (!this.object.parent) {
  29694. this._init();
  29695. }
  29696. }
  29697. }
  29698. /**
  29699. * This function will completly initialize this impostor.
  29700. * It will create a new body - but only if this mesh has no parent.
  29701. * If it has, this impostor will not be used other than to define the impostor
  29702. * of the child mesh.
  29703. */
  29704. PhysicsImpostor.prototype._init = function () {
  29705. this._physicsEngine.removeImpostor(this);
  29706. this.physicsBody = null;
  29707. this._parent = this._parent || this._getPhysicsParent();
  29708. if (!this.parent) {
  29709. this._physicsEngine.addImpostor(this);
  29710. }
  29711. };
  29712. PhysicsImpostor.prototype._getPhysicsParent = function () {
  29713. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  29714. var parentMesh = this.object.parent;
  29715. return parentMesh.physicsImpostor;
  29716. }
  29717. return;
  29718. };
  29719. /**
  29720. * Should a new body be generated.
  29721. */
  29722. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  29723. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  29724. };
  29725. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  29726. this.forceUpdate();
  29727. };
  29728. /**
  29729. * Force a regeneration of this or the parent's impostor's body.
  29730. * Use under cautious - This will remove all joints already implemented.
  29731. */
  29732. PhysicsImpostor.prototype.forceUpdate = function () {
  29733. this._init();
  29734. if (this.parent) {
  29735. this.parent.forceUpdate();
  29736. }
  29737. };
  29738. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  29739. /*public get mesh(): AbstractMesh {
  29740. return this._mesh;
  29741. }*/
  29742. /**
  29743. * Gets the body that holds this impostor. Either its own, or its parent.
  29744. */
  29745. get: function () {
  29746. return this._parent ? this._parent.physicsBody : this._physicsBody;
  29747. },
  29748. /**
  29749. * Set the physics body. Used mainly by the physics engine/plugin
  29750. */
  29751. set: function (physicsBody) {
  29752. if (this._physicsBody) {
  29753. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  29754. }
  29755. this._physicsBody = physicsBody;
  29756. this.resetUpdateFlags();
  29757. },
  29758. enumerable: true,
  29759. configurable: true
  29760. });
  29761. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  29762. get: function () {
  29763. return this._parent;
  29764. },
  29765. enumerable: true,
  29766. configurable: true
  29767. });
  29768. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  29769. this._bodyUpdateRequired = false;
  29770. };
  29771. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  29772. if (this.object.getBoundingInfo) {
  29773. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  29774. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  29775. }
  29776. else {
  29777. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  29778. }
  29779. };
  29780. PhysicsImpostor.prototype.getObjectCenter = function () {
  29781. if (this.object.getBoundingInfo) {
  29782. return this.object.getBoundingInfo().boundingBox.center;
  29783. }
  29784. else {
  29785. return this.object.position;
  29786. }
  29787. };
  29788. /**
  29789. * Get a specific parametes from the options parameter.
  29790. */
  29791. PhysicsImpostor.prototype.getParam = function (paramName) {
  29792. return this._options[paramName];
  29793. };
  29794. /**
  29795. * Sets a specific parameter in the options given to the physics plugin
  29796. */
  29797. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  29798. this._options[paramName] = value;
  29799. this._bodyUpdateRequired = true;
  29800. };
  29801. /**
  29802. * Specifically change the body's mass option. Won't recreate the physics body object
  29803. */
  29804. PhysicsImpostor.prototype.setMass = function (mass) {
  29805. if (this.getParam("mass") !== mass) {
  29806. this.setParam("mass", mass);
  29807. }
  29808. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  29809. };
  29810. PhysicsImpostor.prototype.getLinearVelocity = function () {
  29811. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  29812. };
  29813. /**
  29814. * Set the body's linear velocity.
  29815. */
  29816. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  29817. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  29818. };
  29819. PhysicsImpostor.prototype.getAngularVelocity = function () {
  29820. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  29821. };
  29822. /**
  29823. * Set the body's linear velocity.
  29824. */
  29825. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  29826. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  29827. };
  29828. /**
  29829. * Execute a function with the physics plugin native code.
  29830. * Provide a function the will have two variables - the world object and the physics body object.
  29831. */
  29832. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  29833. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  29834. };
  29835. /**
  29836. * Register a function that will be executed before the physics world is stepping forward.
  29837. */
  29838. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  29839. this._onBeforePhysicsStepCallbacks.push(func);
  29840. };
  29841. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  29842. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  29843. if (index > -1) {
  29844. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  29845. }
  29846. else {
  29847. BABYLON.Tools.Warn("Function to remove was not found");
  29848. }
  29849. };
  29850. /**
  29851. * Register a function that will be executed after the physics step
  29852. */
  29853. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  29854. this._onAfterPhysicsStepCallbacks.push(func);
  29855. };
  29856. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  29857. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  29858. if (index > -1) {
  29859. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  29860. }
  29861. else {
  29862. BABYLON.Tools.Warn("Function to remove was not found");
  29863. }
  29864. };
  29865. /**
  29866. * register a function that will be executed when this impostor collides against a different body.
  29867. */
  29868. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  29869. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29870. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  29871. };
  29872. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  29873. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29874. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  29875. if (index > -1) {
  29876. this._onPhysicsCollideCallbacks.splice(index, 1);
  29877. }
  29878. else {
  29879. BABYLON.Tools.Warn("Function to remove was not found");
  29880. }
  29881. };
  29882. /**
  29883. * Apply a force
  29884. */
  29885. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  29886. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  29887. };
  29888. /**
  29889. * Apply an impulse
  29890. */
  29891. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  29892. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  29893. };
  29894. /**
  29895. * A help function to create a joint.
  29896. */
  29897. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  29898. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  29899. this.addJoint(otherImpostor, joint);
  29900. };
  29901. /**
  29902. * Add a joint to this impostor with a different impostor.
  29903. */
  29904. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  29905. this._joints.push({
  29906. otherImpostor: otherImpostor,
  29907. joint: joint
  29908. });
  29909. this._physicsEngine.addJoint(this, otherImpostor, joint);
  29910. };
  29911. /**
  29912. * Will keep this body still, in a sleep mode.
  29913. */
  29914. PhysicsImpostor.prototype.sleep = function () {
  29915. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  29916. };
  29917. /**
  29918. * Wake the body up.
  29919. */
  29920. PhysicsImpostor.prototype.wakeUp = function () {
  29921. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  29922. };
  29923. PhysicsImpostor.prototype.clone = function (newObject) {
  29924. if (!newObject)
  29925. return null;
  29926. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  29927. };
  29928. PhysicsImpostor.prototype.dispose = function () {
  29929. var _this = this;
  29930. //no dispose if no physics engine is available.
  29931. if (!this._physicsEngine) {
  29932. return;
  29933. }
  29934. this._joints.forEach(function (j) {
  29935. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  29936. });
  29937. //dispose the physics body
  29938. this._physicsEngine.removeImpostor(this);
  29939. if (this.parent) {
  29940. this.parent.forceUpdate();
  29941. }
  29942. else {
  29943. }
  29944. };
  29945. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  29946. this._deltaPosition.copyFrom(position);
  29947. };
  29948. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  29949. if (!this._deltaRotation) {
  29950. this._deltaRotation = new BABYLON.Quaternion();
  29951. }
  29952. this._deltaRotation.copyFrom(rotation);
  29953. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  29954. };
  29955. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  29956. //Impostor types
  29957. PhysicsImpostor.NoImpostor = 0;
  29958. PhysicsImpostor.SphereImpostor = 1;
  29959. PhysicsImpostor.BoxImpostor = 2;
  29960. PhysicsImpostor.PlaneImpostor = 3;
  29961. PhysicsImpostor.MeshImpostor = 4;
  29962. PhysicsImpostor.CylinderImpostor = 7;
  29963. PhysicsImpostor.ParticleImpostor = 8;
  29964. PhysicsImpostor.HeightmapImpostor = 9;
  29965. return PhysicsImpostor;
  29966. })();
  29967. BABYLON.PhysicsImpostor = PhysicsImpostor;
  29968. })(BABYLON || (BABYLON = {}));
  29969. var BABYLON;
  29970. (function (BABYLON) {
  29971. var PhysicsEngine = (function () {
  29972. function PhysicsEngine(gravity, _physicsPlugin) {
  29973. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  29974. this._physicsPlugin = _physicsPlugin;
  29975. //new methods and parameters
  29976. this._impostors = [];
  29977. this._joints = [];
  29978. if (!this._physicsPlugin.isSupported()) {
  29979. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  29980. + "Please make sure it is included.");
  29981. }
  29982. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  29983. this.setGravity(gravity);
  29984. this.setTimeStep();
  29985. }
  29986. PhysicsEngine.prototype.setGravity = function (gravity) {
  29987. this.gravity = gravity;
  29988. this._physicsPlugin.setGravity(this.gravity);
  29989. };
  29990. /**
  29991. * Set the time step of the physics engine.
  29992. * default is 1/60.
  29993. * To slow it down, enter 1/600 for example.
  29994. * To speed it up, 1/30
  29995. * @param {number} newTimeStep the new timestep to apply to this world.
  29996. */
  29997. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  29998. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  29999. this._physicsPlugin.setTimeStep(newTimeStep);
  30000. };
  30001. PhysicsEngine.prototype.dispose = function () {
  30002. this._impostors.forEach(function (impostor) {
  30003. impostor.dispose();
  30004. });
  30005. this._physicsPlugin.dispose();
  30006. };
  30007. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  30008. return this._physicsPlugin.name;
  30009. };
  30010. /**
  30011. * Adding a new impostor for the impostor tracking.
  30012. * This will be done by the impostor itself.
  30013. * @param {PhysicsImpostor} impostor the impostor to add
  30014. */
  30015. PhysicsEngine.prototype.addImpostor = function (impostor) {
  30016. impostor.uniqueId = this._impostors.push(impostor);
  30017. //if no parent, generate the body
  30018. if (!impostor.parent) {
  30019. this._physicsPlugin.generatePhysicsBody(impostor);
  30020. }
  30021. };
  30022. /**
  30023. * Remove an impostor from the engine.
  30024. * This impostor and its mesh will not longer be updated by the physics engine.
  30025. * @param {PhysicsImpostor} impostor the impostor to remove
  30026. */
  30027. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  30028. var index = this._impostors.indexOf(impostor);
  30029. if (index > -1) {
  30030. var removed = this._impostors.splice(index, 1);
  30031. //Is it needed?
  30032. if (removed.length) {
  30033. //this will also remove it from the world.
  30034. removed[0].physicsBody = null;
  30035. }
  30036. }
  30037. };
  30038. /**
  30039. * Add a joint to the physics engine
  30040. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  30041. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  30042. * @param {PhysicsJoint} the joint that will connect both impostors.
  30043. */
  30044. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  30045. var impostorJoint = {
  30046. mainImpostor: mainImpostor,
  30047. connectedImpostor: connectedImpostor,
  30048. joint: joint
  30049. };
  30050. joint.physicsPlugin = this._physicsPlugin;
  30051. this._joints.push(impostorJoint);
  30052. this._physicsPlugin.generateJoint(impostorJoint);
  30053. };
  30054. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  30055. var matchingJoints = this._joints.filter(function (impostorJoint) {
  30056. return (impostorJoint.connectedImpostor === connectedImpostor
  30057. && impostorJoint.joint === joint
  30058. && impostorJoint.mainImpostor === mainImpostor);
  30059. });
  30060. if (matchingJoints.length) {
  30061. this._physicsPlugin.removeJoint(matchingJoints[0]);
  30062. }
  30063. };
  30064. /**
  30065. * Called by the scene. no need to call it.
  30066. */
  30067. PhysicsEngine.prototype._step = function (delta) {
  30068. var _this = this;
  30069. //check if any mesh has no body / requires an update
  30070. this._impostors.forEach(function (impostor) {
  30071. if (impostor.isBodyInitRequired()) {
  30072. _this._physicsPlugin.generatePhysicsBody(impostor);
  30073. }
  30074. });
  30075. if (delta > 0.1) {
  30076. delta = 0.1;
  30077. }
  30078. else if (delta <= 0) {
  30079. delta = 1.0 / 60.0;
  30080. }
  30081. this._physicsPlugin.executeStep(delta, this._impostors);
  30082. };
  30083. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  30084. return this._physicsPlugin;
  30085. };
  30086. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  30087. for (var i = 0; i < this._impostors.length; ++i) {
  30088. if (this._impostors[i].object === object) {
  30089. return this._impostors[i];
  30090. }
  30091. }
  30092. };
  30093. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  30094. for (var i = 0; i < this._impostors.length; ++i) {
  30095. if (this._impostors[i].physicsBody === body) {
  30096. return this._impostors[i];
  30097. }
  30098. }
  30099. };
  30100. // Statics, Legacy support.
  30101. /**
  30102. * @Deprecated
  30103. *
  30104. */
  30105. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  30106. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  30107. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  30108. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  30109. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  30110. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  30111. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  30112. PhysicsEngine.CapsuleImpostor = -1;
  30113. PhysicsEngine.ConeImpostor = -1;
  30114. PhysicsEngine.ConvexHullImpostor = -1;
  30115. PhysicsEngine.Epsilon = 0.001;
  30116. return PhysicsEngine;
  30117. })();
  30118. BABYLON.PhysicsEngine = PhysicsEngine;
  30119. })(BABYLON || (BABYLON = {}));
  30120. var BABYLON;
  30121. (function (BABYLON) {
  30122. var VertexData = (function () {
  30123. function VertexData() {
  30124. }
  30125. VertexData.prototype.set = function (data, kind) {
  30126. switch (kind) {
  30127. case BABYLON.VertexBuffer.PositionKind:
  30128. this.positions = data;
  30129. break;
  30130. case BABYLON.VertexBuffer.NormalKind:
  30131. this.normals = data;
  30132. break;
  30133. case BABYLON.VertexBuffer.UVKind:
  30134. this.uvs = data;
  30135. break;
  30136. case BABYLON.VertexBuffer.UV2Kind:
  30137. this.uvs2 = data;
  30138. break;
  30139. case BABYLON.VertexBuffer.UV3Kind:
  30140. this.uvs3 = data;
  30141. break;
  30142. case BABYLON.VertexBuffer.UV4Kind:
  30143. this.uvs4 = data;
  30144. break;
  30145. case BABYLON.VertexBuffer.UV5Kind:
  30146. this.uvs5 = data;
  30147. break;
  30148. case BABYLON.VertexBuffer.UV6Kind:
  30149. this.uvs6 = data;
  30150. break;
  30151. case BABYLON.VertexBuffer.ColorKind:
  30152. this.colors = data;
  30153. break;
  30154. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30155. this.matricesIndices = data;
  30156. break;
  30157. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30158. this.matricesWeights = data;
  30159. break;
  30160. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30161. this.matricesIndicesExtra = data;
  30162. break;
  30163. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30164. this.matricesWeightsExtra = data;
  30165. break;
  30166. }
  30167. };
  30168. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30169. this._applyTo(mesh, updatable);
  30170. };
  30171. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30172. this._applyTo(geometry, updatable);
  30173. };
  30174. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30175. this._update(mesh);
  30176. };
  30177. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30178. this._update(geometry);
  30179. };
  30180. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30181. if (this.positions) {
  30182. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30183. }
  30184. if (this.normals) {
  30185. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30186. }
  30187. if (this.uvs) {
  30188. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30189. }
  30190. if (this.uvs2) {
  30191. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30192. }
  30193. if (this.uvs3) {
  30194. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30195. }
  30196. if (this.uvs4) {
  30197. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30198. }
  30199. if (this.uvs5) {
  30200. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30201. }
  30202. if (this.uvs6) {
  30203. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30204. }
  30205. if (this.colors) {
  30206. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30207. }
  30208. if (this.matricesIndices) {
  30209. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30210. }
  30211. if (this.matricesWeights) {
  30212. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30213. }
  30214. if (this.matricesIndicesExtra) {
  30215. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30216. }
  30217. if (this.matricesWeightsExtra) {
  30218. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30219. }
  30220. if (this.indices) {
  30221. meshOrGeometry.setIndices(this.indices);
  30222. }
  30223. };
  30224. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30225. if (this.positions) {
  30226. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30227. }
  30228. if (this.normals) {
  30229. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30230. }
  30231. if (this.uvs) {
  30232. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30233. }
  30234. if (this.uvs2) {
  30235. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30236. }
  30237. if (this.uvs3) {
  30238. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30239. }
  30240. if (this.uvs4) {
  30241. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30242. }
  30243. if (this.uvs5) {
  30244. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30245. }
  30246. if (this.uvs6) {
  30247. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30248. }
  30249. if (this.colors) {
  30250. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30251. }
  30252. if (this.matricesIndices) {
  30253. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30254. }
  30255. if (this.matricesWeights) {
  30256. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30257. }
  30258. if (this.matricesIndicesExtra) {
  30259. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30260. }
  30261. if (this.matricesWeightsExtra) {
  30262. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30263. }
  30264. if (this.indices) {
  30265. meshOrGeometry.setIndices(this.indices);
  30266. }
  30267. };
  30268. VertexData.prototype.transform = function (matrix) {
  30269. var transformed = BABYLON.Vector3.Zero();
  30270. var index;
  30271. if (this.positions) {
  30272. var position = BABYLON.Vector3.Zero();
  30273. for (index = 0; index < this.positions.length; index += 3) {
  30274. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30275. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30276. this.positions[index] = transformed.x;
  30277. this.positions[index + 1] = transformed.y;
  30278. this.positions[index + 2] = transformed.z;
  30279. }
  30280. }
  30281. if (this.normals) {
  30282. var normal = BABYLON.Vector3.Zero();
  30283. for (index = 0; index < this.normals.length; index += 3) {
  30284. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30285. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30286. this.normals[index] = transformed.x;
  30287. this.normals[index + 1] = transformed.y;
  30288. this.normals[index + 2] = transformed.z;
  30289. }
  30290. }
  30291. };
  30292. VertexData.prototype.merge = function (other) {
  30293. if (other.indices) {
  30294. if (!this.indices) {
  30295. this.indices = [];
  30296. }
  30297. var offset = this.positions ? this.positions.length / 3 : 0;
  30298. for (var index = 0; index < other.indices.length; index++) {
  30299. //TODO check type - if Int32Array!
  30300. this.indices.push(other.indices[index] + offset);
  30301. }
  30302. }
  30303. this.positions = this._mergeElement(this.positions, other.positions);
  30304. this.normals = this._mergeElement(this.normals, other.normals);
  30305. this.uvs = this._mergeElement(this.uvs, other.uvs);
  30306. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  30307. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  30308. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  30309. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  30310. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  30311. this.colors = this._mergeElement(this.colors, other.colors);
  30312. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  30313. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  30314. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  30315. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  30316. };
  30317. VertexData.prototype._mergeElement = function (source, other) {
  30318. if (!other)
  30319. return source;
  30320. if (!source)
  30321. return other;
  30322. var len = other.length + source.length;
  30323. var isSrcTypedArray = source instanceof Float32Array;
  30324. var isOthTypedArray = other instanceof Float32Array;
  30325. // use non-loop method when the source is Float32Array
  30326. if (isSrcTypedArray) {
  30327. var ret32 = new Float32Array(len);
  30328. ret32.set(source);
  30329. ret32.set(other, source.length);
  30330. return ret32;
  30331. }
  30332. else if (!isOthTypedArray) {
  30333. return source.concat(other);
  30334. }
  30335. else {
  30336. var ret = source.slice(0); // copy source to a separate array
  30337. for (var i = 0, len = other.length; i < len; i++) {
  30338. ret.push(other[i]);
  30339. }
  30340. return ret;
  30341. }
  30342. };
  30343. VertexData.prototype.serialize = function () {
  30344. var serializationObject = this.serialize();
  30345. if (this.positions) {
  30346. serializationObject.positions = this.positions;
  30347. }
  30348. if (this.normals) {
  30349. serializationObject.normals = this.normals;
  30350. }
  30351. if (this.uvs) {
  30352. serializationObject.uvs = this.uvs;
  30353. }
  30354. if (this.uvs2) {
  30355. serializationObject.uvs2 = this.uvs2;
  30356. }
  30357. if (this.uvs3) {
  30358. serializationObject.uvs3 = this.uvs3;
  30359. }
  30360. if (this.uvs4) {
  30361. serializationObject.uvs4 = this.uvs4;
  30362. }
  30363. if (this.uvs5) {
  30364. serializationObject.uvs5 = this.uvs5;
  30365. }
  30366. if (this.uvs6) {
  30367. serializationObject.uvs6 = this.uvs6;
  30368. }
  30369. if (this.colors) {
  30370. serializationObject.colors = this.colors;
  30371. }
  30372. if (this.matricesIndices) {
  30373. serializationObject.matricesIndices = this.matricesIndices;
  30374. serializationObject.matricesIndices._isExpanded = true;
  30375. }
  30376. if (this.matricesWeights) {
  30377. serializationObject.matricesWeights = this.matricesWeights;
  30378. }
  30379. if (this.matricesIndicesExtra) {
  30380. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30381. serializationObject.matricesIndicesExtra._isExpanded = true;
  30382. }
  30383. if (this.matricesWeightsExtra) {
  30384. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30385. }
  30386. serializationObject.indices = this.indices;
  30387. return serializationObject;
  30388. };
  30389. // Statics
  30390. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  30391. return VertexData._ExtractFrom(mesh, copyWhenShared);
  30392. };
  30393. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  30394. return VertexData._ExtractFrom(geometry, copyWhenShared);
  30395. };
  30396. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  30397. var result = new VertexData();
  30398. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30399. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  30400. }
  30401. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30402. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  30403. }
  30404. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30405. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  30406. }
  30407. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30408. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  30409. }
  30410. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30411. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  30412. }
  30413. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30414. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  30415. }
  30416. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30417. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  30418. }
  30419. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30420. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  30421. }
  30422. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30423. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  30424. }
  30425. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30426. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  30427. }
  30428. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30429. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  30430. }
  30431. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30432. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  30433. }
  30434. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30435. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  30436. }
  30437. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30438. return result;
  30439. };
  30440. VertexData.CreateRibbon = function (options) {
  30441. var pathArray = options.pathArray;
  30442. var closeArray = options.closeArray || false;
  30443. var closePath = options.closePath || false;
  30444. var invertUV = options.invertUV || false;
  30445. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30446. var offset = options.offset || defaultOffset;
  30447. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30448. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30449. var positions = [];
  30450. var indices = [];
  30451. var normals = [];
  30452. var uvs = [];
  30453. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30454. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30455. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30456. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30457. var minlg; // minimal length among all paths from pathArray
  30458. var lg = []; // array of path lengths : nb of vertex per path
  30459. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30460. var p; // path iterator
  30461. var i; // point iterator
  30462. var j; // point iterator
  30463. // if single path in pathArray
  30464. if (pathArray.length < 2) {
  30465. var ar1 = [];
  30466. var ar2 = [];
  30467. for (i = 0; i < pathArray[0].length - offset; i++) {
  30468. ar1.push(pathArray[0][i]);
  30469. ar2.push(pathArray[0][i + offset]);
  30470. }
  30471. pathArray = [ar1, ar2];
  30472. }
  30473. // positions and horizontal distances (u)
  30474. var idc = 0;
  30475. var closePathCorr = (closePath) ? 1 : 0;
  30476. var path;
  30477. var l;
  30478. minlg = pathArray[0].length;
  30479. var vectlg;
  30480. var dist;
  30481. for (p = 0; p < pathArray.length; p++) {
  30482. uTotalDistance[p] = 0;
  30483. us[p] = [0];
  30484. path = pathArray[p];
  30485. l = path.length;
  30486. minlg = (minlg < l) ? minlg : l;
  30487. j = 0;
  30488. while (j < l) {
  30489. positions.push(path[j].x, path[j].y, path[j].z);
  30490. if (j > 0) {
  30491. vectlg = path[j].subtract(path[j - 1]).length();
  30492. dist = vectlg + uTotalDistance[p];
  30493. us[p].push(dist);
  30494. uTotalDistance[p] = dist;
  30495. }
  30496. j++;
  30497. }
  30498. if (closePath) {
  30499. j--;
  30500. positions.push(path[0].x, path[0].y, path[0].z);
  30501. vectlg = path[j].subtract(path[0]).length();
  30502. dist = vectlg + uTotalDistance[p];
  30503. us[p].push(dist);
  30504. uTotalDistance[p] = dist;
  30505. }
  30506. lg[p] = l + closePathCorr;
  30507. idx[p] = idc;
  30508. idc += (l + closePathCorr);
  30509. }
  30510. // vertical distances (v)
  30511. var path1;
  30512. var path2;
  30513. var vertex1;
  30514. var vertex2;
  30515. for (i = 0; i < minlg + closePathCorr; i++) {
  30516. vTotalDistance[i] = 0;
  30517. vs[i] = [0];
  30518. for (p = 0; p < pathArray.length - 1; p++) {
  30519. path1 = pathArray[p];
  30520. path2 = pathArray[p + 1];
  30521. if (i === minlg) {
  30522. vertex1 = path1[0];
  30523. vertex2 = path2[0];
  30524. }
  30525. else {
  30526. vertex1 = path1[i];
  30527. vertex2 = path2[i];
  30528. }
  30529. vectlg = vertex2.subtract(vertex1).length();
  30530. dist = vectlg + vTotalDistance[i];
  30531. vs[i].push(dist);
  30532. vTotalDistance[i] = dist;
  30533. }
  30534. if (closeArray) {
  30535. path1 = pathArray[p];
  30536. path2 = pathArray[0];
  30537. if (i === minlg) {
  30538. vertex2 = path2[0];
  30539. }
  30540. vectlg = vertex2.subtract(vertex1).length();
  30541. dist = vectlg + vTotalDistance[i];
  30542. vTotalDistance[i] = dist;
  30543. }
  30544. }
  30545. // uvs
  30546. var u;
  30547. var v;
  30548. for (p = 0; p < pathArray.length; p++) {
  30549. for (i = 0; i < minlg + closePathCorr; i++) {
  30550. u = us[p][i] / uTotalDistance[p];
  30551. v = vs[i][p] / vTotalDistance[i];
  30552. if (invertUV) {
  30553. uvs.push(v, u);
  30554. }
  30555. else {
  30556. uvs.push(u, v);
  30557. }
  30558. }
  30559. }
  30560. // indices
  30561. p = 0; // path index
  30562. var pi = 0; // positions array index
  30563. var l1 = lg[p] - 1; // path1 length
  30564. var l2 = lg[p + 1] - 1; // path2 length
  30565. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30566. var shft = idx[1] - idx[0]; // shift
  30567. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30568. while (pi <= min && p < path1nb) {
  30569. // 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
  30570. indices.push(pi, pi + shft, pi + 1);
  30571. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30572. pi += 1;
  30573. if (pi === min) {
  30574. p++;
  30575. if (p === lg.length - 1) {
  30576. shft = idx[0] - idx[p];
  30577. l1 = lg[p] - 1;
  30578. l2 = lg[0] - 1;
  30579. }
  30580. else {
  30581. shft = idx[p + 1] - idx[p];
  30582. l1 = lg[p] - 1;
  30583. l2 = lg[p + 1] - 1;
  30584. }
  30585. pi = idx[p];
  30586. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30587. }
  30588. }
  30589. // normals
  30590. VertexData.ComputeNormals(positions, indices, normals);
  30591. if (closePath) {
  30592. var indexFirst = 0;
  30593. var indexLast = 0;
  30594. for (p = 0; p < pathArray.length; p++) {
  30595. indexFirst = idx[p] * 3;
  30596. if (p + 1 < pathArray.length) {
  30597. indexLast = (idx[p + 1] - 1) * 3;
  30598. }
  30599. else {
  30600. indexLast = normals.length - 3;
  30601. }
  30602. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30603. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30604. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30605. normals[indexLast] = normals[indexFirst];
  30606. normals[indexLast + 1] = normals[indexFirst + 1];
  30607. normals[indexLast + 2] = normals[indexFirst + 2];
  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. if (closePath) {
  30619. vertexData._idx = idx;
  30620. }
  30621. return vertexData;
  30622. };
  30623. VertexData.CreateBox = function (options) {
  30624. var normalsSource = [
  30625. new BABYLON.Vector3(0, 0, 1),
  30626. new BABYLON.Vector3(0, 0, -1),
  30627. new BABYLON.Vector3(1, 0, 0),
  30628. new BABYLON.Vector3(-1, 0, 0),
  30629. new BABYLON.Vector3(0, 1, 0),
  30630. new BABYLON.Vector3(0, -1, 0)
  30631. ];
  30632. var indices = [];
  30633. var positions = [];
  30634. var normals = [];
  30635. var uvs = [];
  30636. var width = options.width || options.size || 1;
  30637. var height = options.height || options.size || 1;
  30638. var depth = options.depth || options.size || 1;
  30639. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30640. var faceUV = options.faceUV || new Array(6);
  30641. var faceColors = options.faceColors;
  30642. var colors = [];
  30643. // default face colors and UV if undefined
  30644. for (var f = 0; f < 6; f++) {
  30645. if (faceUV[f] === undefined) {
  30646. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30647. }
  30648. if (faceColors && faceColors[f] === undefined) {
  30649. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30650. }
  30651. }
  30652. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30653. // Create each face in turn.
  30654. for (var index = 0; index < normalsSource.length; index++) {
  30655. var normal = normalsSource[index];
  30656. // Get two vectors perpendicular to the face normal and to each other.
  30657. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30658. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30659. // Six indices (two triangles) per face.
  30660. var verticesLength = positions.length / 3;
  30661. indices.push(verticesLength);
  30662. indices.push(verticesLength + 1);
  30663. indices.push(verticesLength + 2);
  30664. indices.push(verticesLength);
  30665. indices.push(verticesLength + 2);
  30666. indices.push(verticesLength + 3);
  30667. // Four vertices per face.
  30668. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30669. positions.push(vertex.x, vertex.y, vertex.z);
  30670. normals.push(normal.x, normal.y, normal.z);
  30671. uvs.push(faceUV[index].z, faceUV[index].w);
  30672. if (faceColors) {
  30673. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30674. }
  30675. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30676. positions.push(vertex.x, vertex.y, vertex.z);
  30677. normals.push(normal.x, normal.y, normal.z);
  30678. uvs.push(faceUV[index].x, faceUV[index].w);
  30679. if (faceColors) {
  30680. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30681. }
  30682. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30683. positions.push(vertex.x, vertex.y, vertex.z);
  30684. normals.push(normal.x, normal.y, normal.z);
  30685. uvs.push(faceUV[index].x, faceUV[index].y);
  30686. if (faceColors) {
  30687. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30688. }
  30689. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30690. positions.push(vertex.x, vertex.y, vertex.z);
  30691. normals.push(normal.x, normal.y, normal.z);
  30692. uvs.push(faceUV[index].z, faceUV[index].y);
  30693. if (faceColors) {
  30694. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30695. }
  30696. }
  30697. // sides
  30698. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30699. // Result
  30700. var vertexData = new VertexData();
  30701. vertexData.indices = indices;
  30702. vertexData.positions = positions;
  30703. vertexData.normals = normals;
  30704. vertexData.uvs = uvs;
  30705. if (faceColors) {
  30706. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30707. vertexData.colors = totalColors;
  30708. }
  30709. return vertexData;
  30710. };
  30711. VertexData.CreateSphere = function (options) {
  30712. var segments = options.segments || 32;
  30713. var diameterX = options.diameterX || options.diameter || 1;
  30714. var diameterY = options.diameterY || options.diameter || 1;
  30715. var diameterZ = options.diameterZ || options.diameter || 1;
  30716. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30717. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30718. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30719. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30720. var totalZRotationSteps = 2 + segments;
  30721. var totalYRotationSteps = 2 * totalZRotationSteps;
  30722. var indices = [];
  30723. var positions = [];
  30724. var normals = [];
  30725. var uvs = [];
  30726. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30727. var normalizedZ = zRotationStep / totalZRotationSteps;
  30728. var angleZ = normalizedZ * Math.PI * slice;
  30729. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30730. var normalizedY = yRotationStep / totalYRotationSteps;
  30731. var angleY = normalizedY * Math.PI * 2 * arc;
  30732. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30733. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30734. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30735. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30736. var vertex = complete.multiply(radius);
  30737. var normal = complete.divide(radius).normalize();
  30738. positions.push(vertex.x, vertex.y, vertex.z);
  30739. normals.push(normal.x, normal.y, normal.z);
  30740. uvs.push(normalizedY, normalizedZ);
  30741. }
  30742. if (zRotationStep > 0) {
  30743. var verticesCount = positions.length / 3;
  30744. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30745. indices.push((firstIndex));
  30746. indices.push((firstIndex + 1));
  30747. indices.push(firstIndex + totalYRotationSteps + 1);
  30748. indices.push((firstIndex + totalYRotationSteps + 1));
  30749. indices.push((firstIndex + 1));
  30750. indices.push((firstIndex + totalYRotationSteps + 2));
  30751. }
  30752. }
  30753. }
  30754. // Sides
  30755. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30756. // Result
  30757. var vertexData = new VertexData();
  30758. vertexData.indices = indices;
  30759. vertexData.positions = positions;
  30760. vertexData.normals = normals;
  30761. vertexData.uvs = uvs;
  30762. return vertexData;
  30763. };
  30764. // Cylinder and cone
  30765. VertexData.CreateCylinder = function (options) {
  30766. var height = options.height || 2;
  30767. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30768. var diameterBottom = options.diameterBottom || options.diameter || 1;
  30769. var tessellation = options.tessellation || 24;
  30770. var subdivisions = options.subdivisions || 1;
  30771. var hasRings = options.hasRings;
  30772. var enclose = options.enclose;
  30773. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30774. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30775. var faceUV = options.faceUV || new Array(3);
  30776. var faceColors = options.faceColors;
  30777. // default face colors and UV if undefined
  30778. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30779. var ringNb = (hasRings) ? subdivisions : 1;
  30780. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30781. var f;
  30782. for (f = 0; f < surfaceNb; f++) {
  30783. if (faceColors && faceColors[f] === undefined) {
  30784. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30785. }
  30786. }
  30787. for (f = 0; f < surfaceNb; f++) {
  30788. if (faceUV && faceUV[f] === undefined) {
  30789. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30790. }
  30791. }
  30792. var indices = [];
  30793. var positions = [];
  30794. var normals = [];
  30795. var uvs = [];
  30796. var colors = [];
  30797. var angle_step = Math.PI * 2 * arc / tessellation;
  30798. var angle;
  30799. var h;
  30800. var radius;
  30801. var tan = (diameterBottom - diameterTop) / 2 / height;
  30802. var ringVertex = BABYLON.Vector3.Zero();
  30803. var ringNormal = BABYLON.Vector3.Zero();
  30804. var ringFirstVertex = BABYLON.Vector3.Zero();
  30805. var ringFirstNormal = BABYLON.Vector3.Zero();
  30806. var quadNormal = BABYLON.Vector3.Zero();
  30807. var Y = BABYLON.Axis.Y;
  30808. // positions, normals, uvs
  30809. var i;
  30810. var j;
  30811. var r;
  30812. var ringIdx = 1;
  30813. var s = 1; // surface index
  30814. var cs = 0;
  30815. var v = 0;
  30816. for (i = 0; i <= subdivisions; i++) {
  30817. h = i / subdivisions;
  30818. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30819. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30820. for (r = 0; r < ringIdx; r++) {
  30821. if (hasRings) {
  30822. s += r;
  30823. }
  30824. if (enclose) {
  30825. s += 2 * r;
  30826. }
  30827. for (j = 0; j <= tessellation; j++) {
  30828. angle = j * angle_step;
  30829. // position
  30830. ringVertex.x = Math.cos(-angle) * radius;
  30831. ringVertex.y = -height / 2 + h * height;
  30832. ringVertex.z = Math.sin(-angle) * radius;
  30833. // normal
  30834. if (diameterTop === 0 && i === subdivisions) {
  30835. // if no top cap, reuse former normals
  30836. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30837. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30838. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30839. }
  30840. else {
  30841. ringNormal.x = ringVertex.x;
  30842. ringNormal.z = ringVertex.z;
  30843. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30844. ringNormal.normalize();
  30845. }
  30846. // keep first ring vertex values for enclose
  30847. if (j === 0) {
  30848. ringFirstVertex.copyFrom(ringVertex);
  30849. ringFirstNormal.copyFrom(ringNormal);
  30850. }
  30851. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30852. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30853. if (hasRings) {
  30854. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30855. }
  30856. else {
  30857. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30858. }
  30859. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30860. if (faceColors) {
  30861. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30862. }
  30863. }
  30864. // if enclose, add four vertices and their dedicated normals
  30865. if (arc !== 1 && enclose) {
  30866. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30867. positions.push(0, ringVertex.y, 0);
  30868. positions.push(0, ringVertex.y, 0);
  30869. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30870. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30871. quadNormal.normalize();
  30872. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30873. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30874. quadNormal.normalize();
  30875. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30876. if (hasRings) {
  30877. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30878. }
  30879. else {
  30880. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30881. }
  30882. uvs.push(faceUV[s + 1].x, v);
  30883. uvs.push(faceUV[s + 1].z, v);
  30884. if (hasRings) {
  30885. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30886. }
  30887. else {
  30888. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30889. }
  30890. uvs.push(faceUV[s + 2].x, v);
  30891. uvs.push(faceUV[s + 2].z, v);
  30892. if (faceColors) {
  30893. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30894. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30895. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30896. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30897. }
  30898. }
  30899. if (cs !== s) {
  30900. cs = s;
  30901. }
  30902. }
  30903. }
  30904. // indices
  30905. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30906. var s;
  30907. i = 0;
  30908. for (s = 0; s < subdivisions; s++) {
  30909. for (j = 0; j < tessellation; j++) {
  30910. var i0 = i * (e + 1) + j;
  30911. var i1 = (i + 1) * (e + 1) + j;
  30912. var i2 = i * (e + 1) + (j + 1);
  30913. var i3 = (i + 1) * (e + 1) + (j + 1);
  30914. indices.push(i0, i1, i2);
  30915. indices.push(i3, i2, i1);
  30916. }
  30917. if (arc !== 1 && enclose) {
  30918. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30919. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30920. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30921. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30922. }
  30923. i = (hasRings) ? (i + 2) : (i + 1);
  30924. }
  30925. // Caps
  30926. var createCylinderCap = function (isTop) {
  30927. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30928. if (radius === 0) {
  30929. return;
  30930. }
  30931. // Cap positions, normals & uvs
  30932. var angle;
  30933. var circleVector;
  30934. var i;
  30935. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30936. var c;
  30937. if (faceColors) {
  30938. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30939. }
  30940. // cap center
  30941. var vbase = positions.length / 3;
  30942. var offset = isTop ? height / 2 : -height / 2;
  30943. var center = new BABYLON.Vector3(0, offset, 0);
  30944. positions.push(center.x, center.y, center.z);
  30945. normals.push(0, isTop ? 1 : -1, 0);
  30946. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30947. if (faceColors) {
  30948. colors.push(c.r, c.g, c.b, c.a);
  30949. }
  30950. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30951. for (i = 0; i <= tessellation; i++) {
  30952. angle = Math.PI * 2 * i * arc / tessellation;
  30953. var cos = Math.cos(-angle);
  30954. var sin = Math.sin(-angle);
  30955. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30956. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30957. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30958. normals.push(0, isTop ? 1 : -1, 0);
  30959. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30960. if (faceColors) {
  30961. colors.push(c.r, c.g, c.b, c.a);
  30962. }
  30963. }
  30964. // Cap indices
  30965. for (i = 0; i < tessellation; i++) {
  30966. if (!isTop) {
  30967. indices.push(vbase);
  30968. indices.push(vbase + (i + 1));
  30969. indices.push(vbase + (i + 2));
  30970. }
  30971. else {
  30972. indices.push(vbase);
  30973. indices.push(vbase + (i + 2));
  30974. indices.push(vbase + (i + 1));
  30975. }
  30976. }
  30977. };
  30978. // add caps to geometry
  30979. createCylinderCap(false);
  30980. createCylinderCap(true);
  30981. // Sides
  30982. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30983. var vertexData = new VertexData();
  30984. vertexData.indices = indices;
  30985. vertexData.positions = positions;
  30986. vertexData.normals = normals;
  30987. vertexData.uvs = uvs;
  30988. if (faceColors) {
  30989. vertexData.colors = colors;
  30990. }
  30991. return vertexData;
  30992. };
  30993. VertexData.CreateTorus = function (options) {
  30994. var indices = [];
  30995. var positions = [];
  30996. var normals = [];
  30997. var uvs = [];
  30998. var diameter = options.diameter || 1;
  30999. var thickness = options.thickness || 0.5;
  31000. var tessellation = options.tessellation || 16;
  31001. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31002. var stride = tessellation + 1;
  31003. for (var i = 0; i <= tessellation; i++) {
  31004. var u = i / tessellation;
  31005. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31006. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31007. for (var j = 0; j <= tessellation; j++) {
  31008. var v = 1 - j / tessellation;
  31009. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31010. var dx = Math.cos(innerAngle);
  31011. var dy = Math.sin(innerAngle);
  31012. // Create a vertex.
  31013. var normal = new BABYLON.Vector3(dx, dy, 0);
  31014. var position = normal.scale(thickness / 2);
  31015. var textureCoordinate = new BABYLON.Vector2(u, v);
  31016. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31017. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31018. positions.push(position.x, position.y, position.z);
  31019. normals.push(normal.x, normal.y, normal.z);
  31020. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31021. // And create indices for two triangles.
  31022. var nextI = (i + 1) % stride;
  31023. var nextJ = (j + 1) % stride;
  31024. indices.push(i * stride + j);
  31025. indices.push(i * stride + nextJ);
  31026. indices.push(nextI * stride + j);
  31027. indices.push(i * stride + nextJ);
  31028. indices.push(nextI * stride + nextJ);
  31029. indices.push(nextI * stride + j);
  31030. }
  31031. }
  31032. // Sides
  31033. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31034. // Result
  31035. var vertexData = new VertexData();
  31036. vertexData.indices = indices;
  31037. vertexData.positions = positions;
  31038. vertexData.normals = normals;
  31039. vertexData.uvs = uvs;
  31040. return vertexData;
  31041. };
  31042. VertexData.CreateLineSystem = function (options) {
  31043. var indices = [];
  31044. var positions = [];
  31045. var lines = options.lines;
  31046. var idx = 0;
  31047. for (var l = 0; l < lines.length; l++) {
  31048. var points = lines[l];
  31049. for (var index = 0; index < points.length; index++) {
  31050. positions.push(points[index].x, points[index].y, points[index].z);
  31051. if (index > 0) {
  31052. indices.push(idx - 1);
  31053. indices.push(idx);
  31054. }
  31055. idx++;
  31056. }
  31057. }
  31058. var vertexData = new VertexData();
  31059. vertexData.indices = indices;
  31060. vertexData.positions = positions;
  31061. return vertexData;
  31062. };
  31063. VertexData.CreateDashedLines = function (options) {
  31064. var dashSize = options.dashSize || 3;
  31065. var gapSize = options.gapSize || 1;
  31066. var dashNb = options.dashNb || 200;
  31067. var points = options.points;
  31068. var positions = new Array();
  31069. var indices = new Array();
  31070. var curvect = BABYLON.Vector3.Zero();
  31071. var lg = 0;
  31072. var nb = 0;
  31073. var shft = 0;
  31074. var dashshft = 0;
  31075. var curshft = 0;
  31076. var idx = 0;
  31077. var i = 0;
  31078. for (i = 0; i < points.length - 1; i++) {
  31079. points[i + 1].subtractToRef(points[i], curvect);
  31080. lg += curvect.length();
  31081. }
  31082. shft = lg / dashNb;
  31083. dashshft = dashSize * shft / (dashSize + gapSize);
  31084. for (i = 0; i < points.length - 1; i++) {
  31085. points[i + 1].subtractToRef(points[i], curvect);
  31086. nb = Math.floor(curvect.length() / shft);
  31087. curvect.normalize();
  31088. for (var j = 0; j < nb; j++) {
  31089. curshft = shft * j;
  31090. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31091. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31092. indices.push(idx, idx + 1);
  31093. idx += 2;
  31094. }
  31095. }
  31096. // Result
  31097. var vertexData = new VertexData();
  31098. vertexData.positions = positions;
  31099. vertexData.indices = indices;
  31100. return vertexData;
  31101. };
  31102. VertexData.CreateGround = function (options) {
  31103. var indices = [];
  31104. var positions = [];
  31105. var normals = [];
  31106. var uvs = [];
  31107. var row, col;
  31108. var width = options.width || 1;
  31109. var height = options.height || 1;
  31110. var subdivisions = options.subdivisions || 1;
  31111. for (row = 0; row <= subdivisions; row++) {
  31112. for (col = 0; col <= subdivisions; col++) {
  31113. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  31114. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31115. positions.push(position.x, position.y, position.z);
  31116. normals.push(normal.x, normal.y, normal.z);
  31117. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  31118. }
  31119. }
  31120. for (row = 0; row < subdivisions; row++) {
  31121. for (col = 0; col < subdivisions; col++) {
  31122. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  31123. indices.push(col + 1 + row * (subdivisions + 1));
  31124. indices.push(col + row * (subdivisions + 1));
  31125. indices.push(col + (row + 1) * (subdivisions + 1));
  31126. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  31127. indices.push(col + row * (subdivisions + 1));
  31128. }
  31129. }
  31130. // Result
  31131. var vertexData = new VertexData();
  31132. vertexData.indices = indices;
  31133. vertexData.positions = positions;
  31134. vertexData.normals = normals;
  31135. vertexData.uvs = uvs;
  31136. return vertexData;
  31137. };
  31138. VertexData.CreateTiledGround = function (options) {
  31139. var xmin = options.xmin || -1.0;
  31140. var zmin = options.zmin || -1.0;
  31141. var xmax = options.xmax || 1.0;
  31142. var zmax = options.zmax || 1.0;
  31143. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31144. var precision = options.precision || { w: 1, h: 1 };
  31145. var indices = [];
  31146. var positions = [];
  31147. var normals = [];
  31148. var uvs = [];
  31149. var row, col, tileRow, tileCol;
  31150. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31151. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31152. precision.w = (precision.w < 1) ? 1 : precision.w;
  31153. precision.h = (precision.h < 1) ? 1 : precision.h;
  31154. var tileSize = {
  31155. 'w': (xmax - xmin) / subdivisions.w,
  31156. 'h': (zmax - zmin) / subdivisions.h
  31157. };
  31158. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31159. // Indices
  31160. var base = positions.length / 3;
  31161. var rowLength = precision.w + 1;
  31162. for (row = 0; row < precision.h; row++) {
  31163. for (col = 0; col < precision.w; col++) {
  31164. var square = [
  31165. base + col + row * rowLength,
  31166. base + (col + 1) + row * rowLength,
  31167. base + (col + 1) + (row + 1) * rowLength,
  31168. base + col + (row + 1) * rowLength
  31169. ];
  31170. indices.push(square[1]);
  31171. indices.push(square[2]);
  31172. indices.push(square[3]);
  31173. indices.push(square[0]);
  31174. indices.push(square[1]);
  31175. indices.push(square[3]);
  31176. }
  31177. }
  31178. // Position, normals and uvs
  31179. var position = BABYLON.Vector3.Zero();
  31180. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31181. for (row = 0; row <= precision.h; row++) {
  31182. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31183. for (col = 0; col <= precision.w; col++) {
  31184. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31185. position.y = 0;
  31186. positions.push(position.x, position.y, position.z);
  31187. normals.push(normal.x, normal.y, normal.z);
  31188. uvs.push(col / precision.w, row / precision.h);
  31189. }
  31190. }
  31191. }
  31192. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31193. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31194. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31195. }
  31196. }
  31197. // Result
  31198. var vertexData = new VertexData();
  31199. vertexData.indices = indices;
  31200. vertexData.positions = positions;
  31201. vertexData.normals = normals;
  31202. vertexData.uvs = uvs;
  31203. return vertexData;
  31204. };
  31205. VertexData.CreateGroundFromHeightMap = function (options) {
  31206. var indices = [];
  31207. var positions = [];
  31208. var normals = [];
  31209. var uvs = [];
  31210. var row, col;
  31211. // Vertices
  31212. for (row = 0; row <= options.subdivisions; row++) {
  31213. for (col = 0; col <= options.subdivisions; col++) {
  31214. 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));
  31215. // Compute height
  31216. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31217. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31218. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31219. var r = options.buffer[pos] / 255.0;
  31220. var g = options.buffer[pos + 1] / 255.0;
  31221. var b = options.buffer[pos + 2] / 255.0;
  31222. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31223. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31224. // Add vertex
  31225. positions.push(position.x, position.y, position.z);
  31226. normals.push(0, 0, 0);
  31227. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31228. }
  31229. }
  31230. // Indices
  31231. for (row = 0; row < options.subdivisions; row++) {
  31232. for (col = 0; col < options.subdivisions; col++) {
  31233. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31234. indices.push(col + 1 + row * (options.subdivisions + 1));
  31235. indices.push(col + row * (options.subdivisions + 1));
  31236. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31237. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31238. indices.push(col + row * (options.subdivisions + 1));
  31239. }
  31240. }
  31241. // Normals
  31242. VertexData.ComputeNormals(positions, indices, normals);
  31243. // Result
  31244. var vertexData = new VertexData();
  31245. vertexData.indices = indices;
  31246. vertexData.positions = positions;
  31247. vertexData.normals = normals;
  31248. vertexData.uvs = uvs;
  31249. return vertexData;
  31250. };
  31251. VertexData.CreatePlane = function (options) {
  31252. var indices = [];
  31253. var positions = [];
  31254. var normals = [];
  31255. var uvs = [];
  31256. var width = options.width || options.size || 1;
  31257. var height = options.height || options.size || 1;
  31258. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31259. // Vertices
  31260. var halfWidth = width / 2.0;
  31261. var halfHeight = height / 2.0;
  31262. positions.push(-halfWidth, -halfHeight, 0);
  31263. normals.push(0, 0, -1.0);
  31264. uvs.push(0.0, 0.0);
  31265. positions.push(halfWidth, -halfHeight, 0);
  31266. normals.push(0, 0, -1.0);
  31267. uvs.push(1.0, 0.0);
  31268. positions.push(halfWidth, halfHeight, 0);
  31269. normals.push(0, 0, -1.0);
  31270. uvs.push(1.0, 1.0);
  31271. positions.push(-halfWidth, halfHeight, 0);
  31272. normals.push(0, 0, -1.0);
  31273. uvs.push(0.0, 1.0);
  31274. // Indices
  31275. indices.push(0);
  31276. indices.push(1);
  31277. indices.push(2);
  31278. indices.push(0);
  31279. indices.push(2);
  31280. indices.push(3);
  31281. // Sides
  31282. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31283. // Result
  31284. var vertexData = new VertexData();
  31285. vertexData.indices = indices;
  31286. vertexData.positions = positions;
  31287. vertexData.normals = normals;
  31288. vertexData.uvs = uvs;
  31289. return vertexData;
  31290. };
  31291. VertexData.CreateDisc = function (options) {
  31292. var positions = [];
  31293. var indices = [];
  31294. var normals = [];
  31295. var uvs = [];
  31296. var radius = options.radius || 0.5;
  31297. var tessellation = options.tessellation || 64;
  31298. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31299. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31300. // positions and uvs
  31301. positions.push(0, 0, 0); // disc center first
  31302. uvs.push(0.5, 0.5);
  31303. var theta = Math.PI * 2 * arc;
  31304. var step = theta / tessellation;
  31305. for (var a = 0; a < theta; a += step) {
  31306. var x = Math.cos(a);
  31307. var y = Math.sin(a);
  31308. var u = (x + 1) / 2;
  31309. var v = (1 - y) / 2;
  31310. positions.push(radius * x, radius * y, 0);
  31311. uvs.push(u, v);
  31312. }
  31313. if (arc === 1) {
  31314. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31315. uvs.push(uvs[2], uvs[3]);
  31316. }
  31317. //indices
  31318. var vertexNb = positions.length / 3;
  31319. for (var i = 1; i < vertexNb - 1; i++) {
  31320. indices.push(i + 1, 0, i);
  31321. }
  31322. // result
  31323. VertexData.ComputeNormals(positions, indices, normals);
  31324. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31325. var vertexData = new VertexData();
  31326. vertexData.indices = indices;
  31327. vertexData.positions = positions;
  31328. vertexData.normals = normals;
  31329. vertexData.uvs = uvs;
  31330. return vertexData;
  31331. };
  31332. VertexData.CreateIcoSphere = function (options) {
  31333. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31334. var radius = options.radius || 1;
  31335. var flat = (options.flat === undefined) ? true : options.flat;
  31336. var subdivisions = options.subdivisions || 4;
  31337. var radiusX = options.radiusX || radius;
  31338. var radiusY = options.radiusY || radius;
  31339. var radiusZ = options.radiusZ || radius;
  31340. var t = (1 + Math.sqrt(5)) / 2;
  31341. // 12 vertex x,y,z
  31342. var ico_vertices = [
  31343. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31344. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31345. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31346. ];
  31347. // index of 3 vertex makes a face of icopshere
  31348. var ico_indices = [
  31349. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31350. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31351. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31352. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31353. ];
  31354. // vertex for uv have aliased position, not for UV
  31355. var vertices_unalias_id = [
  31356. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31357. // vertex alias
  31358. 0,
  31359. 2,
  31360. 3,
  31361. 3,
  31362. 3,
  31363. 4,
  31364. 7,
  31365. 8,
  31366. 9,
  31367. 9,
  31368. 10,
  31369. 11 // 23: B + 12
  31370. ];
  31371. // uv as integer step (not pixels !)
  31372. var ico_vertexuv = [
  31373. 5, 1, 3, 1, 6, 4, 0, 0,
  31374. 5, 3, 4, 2, 2, 2, 4, 0,
  31375. 2, 0, 1, 1, 6, 0, 6, 2,
  31376. // vertex alias (for same vertex on different faces)
  31377. 0, 4,
  31378. 3, 3,
  31379. 4, 4,
  31380. 3, 1,
  31381. 4, 2,
  31382. 4, 4,
  31383. 0, 2,
  31384. 1, 1,
  31385. 2, 2,
  31386. 3, 3,
  31387. 1, 3,
  31388. 2, 4 // 23: B + 12
  31389. ];
  31390. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31391. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31392. // First island of uv mapping
  31393. // v = 4h 3+ 2
  31394. // v = 3h 9+ 4
  31395. // v = 2h 9+ 5 B
  31396. // v = 1h 9 1 0
  31397. // v = 0h 3 8 7 A
  31398. // u = 0 1 2 3 4 5 6 *a
  31399. // Second island of uv mapping
  31400. // v = 4h 0+ B+ 4+
  31401. // v = 3h A+ 2+
  31402. // v = 2h 7+ 6 3+
  31403. // v = 1h 8+ 3+
  31404. // v = 0h
  31405. // u = 0 1 2 3 4 5 6 *a
  31406. // Face layout on texture UV mapping
  31407. // ============
  31408. // \ 4 /\ 16 / ======
  31409. // \ / \ / /\ 11 /
  31410. // \/ 7 \/ / \ /
  31411. // ======= / 10 \/
  31412. // /\ 17 /\ =======
  31413. // / \ / \ \ 15 /\
  31414. // / 8 \/ 12 \ \ / \
  31415. // ============ \/ 6 \
  31416. // \ 18 /\ ============
  31417. // \ / \ \ 5 /\ 0 /
  31418. // \/ 13 \ \ / \ /
  31419. // ======= \/ 1 \/
  31420. // =============
  31421. // /\ 19 /\ 2 /\
  31422. // / \ / \ / \
  31423. // / 14 \/ 9 \/ 3 \
  31424. // ===================
  31425. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31426. var ustep = 138 / 1024;
  31427. var vstep = 239 / 1024;
  31428. var uoffset = 60 / 1024;
  31429. var voffset = 26 / 1024;
  31430. // Second island should have margin, not to touch the first island
  31431. // avoid any borderline artefact in pixel rounding
  31432. var island_u_offset = -40 / 1024;
  31433. var island_v_offset = +20 / 1024;
  31434. // face is either island 0 or 1 :
  31435. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31436. var island = [
  31437. 0, 0, 0, 0, 1,
  31438. 0, 0, 1, 1, 0,
  31439. 0, 0, 1, 1, 0,
  31440. 0, 1, 1, 1, 0 // 15 - 19
  31441. ];
  31442. var indices = [];
  31443. var positions = [];
  31444. var normals = [];
  31445. var uvs = [];
  31446. var current_indice = 0;
  31447. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31448. var face_vertex_pos = new Array(3);
  31449. var face_vertex_uv = new Array(3);
  31450. var v012;
  31451. for (v012 = 0; v012 < 3; v012++) {
  31452. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31453. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31454. }
  31455. // create all with normals
  31456. for (var face = 0; face < 20; face++) {
  31457. // 3 vertex per face
  31458. for (v012 = 0; v012 < 3; v012++) {
  31459. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31460. var v_id = ico_indices[3 * face + v012];
  31461. // vertex have 3D position (x,y,z)
  31462. 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]);
  31463. // Normalize to get normal, then scale to radius
  31464. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31465. // uv Coordinates from vertex ID
  31466. 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);
  31467. }
  31468. // Subdivide the face (interpolate pos, norm, uv)
  31469. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31470. // - norm is linear interpolation of vertex corner normal
  31471. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31472. // - uv is linear interpolation
  31473. //
  31474. // Topology is as below for sub-divide by 2
  31475. // vertex shown as v0,v1,v2
  31476. // interp index is i1 to progress in range [v0,v1[
  31477. // interp index is i2 to progress in range [v0,v2[
  31478. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31479. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31480. //
  31481. //
  31482. // i2 v2
  31483. // ^ ^
  31484. // / / \
  31485. // / / \
  31486. // / / \
  31487. // / / (0,1) \
  31488. // / #---------\
  31489. // / / \ (0,0)'/ \
  31490. // / / \ / \
  31491. // / / \ / \
  31492. // / / (0,0) \ / (1,0) \
  31493. // / #---------#---------\
  31494. // v0 v1
  31495. //
  31496. // --------------------> i1
  31497. //
  31498. // interp of (i1,i2):
  31499. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31500. // along i1 : lerp(x0,x1, i1/(S-i2))
  31501. //
  31502. // centroid of triangle is needed to get help normal computation
  31503. // (c1,c2) are used for centroid location
  31504. var interp_vertex = function (i1, i2, c1, c2) {
  31505. // vertex is interpolated from
  31506. // - face_vertex_pos[0..2]
  31507. // - face_vertex_uv[0..2]
  31508. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31509. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31510. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31511. pos_interp.normalize();
  31512. var vertex_normal;
  31513. if (flat) {
  31514. // in flat mode, recalculate normal as face centroid normal
  31515. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31516. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31517. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31518. }
  31519. else {
  31520. // in smooth mode, recalculate normal from each single vertex position
  31521. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31522. }
  31523. // Vertex normal need correction due to X,Y,Z radius scaling
  31524. vertex_normal.x /= radiusX;
  31525. vertex_normal.y /= radiusY;
  31526. vertex_normal.z /= radiusZ;
  31527. vertex_normal.normalize();
  31528. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31529. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31530. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31531. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31532. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31533. uvs.push(uv_interp.x, uv_interp.y);
  31534. // push each vertex has member of a face
  31535. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31536. indices.push(current_indice);
  31537. current_indice++;
  31538. };
  31539. for (var i2 = 0; i2 < subdivisions; i2++) {
  31540. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31541. // face : (i1,i2) for /\ :
  31542. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31543. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31544. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31545. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31546. if (i1 + i2 + 1 < subdivisions) {
  31547. // face : (i1,i2)' for \/ :
  31548. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31549. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31550. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31551. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31552. }
  31553. }
  31554. }
  31555. }
  31556. // Sides
  31557. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31558. // Result
  31559. var vertexData = new VertexData();
  31560. vertexData.indices = indices;
  31561. vertexData.positions = positions;
  31562. vertexData.normals = normals;
  31563. vertexData.uvs = uvs;
  31564. return vertexData;
  31565. };
  31566. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31567. VertexData.CreatePolyhedron = function (options) {
  31568. // provided polyhedron types :
  31569. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31570. // 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)
  31571. var polyhedra = [];
  31572. 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]] };
  31573. 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]] };
  31574. polyhedra[2] = {
  31575. 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]],
  31576. 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]]
  31577. };
  31578. polyhedra[3] = {
  31579. 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]],
  31580. 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]]
  31581. };
  31582. polyhedra[4] = {
  31583. 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]],
  31584. 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]]
  31585. };
  31586. 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]] };
  31587. 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]] };
  31588. 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]] };
  31589. 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]] };
  31590. 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]] };
  31591. 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]] };
  31592. 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]] };
  31593. 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]] };
  31594. 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]] };
  31595. polyhedra[14] = {
  31596. 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]],
  31597. 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]]
  31598. };
  31599. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31600. var size = options.size;
  31601. var sizeX = options.sizeX || size || 1;
  31602. var sizeY = options.sizeY || size || 1;
  31603. var sizeZ = options.sizeZ || size || 1;
  31604. var data = options.custom || polyhedra[type];
  31605. var nbfaces = data.face.length;
  31606. var faceUV = options.faceUV || new Array(nbfaces);
  31607. var faceColors = options.faceColors;
  31608. var flat = (options.flat === undefined) ? true : options.flat;
  31609. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31610. var positions = [];
  31611. var indices = [];
  31612. var normals = [];
  31613. var uvs = [];
  31614. var colors = [];
  31615. var index = 0;
  31616. var faceIdx = 0; // face cursor in the array "indexes"
  31617. var indexes = [];
  31618. var i = 0;
  31619. var f = 0;
  31620. var u, v, ang, x, y, tmp;
  31621. // default face colors and UV if undefined
  31622. if (flat) {
  31623. for (f = 0; f < nbfaces; f++) {
  31624. if (faceColors && faceColors[f] === undefined) {
  31625. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31626. }
  31627. if (faceUV && faceUV[f] === undefined) {
  31628. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31629. }
  31630. }
  31631. }
  31632. if (!flat) {
  31633. for (i = 0; i < data.vertex.length; i++) {
  31634. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31635. uvs.push(0, 0);
  31636. }
  31637. for (f = 0; f < nbfaces; f++) {
  31638. for (i = 0; i < data.face[f].length - 2; i++) {
  31639. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31640. }
  31641. }
  31642. }
  31643. else {
  31644. for (f = 0; f < nbfaces; f++) {
  31645. var fl = data.face[f].length; // number of vertices of the current face
  31646. ang = 2 * Math.PI / fl;
  31647. x = 0.5 * Math.tan(ang / 2);
  31648. y = 0.5;
  31649. // positions, uvs, colors
  31650. for (i = 0; i < fl; i++) {
  31651. // positions
  31652. 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);
  31653. indexes.push(index);
  31654. index++;
  31655. // uvs
  31656. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31657. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31658. uvs.push(u, v);
  31659. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31660. y = x * Math.sin(ang) + y * Math.cos(ang);
  31661. x = tmp;
  31662. // colors
  31663. if (faceColors) {
  31664. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31665. }
  31666. }
  31667. // indices from indexes
  31668. for (i = 0; i < fl - 2; i++) {
  31669. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31670. }
  31671. faceIdx += fl;
  31672. }
  31673. }
  31674. VertexData.ComputeNormals(positions, indices, normals);
  31675. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31676. var vertexData = new VertexData();
  31677. vertexData.positions = positions;
  31678. vertexData.indices = indices;
  31679. vertexData.normals = normals;
  31680. vertexData.uvs = uvs;
  31681. if (faceColors && flat) {
  31682. vertexData.colors = colors;
  31683. }
  31684. return vertexData;
  31685. };
  31686. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31687. VertexData.CreateTorusKnot = function (options) {
  31688. var indices = [];
  31689. var positions = [];
  31690. var normals = [];
  31691. var uvs = [];
  31692. var radius = options.radius || 2;
  31693. var tube = options.tube || 0.5;
  31694. var radialSegments = options.radialSegments || 32;
  31695. var tubularSegments = options.tubularSegments || 32;
  31696. var p = options.p || 2;
  31697. var q = options.q || 3;
  31698. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31699. // Helper
  31700. var getPos = function (angle) {
  31701. var cu = Math.cos(angle);
  31702. var su = Math.sin(angle);
  31703. var quOverP = q / p * angle;
  31704. var cs = Math.cos(quOverP);
  31705. var tx = radius * (2 + cs) * 0.5 * cu;
  31706. var ty = radius * (2 + cs) * su * 0.5;
  31707. var tz = radius * Math.sin(quOverP) * 0.5;
  31708. return new BABYLON.Vector3(tx, ty, tz);
  31709. };
  31710. // Vertices
  31711. var i;
  31712. var j;
  31713. for (i = 0; i <= radialSegments; i++) {
  31714. var modI = i % radialSegments;
  31715. var u = modI / radialSegments * 2 * p * Math.PI;
  31716. var p1 = getPos(u);
  31717. var p2 = getPos(u + 0.01);
  31718. var tang = p2.subtract(p1);
  31719. var n = p2.add(p1);
  31720. var bitan = BABYLON.Vector3.Cross(tang, n);
  31721. n = BABYLON.Vector3.Cross(bitan, tang);
  31722. bitan.normalize();
  31723. n.normalize();
  31724. for (j = 0; j < tubularSegments; j++) {
  31725. var modJ = j % tubularSegments;
  31726. var v = modJ / tubularSegments * 2 * Math.PI;
  31727. var cx = -tube * Math.cos(v);
  31728. var cy = tube * Math.sin(v);
  31729. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31730. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31731. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31732. uvs.push(i / radialSegments);
  31733. uvs.push(j / tubularSegments);
  31734. }
  31735. }
  31736. for (i = 0; i < radialSegments; i++) {
  31737. for (j = 0; j < tubularSegments; j++) {
  31738. var jNext = (j + 1) % tubularSegments;
  31739. var a = i * tubularSegments + j;
  31740. var b = (i + 1) * tubularSegments + j;
  31741. var c = (i + 1) * tubularSegments + jNext;
  31742. var d = i * tubularSegments + jNext;
  31743. indices.push(d);
  31744. indices.push(b);
  31745. indices.push(a);
  31746. indices.push(d);
  31747. indices.push(c);
  31748. indices.push(b);
  31749. }
  31750. }
  31751. // Normals
  31752. VertexData.ComputeNormals(positions, indices, normals);
  31753. // Sides
  31754. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31755. // Result
  31756. var vertexData = new VertexData();
  31757. vertexData.indices = indices;
  31758. vertexData.positions = positions;
  31759. vertexData.normals = normals;
  31760. vertexData.uvs = uvs;
  31761. return vertexData;
  31762. };
  31763. // Tools
  31764. /**
  31765. * @param {any} - positions (number[] or Float32Array)
  31766. * @param {any} - indices (number[] or Uint16Array)
  31767. * @param {any} - normals (number[] or Float32Array)
  31768. */
  31769. VertexData.ComputeNormals = function (positions, indices, normals) {
  31770. var index = 0;
  31771. var p1p2x = 0.0;
  31772. var p1p2y = 0.0;
  31773. var p1p2z = 0.0;
  31774. var p3p2x = 0.0;
  31775. var p3p2y = 0.0;
  31776. var p3p2z = 0.0;
  31777. var faceNormalx = 0.0;
  31778. var faceNormaly = 0.0;
  31779. var faceNormalz = 0.0;
  31780. var length = 0.0;
  31781. var i1 = 0;
  31782. var i2 = 0;
  31783. var i3 = 0;
  31784. for (index = 0; index < positions.length; index++) {
  31785. normals[index] = 0.0;
  31786. }
  31787. // indice triplet = 1 face
  31788. var nbFaces = indices.length / 3;
  31789. for (index = 0; index < nbFaces; index++) {
  31790. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  31791. i2 = indices[index * 3 + 1];
  31792. i3 = indices[index * 3 + 2];
  31793. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  31794. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  31795. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  31796. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  31797. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  31798. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  31799. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  31800. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  31801. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  31802. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31803. length = (length === 0) ? 1.0 : length;
  31804. faceNormalx /= length; // normalize this normal
  31805. faceNormaly /= length;
  31806. faceNormalz /= length;
  31807. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  31808. normals[i1 * 3 + 1] += faceNormaly;
  31809. normals[i1 * 3 + 2] += faceNormalz;
  31810. normals[i2 * 3] += faceNormalx;
  31811. normals[i2 * 3 + 1] += faceNormaly;
  31812. normals[i2 * 3 + 2] += faceNormalz;
  31813. normals[i3 * 3] += faceNormalx;
  31814. normals[i3 * 3 + 1] += faceNormaly;
  31815. normals[i3 * 3 + 2] += faceNormalz;
  31816. }
  31817. // last normalization of each normal
  31818. for (index = 0; index < normals.length / 3; index++) {
  31819. faceNormalx = normals[index * 3];
  31820. faceNormaly = normals[index * 3 + 1];
  31821. faceNormalz = normals[index * 3 + 2];
  31822. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31823. length = (length === 0) ? 1.0 : length;
  31824. faceNormalx /= length;
  31825. faceNormaly /= length;
  31826. faceNormalz /= length;
  31827. normals[index * 3] = faceNormalx;
  31828. normals[index * 3 + 1] = faceNormaly;
  31829. normals[index * 3 + 2] = faceNormalz;
  31830. }
  31831. };
  31832. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  31833. var li = indices.length;
  31834. var ln = normals.length;
  31835. var i;
  31836. var n;
  31837. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31838. switch (sideOrientation) {
  31839. case BABYLON.Mesh.FRONTSIDE:
  31840. // nothing changed
  31841. break;
  31842. case BABYLON.Mesh.BACKSIDE:
  31843. var tmp;
  31844. // indices
  31845. for (i = 0; i < li; i += 3) {
  31846. tmp = indices[i];
  31847. indices[i] = indices[i + 2];
  31848. indices[i + 2] = tmp;
  31849. }
  31850. // normals
  31851. for (n = 0; n < ln; n++) {
  31852. normals[n] = -normals[n];
  31853. }
  31854. break;
  31855. case BABYLON.Mesh.DOUBLESIDE:
  31856. // positions
  31857. var lp = positions.length;
  31858. var l = lp / 3;
  31859. for (var p = 0; p < lp; p++) {
  31860. positions[lp + p] = positions[p];
  31861. }
  31862. // indices
  31863. for (i = 0; i < li; i += 3) {
  31864. indices[i + li] = indices[i + 2] + l;
  31865. indices[i + 1 + li] = indices[i + 1] + l;
  31866. indices[i + 2 + li] = indices[i] + l;
  31867. }
  31868. // normals
  31869. for (n = 0; n < ln; n++) {
  31870. normals[ln + n] = -normals[n];
  31871. }
  31872. // uvs
  31873. var lu = uvs.length;
  31874. for (var u = 0; u < lu; u++) {
  31875. uvs[u + lu] = uvs[u];
  31876. }
  31877. break;
  31878. }
  31879. };
  31880. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31881. var vertexData = new VertexData();
  31882. // positions
  31883. var positions = parsedVertexData.positions;
  31884. if (positions) {
  31885. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31886. }
  31887. // normals
  31888. var normals = parsedVertexData.normals;
  31889. if (normals) {
  31890. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31891. }
  31892. // uvs
  31893. var uvs = parsedVertexData.uvs;
  31894. if (uvs) {
  31895. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31896. }
  31897. // uv2s
  31898. var uv2s = parsedVertexData.uv2s;
  31899. if (uv2s) {
  31900. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31901. }
  31902. // uv3s
  31903. var uv3s = parsedVertexData.uv3s;
  31904. if (uv3s) {
  31905. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31906. }
  31907. // uv4s
  31908. var uv4s = parsedVertexData.uv4s;
  31909. if (uv4s) {
  31910. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31911. }
  31912. // uv5s
  31913. var uv5s = parsedVertexData.uv5s;
  31914. if (uv5s) {
  31915. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31916. }
  31917. // uv6s
  31918. var uv6s = parsedVertexData.uv6s;
  31919. if (uv6s) {
  31920. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31921. }
  31922. // colors
  31923. var colors = parsedVertexData.colors;
  31924. if (colors) {
  31925. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31926. }
  31927. // matricesIndices
  31928. var matricesIndices = parsedVertexData.matricesIndices;
  31929. if (matricesIndices) {
  31930. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31931. }
  31932. // matricesWeights
  31933. var matricesWeights = parsedVertexData.matricesWeights;
  31934. if (matricesWeights) {
  31935. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31936. }
  31937. // indices
  31938. var indices = parsedVertexData.indices;
  31939. if (indices) {
  31940. vertexData.indices = indices;
  31941. }
  31942. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31943. };
  31944. return VertexData;
  31945. })();
  31946. BABYLON.VertexData = VertexData;
  31947. })(BABYLON || (BABYLON = {}));
  31948. var BABYLON;
  31949. (function (BABYLON) {
  31950. var Tags = (function () {
  31951. function Tags() {
  31952. }
  31953. Tags.EnableFor = function (obj) {
  31954. obj._tags = obj._tags || {};
  31955. obj.hasTags = function () {
  31956. return Tags.HasTags(obj);
  31957. };
  31958. obj.addTags = function (tagsString) {
  31959. return Tags.AddTagsTo(obj, tagsString);
  31960. };
  31961. obj.removeTags = function (tagsString) {
  31962. return Tags.RemoveTagsFrom(obj, tagsString);
  31963. };
  31964. obj.matchesTagsQuery = function (tagsQuery) {
  31965. return Tags.MatchesQuery(obj, tagsQuery);
  31966. };
  31967. };
  31968. Tags.DisableFor = function (obj) {
  31969. delete obj._tags;
  31970. delete obj.hasTags;
  31971. delete obj.addTags;
  31972. delete obj.removeTags;
  31973. delete obj.matchesTagsQuery;
  31974. };
  31975. Tags.HasTags = function (obj) {
  31976. if (!obj._tags) {
  31977. return false;
  31978. }
  31979. return !BABYLON.Tools.IsEmpty(obj._tags);
  31980. };
  31981. Tags.GetTags = function (obj, asString) {
  31982. if (asString === void 0) { asString = true; }
  31983. if (!obj._tags) {
  31984. return null;
  31985. }
  31986. if (asString) {
  31987. var tagsArray = [];
  31988. for (var tag in obj._tags) {
  31989. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  31990. tagsArray.push(tag);
  31991. }
  31992. }
  31993. return tagsArray.join(" ");
  31994. }
  31995. else {
  31996. return obj._tags;
  31997. }
  31998. };
  31999. // the tags 'true' and 'false' are reserved and cannot be used as tags
  32000. // a tag cannot start with '||', '&&', and '!'
  32001. // it cannot contain whitespaces
  32002. Tags.AddTagsTo = function (obj, tagsString) {
  32003. if (!tagsString) {
  32004. return;
  32005. }
  32006. if (typeof tagsString !== "string") {
  32007. return;
  32008. }
  32009. var tags = tagsString.split(" ");
  32010. for (var t in tags) {
  32011. Tags._AddTagTo(obj, tags[t]);
  32012. }
  32013. };
  32014. Tags._AddTagTo = function (obj, tag) {
  32015. tag = tag.trim();
  32016. if (tag === "" || tag === "true" || tag === "false") {
  32017. return;
  32018. }
  32019. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  32020. return;
  32021. }
  32022. Tags.EnableFor(obj);
  32023. obj._tags[tag] = true;
  32024. };
  32025. Tags.RemoveTagsFrom = function (obj, tagsString) {
  32026. if (!Tags.HasTags(obj)) {
  32027. return;
  32028. }
  32029. var tags = tagsString.split(" ");
  32030. for (var t in tags) {
  32031. Tags._RemoveTagFrom(obj, tags[t]);
  32032. }
  32033. };
  32034. Tags._RemoveTagFrom = function (obj, tag) {
  32035. delete obj._tags[tag];
  32036. };
  32037. Tags.MatchesQuery = function (obj, tagsQuery) {
  32038. if (tagsQuery === undefined) {
  32039. return true;
  32040. }
  32041. if (tagsQuery === "") {
  32042. return Tags.HasTags(obj);
  32043. }
  32044. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  32045. };
  32046. return Tags;
  32047. })();
  32048. BABYLON.Tags = Tags;
  32049. })(BABYLON || (BABYLON = {}));
  32050. var BABYLON;
  32051. (function (BABYLON) {
  32052. var Internals;
  32053. (function (Internals) {
  32054. var AndOrNotEvaluator = (function () {
  32055. function AndOrNotEvaluator() {
  32056. }
  32057. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  32058. if (!query.match(/\([^\(\)]*\)/g)) {
  32059. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  32060. }
  32061. else {
  32062. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  32063. // remove parenthesis
  32064. r = r.slice(1, r.length - 1);
  32065. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  32066. });
  32067. }
  32068. if (query === "true") {
  32069. return true;
  32070. }
  32071. if (query === "false") {
  32072. return false;
  32073. }
  32074. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  32075. };
  32076. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  32077. evaluateCallback = evaluateCallback || (function (r) {
  32078. return r === "true" ? true : false;
  32079. });
  32080. var result;
  32081. var or = parenthesisContent.split("||");
  32082. for (var i in or) {
  32083. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  32084. var and = ori.split("&&");
  32085. if (and.length > 1) {
  32086. for (var j = 0; j < and.length; ++j) {
  32087. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  32088. if (andj !== "true" && andj !== "false") {
  32089. if (andj[0] === "!") {
  32090. result = !evaluateCallback(andj.substring(1));
  32091. }
  32092. else {
  32093. result = evaluateCallback(andj);
  32094. }
  32095. }
  32096. else {
  32097. result = andj === "true" ? true : false;
  32098. }
  32099. if (!result) {
  32100. ori = "false";
  32101. break;
  32102. }
  32103. }
  32104. }
  32105. if (result || ori === "true") {
  32106. result = true;
  32107. break;
  32108. }
  32109. // result equals false (or undefined)
  32110. if (ori !== "true" && ori !== "false") {
  32111. if (ori[0] === "!") {
  32112. result = !evaluateCallback(ori.substring(1));
  32113. }
  32114. else {
  32115. result = evaluateCallback(ori);
  32116. }
  32117. }
  32118. else {
  32119. result = ori === "true" ? true : false;
  32120. }
  32121. }
  32122. // the whole parenthesis scope is replaced by 'true' or 'false'
  32123. return result ? "true" : "false";
  32124. };
  32125. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  32126. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  32127. // remove whitespaces
  32128. r = r.replace(/[\s]/g, function () { return ""; });
  32129. return r.length % 2 ? "!" : "";
  32130. });
  32131. booleanString = booleanString.trim();
  32132. if (booleanString === "!true") {
  32133. booleanString = "false";
  32134. }
  32135. else if (booleanString === "!false") {
  32136. booleanString = "true";
  32137. }
  32138. return booleanString;
  32139. };
  32140. return AndOrNotEvaluator;
  32141. })();
  32142. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  32143. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32144. })(BABYLON || (BABYLON = {}));
  32145. var BABYLON;
  32146. (function (BABYLON) {
  32147. var PostProcessRenderPass = (function () {
  32148. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  32149. this._enabled = true;
  32150. this._refCount = 0;
  32151. this._name = name;
  32152. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  32153. this.setRenderList(renderList);
  32154. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  32155. this._renderTexture.onAfterRenderObservable.add(afterRender);
  32156. this._scene = scene;
  32157. this._renderList = renderList;
  32158. }
  32159. // private
  32160. PostProcessRenderPass.prototype._incRefCount = function () {
  32161. if (this._refCount === 0) {
  32162. this._scene.customRenderTargets.push(this._renderTexture);
  32163. }
  32164. return ++this._refCount;
  32165. };
  32166. PostProcessRenderPass.prototype._decRefCount = function () {
  32167. this._refCount--;
  32168. if (this._refCount <= 0) {
  32169. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  32170. }
  32171. return this._refCount;
  32172. };
  32173. PostProcessRenderPass.prototype._update = function () {
  32174. this.setRenderList(this._renderList);
  32175. };
  32176. // public
  32177. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  32178. this._renderTexture.renderList = renderList;
  32179. };
  32180. PostProcessRenderPass.prototype.getRenderTexture = function () {
  32181. return this._renderTexture;
  32182. };
  32183. return PostProcessRenderPass;
  32184. })();
  32185. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  32186. })(BABYLON || (BABYLON = {}));
  32187. var BABYLON;
  32188. (function (BABYLON) {
  32189. var PostProcessRenderEffect = (function () {
  32190. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  32191. this._engine = engine;
  32192. this._name = name;
  32193. this._singleInstance = singleInstance || true;
  32194. this._getPostProcess = getPostProcess;
  32195. this._cameras = [];
  32196. this._indicesForCamera = [];
  32197. this._postProcesses = {};
  32198. this._renderPasses = {};
  32199. this._renderEffectAsPasses = {};
  32200. }
  32201. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  32202. get: function () {
  32203. for (var index in this._postProcesses) {
  32204. if (!this._postProcesses[index].isSupported) {
  32205. return false;
  32206. }
  32207. }
  32208. return true;
  32209. },
  32210. enumerable: true,
  32211. configurable: true
  32212. });
  32213. PostProcessRenderEffect.prototype._update = function () {
  32214. for (var renderPassName in this._renderPasses) {
  32215. this._renderPasses[renderPassName]._update();
  32216. }
  32217. };
  32218. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  32219. this._renderPasses[renderPass._name] = renderPass;
  32220. this._linkParameters();
  32221. };
  32222. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  32223. delete this._renderPasses[renderPass._name];
  32224. this._linkParameters();
  32225. };
  32226. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  32227. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  32228. this._linkParameters();
  32229. };
  32230. PostProcessRenderEffect.prototype.getPass = function (passName) {
  32231. for (var renderPassName in this._renderPasses) {
  32232. if (renderPassName === passName) {
  32233. return this._renderPasses[passName];
  32234. }
  32235. }
  32236. };
  32237. PostProcessRenderEffect.prototype.emptyPasses = function () {
  32238. this._renderPasses = {};
  32239. this._linkParameters();
  32240. };
  32241. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  32242. var cameraKey;
  32243. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32244. for (var i = 0; i < _cam.length; i++) {
  32245. var camera = _cam[i];
  32246. var cameraName = camera.name;
  32247. if (this._singleInstance) {
  32248. cameraKey = 0;
  32249. }
  32250. else {
  32251. cameraKey = cameraName;
  32252. }
  32253. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  32254. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  32255. if (!this._indicesForCamera[cameraName]) {
  32256. this._indicesForCamera[cameraName] = [];
  32257. }
  32258. this._indicesForCamera[cameraName].push(index);
  32259. if (this._cameras.indexOf(camera) === -1) {
  32260. this._cameras[cameraName] = camera;
  32261. }
  32262. for (var passName in this._renderPasses) {
  32263. this._renderPasses[passName]._incRefCount();
  32264. }
  32265. }
  32266. this._linkParameters();
  32267. };
  32268. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  32269. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32270. for (var i = 0; i < _cam.length; i++) {
  32271. var camera = _cam[i];
  32272. var cameraName = camera.name;
  32273. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32274. var index = this._cameras.indexOf(cameraName);
  32275. this._indicesForCamera.splice(index, 1);
  32276. this._cameras.splice(index, 1);
  32277. for (var passName in this._renderPasses) {
  32278. this._renderPasses[passName]._decRefCount();
  32279. }
  32280. }
  32281. };
  32282. PostProcessRenderEffect.prototype._enable = function (cameras) {
  32283. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32284. for (var i = 0; i < _cam.length; i++) {
  32285. var camera = _cam[i];
  32286. var cameraName = camera.name;
  32287. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  32288. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  32289. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  32290. }
  32291. }
  32292. for (var passName in this._renderPasses) {
  32293. this._renderPasses[passName]._incRefCount();
  32294. }
  32295. }
  32296. };
  32297. PostProcessRenderEffect.prototype._disable = function (cameras) {
  32298. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32299. for (var i = 0; i < _cam.length; i++) {
  32300. var camera = _cam[i];
  32301. var cameraName = camera.Name;
  32302. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32303. for (var passName in this._renderPasses) {
  32304. this._renderPasses[passName]._decRefCount();
  32305. }
  32306. }
  32307. };
  32308. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  32309. if (this._singleInstance) {
  32310. return this._postProcesses[0];
  32311. }
  32312. else {
  32313. return this._postProcesses[camera.name];
  32314. }
  32315. };
  32316. PostProcessRenderEffect.prototype._linkParameters = function () {
  32317. var _this = this;
  32318. for (var index in this._postProcesses) {
  32319. if (this.applyParameters) {
  32320. this.applyParameters(this._postProcesses[index]);
  32321. }
  32322. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  32323. _this._linkTextures(effect);
  32324. });
  32325. }
  32326. };
  32327. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  32328. for (var renderPassName in this._renderPasses) {
  32329. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  32330. }
  32331. for (var renderEffectName in this._renderEffectAsPasses) {
  32332. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  32333. }
  32334. };
  32335. return PostProcessRenderEffect;
  32336. })();
  32337. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  32338. })(BABYLON || (BABYLON = {}));
  32339. var BABYLON;
  32340. (function (BABYLON) {
  32341. var PostProcessRenderPipeline = (function () {
  32342. function PostProcessRenderPipeline(engine, name) {
  32343. this._engine = engine;
  32344. this._name = name;
  32345. this._renderEffects = {};
  32346. this._renderEffectsForIsolatedPass = {};
  32347. this._cameras = [];
  32348. }
  32349. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  32350. get: function () {
  32351. for (var renderEffectName in this._renderEffects) {
  32352. if (!this._renderEffects[renderEffectName].isSupported) {
  32353. return false;
  32354. }
  32355. }
  32356. return true;
  32357. },
  32358. enumerable: true,
  32359. configurable: true
  32360. });
  32361. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  32362. this._renderEffects[renderEffect._name] = renderEffect;
  32363. };
  32364. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  32365. var renderEffects = this._renderEffects[renderEffectName];
  32366. if (!renderEffects) {
  32367. return;
  32368. }
  32369. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32370. };
  32371. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  32372. var renderEffects = this._renderEffects[renderEffectName];
  32373. if (!renderEffects) {
  32374. return;
  32375. }
  32376. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32377. };
  32378. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  32379. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32380. var indicesToDelete = [];
  32381. var i;
  32382. for (i = 0; i < _cam.length; i++) {
  32383. var camera = _cam[i];
  32384. var cameraName = camera.name;
  32385. if (this._cameras.indexOf(camera) === -1) {
  32386. this._cameras[cameraName] = camera;
  32387. }
  32388. else if (unique) {
  32389. indicesToDelete.push(i);
  32390. }
  32391. }
  32392. for (i = 0; i < indicesToDelete.length; i++) {
  32393. cameras.splice(indicesToDelete[i], 1);
  32394. }
  32395. for (var renderEffectName in this._renderEffects) {
  32396. this._renderEffects[renderEffectName]._attachCameras(_cam);
  32397. }
  32398. };
  32399. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  32400. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32401. for (var renderEffectName in this._renderEffects) {
  32402. this._renderEffects[renderEffectName]._detachCameras(_cam);
  32403. }
  32404. for (var i = 0; i < _cam.length; i++) {
  32405. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  32406. }
  32407. };
  32408. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  32409. var _this = this;
  32410. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32411. var pass = null;
  32412. var renderEffectName;
  32413. for (renderEffectName in this._renderEffects) {
  32414. pass = this._renderEffects[renderEffectName].getPass(passName);
  32415. if (pass != null) {
  32416. break;
  32417. }
  32418. }
  32419. if (pass === null) {
  32420. return;
  32421. }
  32422. for (renderEffectName in this._renderEffects) {
  32423. this._renderEffects[renderEffectName]._disable(_cam);
  32424. }
  32425. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  32426. for (var i = 0; i < _cam.length; i++) {
  32427. var camera = _cam[i];
  32428. var cameraName = camera.name;
  32429. 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); });
  32430. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  32431. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  32432. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  32433. }
  32434. };
  32435. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  32436. var _this = this;
  32437. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32438. for (var i = 0; i < _cam.length; i++) {
  32439. var camera = _cam[i];
  32440. var cameraName = camera.name;
  32441. 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); });
  32442. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  32443. }
  32444. for (var renderEffectName in this._renderEffects) {
  32445. this._renderEffects[renderEffectName]._enable(_cam);
  32446. }
  32447. };
  32448. PostProcessRenderPipeline.prototype._update = function () {
  32449. for (var renderEffectName in this._renderEffects) {
  32450. this._renderEffects[renderEffectName]._update();
  32451. }
  32452. for (var i = 0; i < this._cameras.length; i++) {
  32453. var cameraName = this._cameras[i].name;
  32454. if (this._renderEffectsForIsolatedPass[cameraName]) {
  32455. this._renderEffectsForIsolatedPass[cameraName]._update();
  32456. }
  32457. }
  32458. };
  32459. PostProcessRenderPipeline.prototype.dispose = function () {
  32460. // Must be implemented by children
  32461. };
  32462. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  32463. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  32464. return PostProcessRenderPipeline;
  32465. })();
  32466. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  32467. })(BABYLON || (BABYLON = {}));
  32468. var BABYLON;
  32469. (function (BABYLON) {
  32470. var PostProcessRenderPipelineManager = (function () {
  32471. function PostProcessRenderPipelineManager() {
  32472. this._renderPipelines = {};
  32473. }
  32474. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  32475. this._renderPipelines[renderPipeline._name] = renderPipeline;
  32476. };
  32477. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  32478. var renderPipeline = this._renderPipelines[renderPipelineName];
  32479. if (!renderPipeline) {
  32480. return;
  32481. }
  32482. renderPipeline._attachCameras(cameras, unique);
  32483. };
  32484. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  32485. var renderPipeline = this._renderPipelines[renderPipelineName];
  32486. if (!renderPipeline) {
  32487. return;
  32488. }
  32489. renderPipeline._detachCameras(cameras);
  32490. };
  32491. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32492. var renderPipeline = this._renderPipelines[renderPipelineName];
  32493. if (!renderPipeline) {
  32494. return;
  32495. }
  32496. renderPipeline._enableEffect(renderEffectName, cameras);
  32497. };
  32498. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32499. var renderPipeline = this._renderPipelines[renderPipelineName];
  32500. if (!renderPipeline) {
  32501. return;
  32502. }
  32503. renderPipeline._disableEffect(renderEffectName, cameras);
  32504. };
  32505. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  32506. var renderPipeline = this._renderPipelines[renderPipelineName];
  32507. if (!renderPipeline) {
  32508. return;
  32509. }
  32510. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  32511. };
  32512. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  32513. var renderPipeline = this._renderPipelines[renderPipelineName];
  32514. if (!renderPipeline) {
  32515. return;
  32516. }
  32517. renderPipeline._disableDisplayOnlyPass(cameras);
  32518. };
  32519. PostProcessRenderPipelineManager.prototype.update = function () {
  32520. for (var renderPipelineName in this._renderPipelines) {
  32521. var pipeline = this._renderPipelines[renderPipelineName];
  32522. if (!pipeline.isSupported) {
  32523. pipeline.dispose();
  32524. delete this._renderPipelines[renderPipelineName];
  32525. }
  32526. else {
  32527. pipeline._update();
  32528. }
  32529. }
  32530. };
  32531. return PostProcessRenderPipelineManager;
  32532. })();
  32533. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  32534. })(BABYLON || (BABYLON = {}));
  32535. var BABYLON;
  32536. (function (BABYLON) {
  32537. var BoundingBoxRenderer = (function () {
  32538. function BoundingBoxRenderer(scene) {
  32539. this.frontColor = new BABYLON.Color3(1, 1, 1);
  32540. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  32541. this.showBackLines = true;
  32542. this.renderList = new BABYLON.SmartArray(32);
  32543. this._vertexBuffers = {};
  32544. this._scene = scene;
  32545. }
  32546. BoundingBoxRenderer.prototype._prepareRessources = function () {
  32547. if (this._colorShader) {
  32548. return;
  32549. }
  32550. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  32551. attributes: [BABYLON.VertexBuffer.PositionKind],
  32552. uniforms: ["worldViewProjection", "color"]
  32553. });
  32554. var engine = this._scene.getEngine();
  32555. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  32556. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  32557. 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]);
  32558. };
  32559. BoundingBoxRenderer.prototype.reset = function () {
  32560. this.renderList.reset();
  32561. };
  32562. BoundingBoxRenderer.prototype.render = function () {
  32563. if (this.renderList.length === 0) {
  32564. return;
  32565. }
  32566. this._prepareRessources();
  32567. if (!this._colorShader.isReady()) {
  32568. return;
  32569. }
  32570. var engine = this._scene.getEngine();
  32571. engine.setDepthWrite(false);
  32572. this._colorShader._preBind();
  32573. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  32574. var boundingBox = this.renderList.data[boundingBoxIndex];
  32575. var min = boundingBox.minimum;
  32576. var max = boundingBox.maximum;
  32577. var diff = max.subtract(min);
  32578. var median = min.add(diff.scale(0.5));
  32579. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  32580. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  32581. .multiply(boundingBox.getWorldMatrix());
  32582. // VBOs
  32583. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  32584. if (this.showBackLines) {
  32585. // Back
  32586. engine.setDepthFunctionToGreaterOrEqual();
  32587. this._scene.resetCachedMaterial();
  32588. this._colorShader.setColor4("color", this.backColor.toColor4());
  32589. this._colorShader.bind(worldMatrix);
  32590. // Draw order
  32591. engine.draw(false, 0, 24);
  32592. }
  32593. // Front
  32594. engine.setDepthFunctionToLess();
  32595. this._scene.resetCachedMaterial();
  32596. this._colorShader.setColor4("color", this.frontColor.toColor4());
  32597. this._colorShader.bind(worldMatrix);
  32598. // Draw order
  32599. engine.draw(false, 0, 24);
  32600. }
  32601. this._colorShader.unbind();
  32602. engine.setDepthFunctionToLessOrEqual();
  32603. engine.setDepthWrite(true);
  32604. };
  32605. BoundingBoxRenderer.prototype.dispose = function () {
  32606. if (!this._colorShader) {
  32607. return;
  32608. }
  32609. this._colorShader.dispose();
  32610. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32611. if (buffer) {
  32612. buffer.dispose();
  32613. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32614. }
  32615. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32616. };
  32617. return BoundingBoxRenderer;
  32618. })();
  32619. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  32620. })(BABYLON || (BABYLON = {}));
  32621. var BABYLON;
  32622. (function (BABYLON) {
  32623. var Condition = (function () {
  32624. function Condition(actionManager) {
  32625. this._actionManager = actionManager;
  32626. }
  32627. Condition.prototype.isValid = function () {
  32628. return true;
  32629. };
  32630. Condition.prototype._getProperty = function (propertyPath) {
  32631. return this._actionManager._getProperty(propertyPath);
  32632. };
  32633. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  32634. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32635. };
  32636. Condition.prototype.serialize = function () {
  32637. };
  32638. Condition.prototype._serialize = function (serializedCondition) {
  32639. return {
  32640. type: 2,
  32641. children: [],
  32642. name: serializedCondition.name,
  32643. properties: serializedCondition.properties
  32644. };
  32645. };
  32646. return Condition;
  32647. })();
  32648. BABYLON.Condition = Condition;
  32649. var ValueCondition = (function (_super) {
  32650. __extends(ValueCondition, _super);
  32651. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  32652. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  32653. _super.call(this, actionManager);
  32654. this.propertyPath = propertyPath;
  32655. this.value = value;
  32656. this.operator = operator;
  32657. this._target = target;
  32658. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  32659. this._property = this._getProperty(this.propertyPath);
  32660. }
  32661. Object.defineProperty(ValueCondition, "IsEqual", {
  32662. get: function () {
  32663. return ValueCondition._IsEqual;
  32664. },
  32665. enumerable: true,
  32666. configurable: true
  32667. });
  32668. Object.defineProperty(ValueCondition, "IsDifferent", {
  32669. get: function () {
  32670. return ValueCondition._IsDifferent;
  32671. },
  32672. enumerable: true,
  32673. configurable: true
  32674. });
  32675. Object.defineProperty(ValueCondition, "IsGreater", {
  32676. get: function () {
  32677. return ValueCondition._IsGreater;
  32678. },
  32679. enumerable: true,
  32680. configurable: true
  32681. });
  32682. Object.defineProperty(ValueCondition, "IsLesser", {
  32683. get: function () {
  32684. return ValueCondition._IsLesser;
  32685. },
  32686. enumerable: true,
  32687. configurable: true
  32688. });
  32689. // Methods
  32690. ValueCondition.prototype.isValid = function () {
  32691. switch (this.operator) {
  32692. case ValueCondition.IsGreater:
  32693. return this._effectiveTarget[this._property] > this.value;
  32694. case ValueCondition.IsLesser:
  32695. return this._effectiveTarget[this._property] < this.value;
  32696. case ValueCondition.IsEqual:
  32697. case ValueCondition.IsDifferent:
  32698. var check;
  32699. if (this.value.equals) {
  32700. check = this.value.equals(this._effectiveTarget[this._property]);
  32701. }
  32702. else {
  32703. check = this.value === this._effectiveTarget[this._property];
  32704. }
  32705. return this.operator === ValueCondition.IsEqual ? check : !check;
  32706. }
  32707. return false;
  32708. };
  32709. ValueCondition.prototype.serialize = function () {
  32710. return this._serialize({
  32711. name: "ValueCondition",
  32712. properties: [
  32713. BABYLON.Action._GetTargetProperty(this._target),
  32714. { name: "propertyPath", value: this.propertyPath },
  32715. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32716. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  32717. ]
  32718. });
  32719. };
  32720. ValueCondition.GetOperatorName = function (operator) {
  32721. switch (operator) {
  32722. case ValueCondition._IsEqual: return "IsEqual";
  32723. case ValueCondition._IsDifferent: return "IsDifferent";
  32724. case ValueCondition._IsGreater: return "IsGreater";
  32725. case ValueCondition._IsLesser: return "IsLesser";
  32726. default: return "";
  32727. }
  32728. };
  32729. // Statics
  32730. ValueCondition._IsEqual = 0;
  32731. ValueCondition._IsDifferent = 1;
  32732. ValueCondition._IsGreater = 2;
  32733. ValueCondition._IsLesser = 3;
  32734. return ValueCondition;
  32735. })(Condition);
  32736. BABYLON.ValueCondition = ValueCondition;
  32737. var PredicateCondition = (function (_super) {
  32738. __extends(PredicateCondition, _super);
  32739. function PredicateCondition(actionManager, predicate) {
  32740. _super.call(this, actionManager);
  32741. this.predicate = predicate;
  32742. }
  32743. PredicateCondition.prototype.isValid = function () {
  32744. return this.predicate();
  32745. };
  32746. return PredicateCondition;
  32747. })(Condition);
  32748. BABYLON.PredicateCondition = PredicateCondition;
  32749. var StateCondition = (function (_super) {
  32750. __extends(StateCondition, _super);
  32751. function StateCondition(actionManager, target, value) {
  32752. _super.call(this, actionManager);
  32753. this.value = value;
  32754. this._target = target;
  32755. }
  32756. // Methods
  32757. StateCondition.prototype.isValid = function () {
  32758. return this._target.state === this.value;
  32759. };
  32760. StateCondition.prototype.serialize = function () {
  32761. return this._serialize({
  32762. name: "StateCondition",
  32763. properties: [
  32764. BABYLON.Action._GetTargetProperty(this._target),
  32765. { name: "value", value: this.value }
  32766. ]
  32767. });
  32768. };
  32769. return StateCondition;
  32770. })(Condition);
  32771. BABYLON.StateCondition = StateCondition;
  32772. })(BABYLON || (BABYLON = {}));
  32773. var BABYLON;
  32774. (function (BABYLON) {
  32775. var Action = (function () {
  32776. function Action(triggerOptions, condition) {
  32777. this.triggerOptions = triggerOptions;
  32778. if (triggerOptions.parameter) {
  32779. this.trigger = triggerOptions.trigger;
  32780. this._triggerParameter = triggerOptions.parameter;
  32781. }
  32782. else {
  32783. this.trigger = triggerOptions;
  32784. }
  32785. this._nextActiveAction = this;
  32786. this._condition = condition;
  32787. }
  32788. // Methods
  32789. Action.prototype._prepare = function () {
  32790. };
  32791. Action.prototype.getTriggerParameter = function () {
  32792. return this._triggerParameter;
  32793. };
  32794. Action.prototype._executeCurrent = function (evt) {
  32795. if (this._nextActiveAction._condition) {
  32796. var condition = this._nextActiveAction._condition;
  32797. var currentRenderId = this._actionManager.getScene().getRenderId();
  32798. // We cache the current evaluation for the current frame
  32799. if (condition._evaluationId === currentRenderId) {
  32800. if (!condition._currentResult) {
  32801. return;
  32802. }
  32803. }
  32804. else {
  32805. condition._evaluationId = currentRenderId;
  32806. if (!condition.isValid()) {
  32807. condition._currentResult = false;
  32808. return;
  32809. }
  32810. condition._currentResult = true;
  32811. }
  32812. }
  32813. this._nextActiveAction.execute(evt);
  32814. this.skipToNextActiveAction();
  32815. };
  32816. Action.prototype.execute = function (evt) {
  32817. };
  32818. Action.prototype.skipToNextActiveAction = function () {
  32819. if (this._nextActiveAction._child) {
  32820. if (!this._nextActiveAction._child._actionManager) {
  32821. this._nextActiveAction._child._actionManager = this._actionManager;
  32822. }
  32823. this._nextActiveAction = this._nextActiveAction._child;
  32824. }
  32825. else {
  32826. this._nextActiveAction = this;
  32827. }
  32828. };
  32829. Action.prototype.then = function (action) {
  32830. this._child = action;
  32831. action._actionManager = this._actionManager;
  32832. action._prepare();
  32833. return action;
  32834. };
  32835. Action.prototype._getProperty = function (propertyPath) {
  32836. return this._actionManager._getProperty(propertyPath);
  32837. };
  32838. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  32839. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32840. };
  32841. Action.prototype.serialize = function (parent) {
  32842. };
  32843. // Called by BABYLON.Action objects in serialize(...). Internal use
  32844. Action.prototype._serialize = function (serializedAction, parent) {
  32845. var serializationObject = {
  32846. type: 1,
  32847. children: [],
  32848. name: serializedAction.name,
  32849. properties: serializedAction.properties || []
  32850. };
  32851. // Serialize child
  32852. if (this._child) {
  32853. this._child.serialize(serializationObject);
  32854. }
  32855. // Check if "this" has a condition
  32856. if (this._condition) {
  32857. var serializedCondition = this._condition.serialize();
  32858. serializedCondition.children.push(serializationObject);
  32859. if (parent) {
  32860. parent.children.push(serializedCondition);
  32861. }
  32862. return serializedCondition;
  32863. }
  32864. if (parent) {
  32865. parent.children.push(serializationObject);
  32866. }
  32867. return serializationObject;
  32868. };
  32869. Action._SerializeValueAsString = function (value) {
  32870. if (typeof value === "number") {
  32871. return value.toString();
  32872. }
  32873. if (typeof value === "boolean") {
  32874. return value ? "true" : "false";
  32875. }
  32876. if (value instanceof BABYLON.Vector2) {
  32877. return value.x + ", " + value.y;
  32878. }
  32879. if (value instanceof BABYLON.Vector3) {
  32880. return value.x + ", " + value.y + ", " + value.z;
  32881. }
  32882. if (value instanceof BABYLON.Color3) {
  32883. return value.r + ", " + value.g + ", " + value.b;
  32884. }
  32885. if (value instanceof BABYLON.Color4) {
  32886. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  32887. }
  32888. return value; // string
  32889. };
  32890. Action._GetTargetProperty = function (target) {
  32891. return {
  32892. name: "target",
  32893. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  32894. : target instanceof BABYLON.Light ? "LightProperties"
  32895. : target instanceof BABYLON.Camera ? "CameraProperties"
  32896. : "SceneProperties",
  32897. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  32898. };
  32899. };
  32900. return Action;
  32901. })();
  32902. BABYLON.Action = Action;
  32903. })(BABYLON || (BABYLON = {}));
  32904. var BABYLON;
  32905. (function (BABYLON) {
  32906. /**
  32907. * ActionEvent is the event beint sent when an action is triggered.
  32908. */
  32909. var ActionEvent = (function () {
  32910. /**
  32911. * @constructor
  32912. * @param source The mesh or sprite that triggered the action.
  32913. * @param pointerX The X mouse cursor position at the time of the event
  32914. * @param pointerY The Y mouse cursor position at the time of the event
  32915. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  32916. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  32917. */
  32918. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  32919. this.source = source;
  32920. this.pointerX = pointerX;
  32921. this.pointerY = pointerY;
  32922. this.meshUnderPointer = meshUnderPointer;
  32923. this.sourceEvent = sourceEvent;
  32924. this.additionalData = additionalData;
  32925. }
  32926. /**
  32927. * Helper function to auto-create an ActionEvent from a source mesh.
  32928. * @param source The source mesh that triggered the event
  32929. * @param evt {Event} The original (browser) event
  32930. */
  32931. ActionEvent.CreateNew = function (source, evt, additionalData) {
  32932. var scene = source.getScene();
  32933. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32934. };
  32935. /**
  32936. * Helper function to auto-create an ActionEvent from a source mesh.
  32937. * @param source The source sprite that triggered the event
  32938. * @param scene Scene associated with the sprite
  32939. * @param evt {Event} The original (browser) event
  32940. */
  32941. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  32942. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32943. };
  32944. /**
  32945. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  32946. * @param scene the scene where the event occurred
  32947. * @param evt {Event} The original (browser) event
  32948. */
  32949. ActionEvent.CreateNewFromScene = function (scene, evt) {
  32950. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  32951. };
  32952. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  32953. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  32954. };
  32955. return ActionEvent;
  32956. })();
  32957. BABYLON.ActionEvent = ActionEvent;
  32958. /**
  32959. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  32960. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  32961. */
  32962. var ActionManager = (function () {
  32963. function ActionManager(scene) {
  32964. // Members
  32965. this.actions = new Array();
  32966. this._scene = scene;
  32967. scene._actionManagers.push(this);
  32968. }
  32969. Object.defineProperty(ActionManager, "NothingTrigger", {
  32970. get: function () {
  32971. return ActionManager._NothingTrigger;
  32972. },
  32973. enumerable: true,
  32974. configurable: true
  32975. });
  32976. Object.defineProperty(ActionManager, "OnPickTrigger", {
  32977. get: function () {
  32978. return ActionManager._OnPickTrigger;
  32979. },
  32980. enumerable: true,
  32981. configurable: true
  32982. });
  32983. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  32984. get: function () {
  32985. return ActionManager._OnLeftPickTrigger;
  32986. },
  32987. enumerable: true,
  32988. configurable: true
  32989. });
  32990. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  32991. get: function () {
  32992. return ActionManager._OnRightPickTrigger;
  32993. },
  32994. enumerable: true,
  32995. configurable: true
  32996. });
  32997. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  32998. get: function () {
  32999. return ActionManager._OnCenterPickTrigger;
  33000. },
  33001. enumerable: true,
  33002. configurable: true
  33003. });
  33004. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  33005. get: function () {
  33006. return ActionManager._OnPickDownTrigger;
  33007. },
  33008. enumerable: true,
  33009. configurable: true
  33010. });
  33011. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  33012. get: function () {
  33013. return ActionManager._OnPickUpTrigger;
  33014. },
  33015. enumerable: true,
  33016. configurable: true
  33017. });
  33018. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  33019. /// This trigger will only be raised if you also declared a OnPickDown
  33020. get: function () {
  33021. return ActionManager._OnPickOutTrigger;
  33022. },
  33023. enumerable: true,
  33024. configurable: true
  33025. });
  33026. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  33027. get: function () {
  33028. return ActionManager._OnLongPressTrigger;
  33029. },
  33030. enumerable: true,
  33031. configurable: true
  33032. });
  33033. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  33034. get: function () {
  33035. return ActionManager._OnPointerOverTrigger;
  33036. },
  33037. enumerable: true,
  33038. configurable: true
  33039. });
  33040. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  33041. get: function () {
  33042. return ActionManager._OnPointerOutTrigger;
  33043. },
  33044. enumerable: true,
  33045. configurable: true
  33046. });
  33047. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  33048. get: function () {
  33049. return ActionManager._OnEveryFrameTrigger;
  33050. },
  33051. enumerable: true,
  33052. configurable: true
  33053. });
  33054. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  33055. get: function () {
  33056. return ActionManager._OnIntersectionEnterTrigger;
  33057. },
  33058. enumerable: true,
  33059. configurable: true
  33060. });
  33061. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  33062. get: function () {
  33063. return ActionManager._OnIntersectionExitTrigger;
  33064. },
  33065. enumerable: true,
  33066. configurable: true
  33067. });
  33068. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  33069. get: function () {
  33070. return ActionManager._OnKeyDownTrigger;
  33071. },
  33072. enumerable: true,
  33073. configurable: true
  33074. });
  33075. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  33076. get: function () {
  33077. return ActionManager._OnKeyUpTrigger;
  33078. },
  33079. enumerable: true,
  33080. configurable: true
  33081. });
  33082. // Methods
  33083. ActionManager.prototype.dispose = function () {
  33084. var index = this._scene._actionManagers.indexOf(this);
  33085. if (index > -1) {
  33086. this._scene._actionManagers.splice(index, 1);
  33087. }
  33088. };
  33089. ActionManager.prototype.getScene = function () {
  33090. return this._scene;
  33091. };
  33092. /**
  33093. * Does this action manager handles actions of any of the given triggers
  33094. * @param {number[]} triggers - the triggers to be tested
  33095. * @return {boolean} whether one (or more) of the triggers is handeled
  33096. */
  33097. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  33098. for (var index = 0; index < this.actions.length; index++) {
  33099. var action = this.actions[index];
  33100. if (triggers.indexOf(action.trigger) > -1) {
  33101. return true;
  33102. }
  33103. }
  33104. return false;
  33105. };
  33106. /**
  33107. * Does this action manager handles actions of a given trigger
  33108. * @param {number} trigger - the trigger to be tested
  33109. * @return {boolean} whether the trigger is handeled
  33110. */
  33111. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  33112. for (var index = 0; index < this.actions.length; index++) {
  33113. var action = this.actions[index];
  33114. if (action.trigger === trigger) {
  33115. return true;
  33116. }
  33117. }
  33118. return false;
  33119. };
  33120. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  33121. /**
  33122. * Does this action manager has pointer triggers
  33123. * @return {boolean} whether or not it has pointer triggers
  33124. */
  33125. get: function () {
  33126. for (var index = 0; index < this.actions.length; index++) {
  33127. var action = this.actions[index];
  33128. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  33129. return true;
  33130. }
  33131. }
  33132. return false;
  33133. },
  33134. enumerable: true,
  33135. configurable: true
  33136. });
  33137. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33138. /**
  33139. * Does this action manager has pick triggers
  33140. * @return {boolean} whether or not it has pick triggers
  33141. */
  33142. get: function () {
  33143. for (var index = 0; index < this.actions.length; index++) {
  33144. var action = this.actions[index];
  33145. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33146. return true;
  33147. }
  33148. }
  33149. return false;
  33150. },
  33151. enumerable: true,
  33152. configurable: true
  33153. });
  33154. /**
  33155. * Registers an action to this action manager
  33156. * @param {BABYLON.Action} action - the action to be registered
  33157. * @return {BABYLON.Action} the action amended (prepared) after registration
  33158. */
  33159. ActionManager.prototype.registerAction = function (action) {
  33160. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33161. if (this.getScene().actionManager !== this) {
  33162. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33163. return null;
  33164. }
  33165. }
  33166. this.actions.push(action);
  33167. action._actionManager = this;
  33168. action._prepare();
  33169. return action;
  33170. };
  33171. /**
  33172. * Process a specific trigger
  33173. * @param {number} trigger - the trigger to process
  33174. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33175. */
  33176. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33177. for (var index = 0; index < this.actions.length; index++) {
  33178. var action = this.actions[index];
  33179. if (action.trigger === trigger) {
  33180. if (trigger === ActionManager.OnKeyUpTrigger
  33181. || trigger === ActionManager.OnKeyDownTrigger) {
  33182. var parameter = action.getTriggerParameter();
  33183. if (parameter) {
  33184. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33185. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33186. if (actualkey !== parameter.toLowerCase()) {
  33187. continue;
  33188. }
  33189. }
  33190. }
  33191. action._executeCurrent(evt);
  33192. }
  33193. }
  33194. };
  33195. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33196. var properties = propertyPath.split(".");
  33197. for (var index = 0; index < properties.length - 1; index++) {
  33198. target = target[properties[index]];
  33199. }
  33200. return target;
  33201. };
  33202. ActionManager.prototype._getProperty = function (propertyPath) {
  33203. var properties = propertyPath.split(".");
  33204. return properties[properties.length - 1];
  33205. };
  33206. ActionManager.prototype.serialize = function (name) {
  33207. var root = {
  33208. children: [],
  33209. name: name,
  33210. type: 3,
  33211. properties: [] // Empty for root but required
  33212. };
  33213. for (var i = 0; i < this.actions.length; i++) {
  33214. var triggerObject = {
  33215. type: 0,
  33216. children: [],
  33217. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  33218. properties: []
  33219. };
  33220. var triggerOptions = this.actions[i].triggerOptions;
  33221. if (triggerOptions && typeof triggerOptions !== "number") {
  33222. if (triggerOptions.parameter instanceof BABYLON.Node) {
  33223. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  33224. }
  33225. else {
  33226. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  33227. }
  33228. }
  33229. // Serialize child action, recursively
  33230. this.actions[i].serialize(triggerObject);
  33231. // Add serialized trigger
  33232. root.children.push(triggerObject);
  33233. }
  33234. return root;
  33235. };
  33236. ActionManager.Parse = function (parsedActions, object, scene) {
  33237. var actionManager = new BABYLON.ActionManager(scene);
  33238. if (object === null)
  33239. scene.actionManager = actionManager;
  33240. else
  33241. object.actionManager = actionManager;
  33242. // instanciate a new object
  33243. var instanciate = function (name, params) {
  33244. var newInstance = Object.create(BABYLON[name].prototype);
  33245. newInstance.constructor.apply(newInstance, params);
  33246. return newInstance;
  33247. };
  33248. var parseParameter = function (name, value, target, propertyPath) {
  33249. if (propertyPath === null) {
  33250. // String, boolean or float
  33251. var floatValue = parseFloat(value);
  33252. if (value === "true" || value === "false")
  33253. return value === "true";
  33254. else
  33255. return isNaN(floatValue) ? value : floatValue;
  33256. }
  33257. var effectiveTarget = propertyPath.split(".");
  33258. var values = value.split(",");
  33259. // Get effective Target
  33260. for (var i = 0; i < effectiveTarget.length; i++) {
  33261. target = target[effectiveTarget[i]];
  33262. }
  33263. // Return appropriate value with its type
  33264. if (typeof (target) === "boolean")
  33265. return values[0] === "true";
  33266. if (typeof (target) === "string")
  33267. return values[0];
  33268. // Parameters with multiple values such as Vector3 etc.
  33269. var split = new Array();
  33270. for (var i = 0; i < values.length; i++)
  33271. split.push(parseFloat(values[i]));
  33272. if (target instanceof BABYLON.Vector3)
  33273. return BABYLON.Vector3.FromArray(split);
  33274. if (target instanceof BABYLON.Vector4)
  33275. return BABYLON.Vector4.FromArray(split);
  33276. if (target instanceof BABYLON.Color3)
  33277. return BABYLON.Color3.FromArray(split);
  33278. if (target instanceof BABYLON.Color4)
  33279. return BABYLON.Color4.FromArray(split);
  33280. return parseFloat(values[0]);
  33281. };
  33282. // traverse graph per trigger
  33283. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  33284. if (combineArray === void 0) { combineArray = null; }
  33285. if (parsedAction.detached)
  33286. return;
  33287. var parameters = new Array();
  33288. var target = null;
  33289. var propertyPath = null;
  33290. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  33291. // Parameters
  33292. if (parsedAction.type === 2)
  33293. parameters.push(actionManager);
  33294. else
  33295. parameters.push(trigger);
  33296. if (combine) {
  33297. var actions = new Array();
  33298. for (var j = 0; j < parsedAction.combine.length; j++) {
  33299. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  33300. }
  33301. parameters.push(actions);
  33302. }
  33303. else {
  33304. for (var i = 0; i < parsedAction.properties.length; i++) {
  33305. var value = parsedAction.properties[i].value;
  33306. var name = parsedAction.properties[i].name;
  33307. var targetType = parsedAction.properties[i].targetType;
  33308. if (name === "target")
  33309. if (targetType !== null && targetType === "SceneProperties")
  33310. value = target = scene;
  33311. else
  33312. value = target = scene.getNodeByName(value);
  33313. else if (name === "parent")
  33314. value = scene.getNodeByName(value);
  33315. else if (name === "sound")
  33316. value = scene.getSoundByName(value);
  33317. else if (name !== "propertyPath") {
  33318. if (parsedAction.type === 2 && name === "operator")
  33319. value = BABYLON.ValueCondition[value];
  33320. else
  33321. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  33322. }
  33323. else {
  33324. propertyPath = value;
  33325. }
  33326. parameters.push(value);
  33327. }
  33328. }
  33329. if (combineArray === null) {
  33330. parameters.push(condition);
  33331. }
  33332. else {
  33333. parameters.push(null);
  33334. }
  33335. // If interpolate value action
  33336. if (parsedAction.name === "InterpolateValueAction") {
  33337. var param = parameters[parameters.length - 2];
  33338. parameters[parameters.length - 1] = param;
  33339. parameters[parameters.length - 2] = condition;
  33340. }
  33341. // Action or condition(s) and not CombineAction
  33342. var newAction = instanciate(parsedAction.name, parameters);
  33343. if (newAction instanceof BABYLON.Condition && condition !== null) {
  33344. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  33345. if (action)
  33346. action.then(nothing);
  33347. else
  33348. actionManager.registerAction(nothing);
  33349. action = nothing;
  33350. }
  33351. if (combineArray === null) {
  33352. if (newAction instanceof BABYLON.Condition) {
  33353. condition = newAction;
  33354. newAction = action;
  33355. }
  33356. else {
  33357. condition = null;
  33358. if (action)
  33359. action.then(newAction);
  33360. else
  33361. actionManager.registerAction(newAction);
  33362. }
  33363. }
  33364. else {
  33365. combineArray.push(newAction);
  33366. }
  33367. for (var i = 0; i < parsedAction.children.length; i++)
  33368. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  33369. };
  33370. // triggers
  33371. for (var i = 0; i < parsedActions.children.length; i++) {
  33372. var triggerParams;
  33373. var trigger = parsedActions.children[i];
  33374. if (trigger.properties.length > 0) {
  33375. var param = trigger.properties[0].value;
  33376. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  33377. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  33378. }
  33379. else
  33380. triggerParams = BABYLON.ActionManager[trigger.name];
  33381. for (var j = 0; j < trigger.children.length; j++) {
  33382. if (!trigger.detached)
  33383. traverse(trigger.children[j], triggerParams, null, null);
  33384. }
  33385. }
  33386. };
  33387. ActionManager.GetTriggerName = function (trigger) {
  33388. switch (trigger) {
  33389. case 0: return "NothingTrigger";
  33390. case 1: return "OnPickTrigger";
  33391. case 2: return "OnLeftPickTrigger";
  33392. case 3: return "OnRightPickTrigger";
  33393. case 4: return "OnCenterPickTrigger";
  33394. case 5: return "OnPickDownTrigger";
  33395. case 6: return "OnPickUpTrigger";
  33396. case 7: return "OnLongPressTrigger";
  33397. case 8: return "OnPointerOverTrigger";
  33398. case 9: return "OnPointerOutTrigger";
  33399. case 10: return "OnEveryFrameTrigger";
  33400. case 11: return "OnIntersectionEnterTrigger";
  33401. case 12: return "OnIntersectionExitTrigger";
  33402. case 13: return "OnKeyDownTrigger";
  33403. case 14: return "OnKeyUpTrigger";
  33404. case 15: return "OnPickOutTrigger";
  33405. default: return "";
  33406. }
  33407. };
  33408. // Statics
  33409. ActionManager._NothingTrigger = 0;
  33410. ActionManager._OnPickTrigger = 1;
  33411. ActionManager._OnLeftPickTrigger = 2;
  33412. ActionManager._OnRightPickTrigger = 3;
  33413. ActionManager._OnCenterPickTrigger = 4;
  33414. ActionManager._OnPickDownTrigger = 5;
  33415. ActionManager._OnPickUpTrigger = 6;
  33416. ActionManager._OnLongPressTrigger = 7;
  33417. ActionManager._OnPointerOverTrigger = 8;
  33418. ActionManager._OnPointerOutTrigger = 9;
  33419. ActionManager._OnEveryFrameTrigger = 10;
  33420. ActionManager._OnIntersectionEnterTrigger = 11;
  33421. ActionManager._OnIntersectionExitTrigger = 12;
  33422. ActionManager._OnKeyDownTrigger = 13;
  33423. ActionManager._OnKeyUpTrigger = 14;
  33424. ActionManager._OnPickOutTrigger = 15;
  33425. ActionManager.DragMovementThreshold = 10; // in pixels
  33426. ActionManager.LongPressDelay = 500; // in milliseconds
  33427. return ActionManager;
  33428. })();
  33429. BABYLON.ActionManager = ActionManager;
  33430. })(BABYLON || (BABYLON = {}));
  33431. var BABYLON;
  33432. (function (BABYLON) {
  33433. var InterpolateValueAction = (function (_super) {
  33434. __extends(InterpolateValueAction, _super);
  33435. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  33436. if (duration === void 0) { duration = 1000; }
  33437. _super.call(this, triggerOptions, condition);
  33438. this.propertyPath = propertyPath;
  33439. this.value = value;
  33440. this.duration = duration;
  33441. this.stopOtherAnimations = stopOtherAnimations;
  33442. this.onInterpolationDone = onInterpolationDone;
  33443. this._target = this._effectiveTarget = target;
  33444. }
  33445. InterpolateValueAction.prototype._prepare = function () {
  33446. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33447. this._property = this._getProperty(this.propertyPath);
  33448. };
  33449. InterpolateValueAction.prototype.execute = function () {
  33450. var scene = this._actionManager.getScene();
  33451. var keys = [
  33452. {
  33453. frame: 0,
  33454. value: this._effectiveTarget[this._property]
  33455. }, {
  33456. frame: 100,
  33457. value: this.value
  33458. }
  33459. ];
  33460. var dataType;
  33461. if (typeof this.value === "number") {
  33462. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  33463. }
  33464. else if (this.value instanceof BABYLON.Color3) {
  33465. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  33466. }
  33467. else if (this.value instanceof BABYLON.Vector3) {
  33468. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  33469. }
  33470. else if (this.value instanceof BABYLON.Matrix) {
  33471. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  33472. }
  33473. else if (this.value instanceof BABYLON.Quaternion) {
  33474. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  33475. }
  33476. else {
  33477. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  33478. return;
  33479. }
  33480. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  33481. animation.setKeys(keys);
  33482. if (this.stopOtherAnimations) {
  33483. scene.stopAnimation(this._effectiveTarget);
  33484. }
  33485. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  33486. };
  33487. InterpolateValueAction.prototype.serialize = function (parent) {
  33488. return _super.prototype._serialize.call(this, {
  33489. name: "InterpolateValueAction",
  33490. properties: [
  33491. BABYLON.Action._GetTargetProperty(this._target),
  33492. { name: "propertyPath", value: this.propertyPath },
  33493. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33494. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  33495. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  33496. ]
  33497. }, parent);
  33498. };
  33499. return InterpolateValueAction;
  33500. })(BABYLON.Action);
  33501. BABYLON.InterpolateValueAction = InterpolateValueAction;
  33502. })(BABYLON || (BABYLON = {}));
  33503. var BABYLON;
  33504. (function (BABYLON) {
  33505. var SwitchBooleanAction = (function (_super) {
  33506. __extends(SwitchBooleanAction, _super);
  33507. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  33508. _super.call(this, triggerOptions, condition);
  33509. this.propertyPath = propertyPath;
  33510. this._target = this._effectiveTarget = target;
  33511. }
  33512. SwitchBooleanAction.prototype._prepare = function () {
  33513. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33514. this._property = this._getProperty(this.propertyPath);
  33515. };
  33516. SwitchBooleanAction.prototype.execute = function () {
  33517. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  33518. };
  33519. SwitchBooleanAction.prototype.serialize = function (parent) {
  33520. return _super.prototype._serialize.call(this, {
  33521. name: "SwitchBooleanAction",
  33522. properties: [
  33523. BABYLON.Action._GetTargetProperty(this._target),
  33524. { name: "propertyPath", value: this.propertyPath }
  33525. ]
  33526. }, parent);
  33527. };
  33528. return SwitchBooleanAction;
  33529. })(BABYLON.Action);
  33530. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  33531. var SetStateAction = (function (_super) {
  33532. __extends(SetStateAction, _super);
  33533. function SetStateAction(triggerOptions, target, value, condition) {
  33534. _super.call(this, triggerOptions, condition);
  33535. this.value = value;
  33536. this._target = target;
  33537. }
  33538. SetStateAction.prototype.execute = function () {
  33539. this._target.state = this.value;
  33540. };
  33541. SetStateAction.prototype.serialize = function (parent) {
  33542. return _super.prototype._serialize.call(this, {
  33543. name: "SetStateAction",
  33544. properties: [
  33545. BABYLON.Action._GetTargetProperty(this._target),
  33546. { name: "value", value: this.value }
  33547. ]
  33548. }, parent);
  33549. };
  33550. return SetStateAction;
  33551. })(BABYLON.Action);
  33552. BABYLON.SetStateAction = SetStateAction;
  33553. var SetValueAction = (function (_super) {
  33554. __extends(SetValueAction, _super);
  33555. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  33556. _super.call(this, triggerOptions, condition);
  33557. this.propertyPath = propertyPath;
  33558. this.value = value;
  33559. this._target = this._effectiveTarget = target;
  33560. }
  33561. SetValueAction.prototype._prepare = function () {
  33562. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33563. this._property = this._getProperty(this.propertyPath);
  33564. };
  33565. SetValueAction.prototype.execute = function () {
  33566. this._effectiveTarget[this._property] = this.value;
  33567. if (this._target.markAsDirty) {
  33568. this._target.markAsDirty(this._property);
  33569. }
  33570. };
  33571. SetValueAction.prototype.serialize = function (parent) {
  33572. return _super.prototype._serialize.call(this, {
  33573. name: "SetValueAction",
  33574. properties: [
  33575. BABYLON.Action._GetTargetProperty(this._target),
  33576. { name: "propertyPath", value: this.propertyPath },
  33577. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33578. ]
  33579. }, parent);
  33580. };
  33581. return SetValueAction;
  33582. })(BABYLON.Action);
  33583. BABYLON.SetValueAction = SetValueAction;
  33584. var IncrementValueAction = (function (_super) {
  33585. __extends(IncrementValueAction, _super);
  33586. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  33587. _super.call(this, triggerOptions, condition);
  33588. this.propertyPath = propertyPath;
  33589. this.value = value;
  33590. this._target = this._effectiveTarget = target;
  33591. }
  33592. IncrementValueAction.prototype._prepare = function () {
  33593. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33594. this._property = this._getProperty(this.propertyPath);
  33595. if (typeof this._effectiveTarget[this._property] !== "number") {
  33596. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  33597. }
  33598. };
  33599. IncrementValueAction.prototype.execute = function () {
  33600. this._effectiveTarget[this._property] += this.value;
  33601. if (this._target.markAsDirty) {
  33602. this._target.markAsDirty(this._property);
  33603. }
  33604. };
  33605. IncrementValueAction.prototype.serialize = function (parent) {
  33606. return _super.prototype._serialize.call(this, {
  33607. name: "IncrementValueAction",
  33608. properties: [
  33609. BABYLON.Action._GetTargetProperty(this._target),
  33610. { name: "propertyPath", value: this.propertyPath },
  33611. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33612. ]
  33613. }, parent);
  33614. };
  33615. return IncrementValueAction;
  33616. })(BABYLON.Action);
  33617. BABYLON.IncrementValueAction = IncrementValueAction;
  33618. var PlayAnimationAction = (function (_super) {
  33619. __extends(PlayAnimationAction, _super);
  33620. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  33621. _super.call(this, triggerOptions, condition);
  33622. this.from = from;
  33623. this.to = to;
  33624. this.loop = loop;
  33625. this._target = target;
  33626. }
  33627. PlayAnimationAction.prototype._prepare = function () {
  33628. };
  33629. PlayAnimationAction.prototype.execute = function () {
  33630. var scene = this._actionManager.getScene();
  33631. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  33632. };
  33633. PlayAnimationAction.prototype.serialize = function (parent) {
  33634. return _super.prototype._serialize.call(this, {
  33635. name: "PlayAnimationAction",
  33636. properties: [
  33637. BABYLON.Action._GetTargetProperty(this._target),
  33638. { name: "from", value: String(this.from) },
  33639. { name: "to", value: String(this.to) },
  33640. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  33641. ]
  33642. }, parent);
  33643. };
  33644. return PlayAnimationAction;
  33645. })(BABYLON.Action);
  33646. BABYLON.PlayAnimationAction = PlayAnimationAction;
  33647. var StopAnimationAction = (function (_super) {
  33648. __extends(StopAnimationAction, _super);
  33649. function StopAnimationAction(triggerOptions, target, condition) {
  33650. _super.call(this, triggerOptions, condition);
  33651. this._target = target;
  33652. }
  33653. StopAnimationAction.prototype._prepare = function () {
  33654. };
  33655. StopAnimationAction.prototype.execute = function () {
  33656. var scene = this._actionManager.getScene();
  33657. scene.stopAnimation(this._target);
  33658. };
  33659. StopAnimationAction.prototype.serialize = function (parent) {
  33660. return _super.prototype._serialize.call(this, {
  33661. name: "StopAnimationAction",
  33662. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  33663. }, parent);
  33664. };
  33665. return StopAnimationAction;
  33666. })(BABYLON.Action);
  33667. BABYLON.StopAnimationAction = StopAnimationAction;
  33668. var DoNothingAction = (function (_super) {
  33669. __extends(DoNothingAction, _super);
  33670. function DoNothingAction(triggerOptions, condition) {
  33671. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  33672. _super.call(this, triggerOptions, condition);
  33673. }
  33674. DoNothingAction.prototype.execute = function () {
  33675. };
  33676. DoNothingAction.prototype.serialize = function (parent) {
  33677. return _super.prototype._serialize.call(this, {
  33678. name: "DoNothingAction",
  33679. properties: []
  33680. }, parent);
  33681. };
  33682. return DoNothingAction;
  33683. })(BABYLON.Action);
  33684. BABYLON.DoNothingAction = DoNothingAction;
  33685. var CombineAction = (function (_super) {
  33686. __extends(CombineAction, _super);
  33687. function CombineAction(triggerOptions, children, condition) {
  33688. _super.call(this, triggerOptions, condition);
  33689. this.children = children;
  33690. }
  33691. CombineAction.prototype._prepare = function () {
  33692. for (var index = 0; index < this.children.length; index++) {
  33693. this.children[index]._actionManager = this._actionManager;
  33694. this.children[index]._prepare();
  33695. }
  33696. };
  33697. CombineAction.prototype.execute = function (evt) {
  33698. for (var index = 0; index < this.children.length; index++) {
  33699. this.children[index].execute(evt);
  33700. }
  33701. };
  33702. CombineAction.prototype.serialize = function (parent) {
  33703. var serializationObject = _super.prototype._serialize.call(this, {
  33704. name: "CombineAction",
  33705. properties: [],
  33706. combine: []
  33707. }, parent);
  33708. for (var i = 0; i < this.children.length; i++) {
  33709. serializationObject.combine.push(this.children[i].serialize(null));
  33710. }
  33711. return serializationObject;
  33712. };
  33713. return CombineAction;
  33714. })(BABYLON.Action);
  33715. BABYLON.CombineAction = CombineAction;
  33716. var ExecuteCodeAction = (function (_super) {
  33717. __extends(ExecuteCodeAction, _super);
  33718. function ExecuteCodeAction(triggerOptions, func, condition) {
  33719. _super.call(this, triggerOptions, condition);
  33720. this.func = func;
  33721. }
  33722. ExecuteCodeAction.prototype.execute = function (evt) {
  33723. this.func(evt);
  33724. };
  33725. return ExecuteCodeAction;
  33726. })(BABYLON.Action);
  33727. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  33728. var SetParentAction = (function (_super) {
  33729. __extends(SetParentAction, _super);
  33730. function SetParentAction(triggerOptions, target, parent, condition) {
  33731. _super.call(this, triggerOptions, condition);
  33732. this._target = target;
  33733. this._parent = parent;
  33734. }
  33735. SetParentAction.prototype._prepare = function () {
  33736. };
  33737. SetParentAction.prototype.execute = function () {
  33738. if (this._target.parent === this._parent) {
  33739. return;
  33740. }
  33741. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  33742. invertParentWorldMatrix.invert();
  33743. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  33744. this._target.parent = this._parent;
  33745. };
  33746. SetParentAction.prototype.serialize = function (parent) {
  33747. return _super.prototype._serialize.call(this, {
  33748. name: "SetParentAction",
  33749. properties: [
  33750. BABYLON.Action._GetTargetProperty(this._target),
  33751. BABYLON.Action._GetTargetProperty(this._parent),
  33752. ]
  33753. }, parent);
  33754. };
  33755. return SetParentAction;
  33756. })(BABYLON.Action);
  33757. BABYLON.SetParentAction = SetParentAction;
  33758. var PlaySoundAction = (function (_super) {
  33759. __extends(PlaySoundAction, _super);
  33760. function PlaySoundAction(triggerOptions, sound, condition) {
  33761. _super.call(this, triggerOptions, condition);
  33762. this._sound = sound;
  33763. }
  33764. PlaySoundAction.prototype._prepare = function () {
  33765. };
  33766. PlaySoundAction.prototype.execute = function () {
  33767. if (this._sound !== undefined)
  33768. this._sound.play();
  33769. };
  33770. PlaySoundAction.prototype.serialize = function (parent) {
  33771. return _super.prototype._serialize.call(this, {
  33772. name: "PlaySoundAction",
  33773. properties: [{ name: "sound", value: this._sound.name }]
  33774. }, parent);
  33775. };
  33776. return PlaySoundAction;
  33777. })(BABYLON.Action);
  33778. BABYLON.PlaySoundAction = PlaySoundAction;
  33779. var StopSoundAction = (function (_super) {
  33780. __extends(StopSoundAction, _super);
  33781. function StopSoundAction(triggerOptions, sound, condition) {
  33782. _super.call(this, triggerOptions, condition);
  33783. this._sound = sound;
  33784. }
  33785. StopSoundAction.prototype._prepare = function () {
  33786. };
  33787. StopSoundAction.prototype.execute = function () {
  33788. if (this._sound !== undefined)
  33789. this._sound.stop();
  33790. };
  33791. StopSoundAction.prototype.serialize = function (parent) {
  33792. return _super.prototype._serialize.call(this, {
  33793. name: "StopSoundAction",
  33794. properties: [{ name: "sound", value: this._sound.name }]
  33795. }, parent);
  33796. };
  33797. return StopSoundAction;
  33798. })(BABYLON.Action);
  33799. BABYLON.StopSoundAction = StopSoundAction;
  33800. })(BABYLON || (BABYLON = {}));
  33801. var BABYLON;
  33802. (function (BABYLON) {
  33803. var Geometry = (function () {
  33804. function Geometry(id, scene, vertexData, updatable, mesh) {
  33805. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33806. this._totalVertices = 0;
  33807. this._isDisposed = false;
  33808. this.id = id;
  33809. this._engine = scene.getEngine();
  33810. this._meshes = [];
  33811. this._scene = scene;
  33812. //Init vertex buffer cache
  33813. this._vertexBuffers = {};
  33814. this._indices = [];
  33815. // vertexData
  33816. if (vertexData) {
  33817. this.setAllVerticesData(vertexData, updatable);
  33818. }
  33819. else {
  33820. this._totalVertices = 0;
  33821. this._indices = [];
  33822. }
  33823. // applyToMesh
  33824. if (mesh) {
  33825. if (mesh instanceof BABYLON.LinesMesh) {
  33826. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33827. this.updateExtend();
  33828. }
  33829. this.applyToMesh(mesh);
  33830. mesh.computeWorldMatrix(true);
  33831. }
  33832. }
  33833. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33834. /**
  33835. * 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
  33836. * @returns The Bias Vector
  33837. */
  33838. get: function () {
  33839. return this._boundingBias;
  33840. },
  33841. set: function (value) {
  33842. if (this._boundingBias && this._boundingBias.equals(value)) {
  33843. return;
  33844. }
  33845. this._boundingBias = value.clone();
  33846. this.updateBoundingInfo(true, null);
  33847. },
  33848. enumerable: true,
  33849. configurable: true
  33850. });
  33851. Object.defineProperty(Geometry.prototype, "extend", {
  33852. get: function () {
  33853. return this._extend;
  33854. },
  33855. enumerable: true,
  33856. configurable: true
  33857. });
  33858. Geometry.prototype.getScene = function () {
  33859. return this._scene;
  33860. };
  33861. Geometry.prototype.getEngine = function () {
  33862. return this._engine;
  33863. };
  33864. Geometry.prototype.isReady = function () {
  33865. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  33866. };
  33867. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33868. vertexData.applyToGeometry(this, updatable);
  33869. this.notifyUpdate();
  33870. };
  33871. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33872. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  33873. this.setVerticesBuffer(buffer);
  33874. };
  33875. Geometry.prototype.setVerticesBuffer = function (buffer) {
  33876. var kind = buffer.getKind();
  33877. if (this._vertexBuffers[kind]) {
  33878. this._vertexBuffers[kind].dispose();
  33879. }
  33880. this._vertexBuffers[kind] = buffer;
  33881. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33882. var data = buffer.getData();
  33883. var stride = buffer.getStrideSize();
  33884. this._totalVertices = data.length / stride;
  33885. this.updateExtend(data, stride);
  33886. var meshes = this._meshes;
  33887. var numOfMeshes = meshes.length;
  33888. for (var index = 0; index < numOfMeshes; index++) {
  33889. var mesh = meshes[index];
  33890. mesh._resetPointsArrayCache();
  33891. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33892. mesh._createGlobalSubMesh();
  33893. mesh.computeWorldMatrix(true);
  33894. }
  33895. }
  33896. this.notifyUpdate(kind);
  33897. };
  33898. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  33899. var vertexBuffer = this.getVertexBuffer(kind);
  33900. if (!vertexBuffer) {
  33901. return;
  33902. }
  33903. vertexBuffer.updateDirectly(data, offset);
  33904. this.notifyUpdate(kind);
  33905. };
  33906. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  33907. var vertexBuffer = this.getVertexBuffer(kind);
  33908. if (!vertexBuffer) {
  33909. return;
  33910. }
  33911. vertexBuffer.update(data);
  33912. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33913. var stride = vertexBuffer.getStrideSize();
  33914. this._totalVertices = data.length / stride;
  33915. this.updateBoundingInfo(updateExtends, data);
  33916. }
  33917. this.notifyUpdate(kind);
  33918. };
  33919. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  33920. if (updateExtends) {
  33921. this.updateExtend(data);
  33922. }
  33923. var meshes = this._meshes;
  33924. var numOfMeshes = meshes.length;
  33925. for (var index = 0; index < numOfMeshes; index++) {
  33926. var mesh = meshes[index];
  33927. mesh._resetPointsArrayCache();
  33928. if (updateExtends) {
  33929. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33930. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33931. var subMesh = mesh.subMeshes[subIndex];
  33932. subMesh.refreshBoundingInfo();
  33933. }
  33934. }
  33935. }
  33936. };
  33937. Geometry.prototype.getTotalVertices = function () {
  33938. if (!this.isReady()) {
  33939. return 0;
  33940. }
  33941. return this._totalVertices;
  33942. };
  33943. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  33944. var vertexBuffer = this.getVertexBuffer(kind);
  33945. if (!vertexBuffer) {
  33946. return null;
  33947. }
  33948. var orig = vertexBuffer.getData();
  33949. if (!copyWhenShared || this._meshes.length === 1) {
  33950. return orig;
  33951. }
  33952. else {
  33953. var len = orig.length;
  33954. var copy = [];
  33955. for (var i = 0; i < len; i++) {
  33956. copy.push(orig[i]);
  33957. }
  33958. return copy;
  33959. }
  33960. };
  33961. Geometry.prototype.getVertexBuffer = function (kind) {
  33962. if (!this.isReady()) {
  33963. return null;
  33964. }
  33965. return this._vertexBuffers[kind];
  33966. };
  33967. Geometry.prototype.getVertexBuffers = function () {
  33968. if (!this.isReady()) {
  33969. return null;
  33970. }
  33971. return this._vertexBuffers;
  33972. };
  33973. Geometry.prototype.isVerticesDataPresent = function (kind) {
  33974. if (!this._vertexBuffers) {
  33975. if (this._delayInfo) {
  33976. return this._delayInfo.indexOf(kind) !== -1;
  33977. }
  33978. return false;
  33979. }
  33980. return this._vertexBuffers[kind] !== undefined;
  33981. };
  33982. Geometry.prototype.getVerticesDataKinds = function () {
  33983. var result = [];
  33984. var kind;
  33985. if (!this._vertexBuffers && this._delayInfo) {
  33986. for (kind in this._delayInfo) {
  33987. result.push(kind);
  33988. }
  33989. }
  33990. else {
  33991. for (kind in this._vertexBuffers) {
  33992. result.push(kind);
  33993. }
  33994. }
  33995. return result;
  33996. };
  33997. Geometry.prototype.setIndices = function (indices, totalVertices) {
  33998. if (this._indexBuffer) {
  33999. this._engine._releaseBuffer(this._indexBuffer);
  34000. }
  34001. this._indices = indices;
  34002. if (this._meshes.length !== 0 && this._indices) {
  34003. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34004. }
  34005. if (totalVertices !== undefined) {
  34006. this._totalVertices = totalVertices;
  34007. }
  34008. var meshes = this._meshes;
  34009. var numOfMeshes = meshes.length;
  34010. for (var index = 0; index < numOfMeshes; index++) {
  34011. meshes[index]._createGlobalSubMesh();
  34012. }
  34013. this.notifyUpdate();
  34014. };
  34015. Geometry.prototype.getTotalIndices = function () {
  34016. if (!this.isReady()) {
  34017. return 0;
  34018. }
  34019. return this._indices.length;
  34020. };
  34021. Geometry.prototype.getIndices = function (copyWhenShared) {
  34022. if (!this.isReady()) {
  34023. return null;
  34024. }
  34025. var orig = this._indices;
  34026. if (!copyWhenShared || this._meshes.length === 1) {
  34027. return orig;
  34028. }
  34029. else {
  34030. var len = orig.length;
  34031. var copy = [];
  34032. for (var i = 0; i < len; i++) {
  34033. copy.push(orig[i]);
  34034. }
  34035. return copy;
  34036. }
  34037. };
  34038. Geometry.prototype.getIndexBuffer = function () {
  34039. if (!this.isReady()) {
  34040. return null;
  34041. }
  34042. return this._indexBuffer;
  34043. };
  34044. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34045. var meshes = this._meshes;
  34046. var index = meshes.indexOf(mesh);
  34047. if (index === -1) {
  34048. return;
  34049. }
  34050. for (var kind in this._vertexBuffers) {
  34051. this._vertexBuffers[kind].dispose();
  34052. }
  34053. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  34054. this._indexBuffer = null;
  34055. }
  34056. meshes.splice(index, 1);
  34057. mesh._geometry = null;
  34058. if (meshes.length === 0 && shouldDispose) {
  34059. this.dispose();
  34060. }
  34061. };
  34062. Geometry.prototype.applyToMesh = function (mesh) {
  34063. if (mesh._geometry === this) {
  34064. return;
  34065. }
  34066. var previousGeometry = mesh._geometry;
  34067. if (previousGeometry) {
  34068. previousGeometry.releaseForMesh(mesh);
  34069. }
  34070. var meshes = this._meshes;
  34071. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34072. mesh._geometry = this;
  34073. this._scene.pushGeometry(this);
  34074. meshes.push(mesh);
  34075. if (this.isReady()) {
  34076. this._applyToMesh(mesh);
  34077. }
  34078. else {
  34079. mesh._boundingInfo = this._boundingInfo;
  34080. }
  34081. };
  34082. Geometry.prototype.updateExtend = function (data, stride) {
  34083. if (data === void 0) { data = null; }
  34084. if (!data) {
  34085. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34086. }
  34087. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34088. };
  34089. Geometry.prototype._applyToMesh = function (mesh) {
  34090. var numOfMeshes = this._meshes.length;
  34091. // vertexBuffers
  34092. for (var kind in this._vertexBuffers) {
  34093. if (numOfMeshes === 1) {
  34094. this._vertexBuffers[kind].create();
  34095. }
  34096. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  34097. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34098. mesh._resetPointsArrayCache();
  34099. if (!this._extend) {
  34100. this.updateExtend(this._vertexBuffers[kind].getData());
  34101. }
  34102. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34103. mesh._createGlobalSubMesh();
  34104. //bounding info was just created again, world matrix should be applied again.
  34105. mesh._updateBoundingInfo();
  34106. }
  34107. }
  34108. // indexBuffer
  34109. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34110. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34111. }
  34112. if (this._indexBuffer) {
  34113. this._indexBuffer.references = numOfMeshes;
  34114. }
  34115. };
  34116. Geometry.prototype.notifyUpdate = function (kind) {
  34117. if (this.onGeometryUpdated) {
  34118. this.onGeometryUpdated(this, kind);
  34119. }
  34120. };
  34121. Geometry.prototype.load = function (scene, onLoaded) {
  34122. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34123. return;
  34124. }
  34125. if (this.isReady()) {
  34126. if (onLoaded) {
  34127. onLoaded();
  34128. }
  34129. return;
  34130. }
  34131. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34132. this._queueLoad(scene, onLoaded);
  34133. };
  34134. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34135. var _this = this;
  34136. scene._addPendingData(this);
  34137. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  34138. _this._delayLoadingFunction(JSON.parse(data), _this);
  34139. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34140. _this._delayInfo = [];
  34141. scene._removePendingData(_this);
  34142. var meshes = _this._meshes;
  34143. var numOfMeshes = meshes.length;
  34144. for (var index = 0; index < numOfMeshes; index++) {
  34145. _this._applyToMesh(meshes[index]);
  34146. }
  34147. if (onLoaded) {
  34148. onLoaded();
  34149. }
  34150. }, function () { }, scene.database);
  34151. };
  34152. /**
  34153. * Invert the geometry to move from a right handed system to a left handed one.
  34154. */
  34155. Geometry.prototype.toLeftHanded = function () {
  34156. // Flip faces
  34157. var tIndices = this.getIndices(false);
  34158. if (tIndices != null && tIndices.length > 0) {
  34159. for (var i = 0; i < tIndices.length; i += 3) {
  34160. var tTemp = tIndices[i + 0];
  34161. tIndices[i + 0] = tIndices[i + 2];
  34162. tIndices[i + 2] = tTemp;
  34163. }
  34164. this.setIndices(tIndices);
  34165. }
  34166. // Negate position.z
  34167. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34168. if (tPositions != null && tPositions.length > 0) {
  34169. for (var i = 0; i < tPositions.length; i += 3) {
  34170. tPositions[i + 2] = -tPositions[i + 2];
  34171. }
  34172. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34173. }
  34174. // Negate normal.z
  34175. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34176. if (tNormals != null && tNormals.length > 0) {
  34177. for (var i = 0; i < tNormals.length; i += 3) {
  34178. tNormals[i + 2] = -tNormals[i + 2];
  34179. }
  34180. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34181. }
  34182. };
  34183. Geometry.prototype.isDisposed = function () {
  34184. return this._isDisposed;
  34185. };
  34186. Geometry.prototype.dispose = function () {
  34187. var meshes = this._meshes;
  34188. var numOfMeshes = meshes.length;
  34189. var index;
  34190. for (index = 0; index < numOfMeshes; index++) {
  34191. this.releaseForMesh(meshes[index]);
  34192. }
  34193. this._meshes = [];
  34194. for (var kind in this._vertexBuffers) {
  34195. this._vertexBuffers[kind].dispose();
  34196. }
  34197. this._vertexBuffers = {};
  34198. this._totalVertices = 0;
  34199. if (this._indexBuffer) {
  34200. this._engine._releaseBuffer(this._indexBuffer);
  34201. }
  34202. this._indexBuffer = null;
  34203. this._indices = [];
  34204. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34205. this.delayLoadingFile = null;
  34206. this._delayLoadingFunction = null;
  34207. this._delayInfo = [];
  34208. this._boundingInfo = null;
  34209. this._scene.removeGeometry(this);
  34210. this._isDisposed = true;
  34211. };
  34212. Geometry.prototype.copy = function (id) {
  34213. var vertexData = new BABYLON.VertexData();
  34214. vertexData.indices = [];
  34215. var indices = this.getIndices();
  34216. for (var index = 0; index < indices.length; index++) {
  34217. vertexData.indices.push(indices[index]);
  34218. }
  34219. var updatable = false;
  34220. var stopChecking = false;
  34221. var kind;
  34222. for (kind in this._vertexBuffers) {
  34223. // using slice() to make a copy of the array and not just reference it
  34224. var data = this.getVerticesData(kind);
  34225. if (data instanceof Float32Array) {
  34226. vertexData.set(new Float32Array(data), kind);
  34227. }
  34228. else {
  34229. vertexData.set(data.slice(0), kind);
  34230. }
  34231. if (!stopChecking) {
  34232. updatable = this.getVertexBuffer(kind).isUpdatable();
  34233. stopChecking = !updatable;
  34234. }
  34235. }
  34236. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  34237. geometry.delayLoadState = this.delayLoadState;
  34238. geometry.delayLoadingFile = this.delayLoadingFile;
  34239. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34240. for (kind in this._delayInfo) {
  34241. geometry._delayInfo = geometry._delayInfo || [];
  34242. geometry._delayInfo.push(kind);
  34243. }
  34244. // Bounding info
  34245. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34246. return geometry;
  34247. };
  34248. Geometry.prototype.serialize = function () {
  34249. var serializationObject = {};
  34250. serializationObject.id = this.id;
  34251. if (BABYLON.Tags.HasTags(this)) {
  34252. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34253. }
  34254. return serializationObject;
  34255. };
  34256. Geometry.prototype.serializeVerticeData = function () {
  34257. var serializationObject = this.serialize();
  34258. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34259. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34260. }
  34261. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34262. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34263. }
  34264. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34265. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34266. }
  34267. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34268. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  34269. }
  34270. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34271. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  34272. }
  34273. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34274. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  34275. }
  34276. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34277. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  34278. }
  34279. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34280. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  34281. }
  34282. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34283. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34284. }
  34285. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34286. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34287. serializationObject.matricesIndices._isExpanded = true;
  34288. }
  34289. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34290. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34291. }
  34292. serializationObject.indices = this.getIndices();
  34293. return serializationObject;
  34294. };
  34295. // Statics
  34296. Geometry.ExtractFromMesh = function (mesh, id) {
  34297. var geometry = mesh._geometry;
  34298. if (!geometry) {
  34299. return null;
  34300. }
  34301. return geometry.copy(id);
  34302. };
  34303. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34304. // be aware Math.random() could cause collisions
  34305. Geometry.RandomId = function () {
  34306. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  34307. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  34308. return v.toString(16);
  34309. });
  34310. };
  34311. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  34312. var scene = mesh.getScene();
  34313. // Geometry
  34314. var geometryId = parsedGeometry.geometryId;
  34315. if (geometryId) {
  34316. var geometry = scene.getGeometryByID(geometryId);
  34317. if (geometry) {
  34318. geometry.applyToMesh(mesh);
  34319. }
  34320. }
  34321. else if (parsedGeometry instanceof ArrayBuffer) {
  34322. var binaryInfo = mesh._binaryInfo;
  34323. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34324. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34325. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34326. }
  34327. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34328. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34329. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34330. }
  34331. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34332. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34333. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34334. }
  34335. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34336. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34337. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34338. }
  34339. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34340. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34341. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34342. }
  34343. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34344. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34345. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34346. }
  34347. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34348. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34349. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34350. }
  34351. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34352. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34353. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34354. }
  34355. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34356. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34357. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34358. }
  34359. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34360. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34361. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34362. }
  34363. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34364. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34365. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34366. }
  34367. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34368. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34369. mesh.setIndices(indicesData);
  34370. }
  34371. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34372. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34373. mesh.subMeshes = [];
  34374. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34375. var materialIndex = subMeshesData[(i * 5) + 0];
  34376. var verticesStart = subMeshesData[(i * 5) + 1];
  34377. var verticesCount = subMeshesData[(i * 5) + 2];
  34378. var indexStart = subMeshesData[(i * 5) + 3];
  34379. var indexCount = subMeshesData[(i * 5) + 4];
  34380. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34381. }
  34382. }
  34383. }
  34384. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34385. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  34386. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  34387. if (parsedGeometry.uvs) {
  34388. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  34389. }
  34390. if (parsedGeometry.uvs2) {
  34391. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  34392. }
  34393. if (parsedGeometry.uvs3) {
  34394. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  34395. }
  34396. if (parsedGeometry.uvs4) {
  34397. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  34398. }
  34399. if (parsedGeometry.uvs5) {
  34400. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  34401. }
  34402. if (parsedGeometry.uvs6) {
  34403. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  34404. }
  34405. if (parsedGeometry.colors) {
  34406. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  34407. }
  34408. if (parsedGeometry.matricesIndices) {
  34409. if (!parsedGeometry.matricesIndices._isExpanded) {
  34410. var floatIndices = [];
  34411. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34412. var matricesIndex = parsedGeometry.matricesIndices[i];
  34413. floatIndices.push(matricesIndex & 0x000000FF);
  34414. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34415. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34416. floatIndices.push(matricesIndex >> 24);
  34417. }
  34418. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  34419. }
  34420. else {
  34421. delete parsedGeometry.matricesIndices._isExpanded;
  34422. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  34423. }
  34424. }
  34425. if (parsedGeometry.matricesIndicesExtra) {
  34426. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34427. var floatIndices = [];
  34428. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34429. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34430. floatIndices.push(matricesIndex & 0x000000FF);
  34431. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34432. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34433. floatIndices.push(matricesIndex >> 24);
  34434. }
  34435. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  34436. }
  34437. else {
  34438. delete parsedGeometry.matricesIndices._isExpanded;
  34439. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  34440. }
  34441. }
  34442. if (parsedGeometry.matricesWeights) {
  34443. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  34444. }
  34445. if (parsedGeometry.matricesWeightsExtra) {
  34446. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  34447. }
  34448. mesh.setIndices(parsedGeometry.indices);
  34449. }
  34450. // SubMeshes
  34451. if (parsedGeometry.subMeshes) {
  34452. mesh.subMeshes = [];
  34453. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34454. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34455. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34456. }
  34457. }
  34458. // Flat shading
  34459. if (mesh._shouldGenerateFlatShading) {
  34460. mesh.convertToFlatShadedMesh();
  34461. delete mesh._shouldGenerateFlatShading;
  34462. }
  34463. // Update
  34464. mesh.computeWorldMatrix(true);
  34465. // Octree
  34466. if (scene['_selectionOctree']) {
  34467. scene['_selectionOctree'].addMesh(mesh);
  34468. }
  34469. };
  34470. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  34471. if (scene.getGeometryByID(parsedVertexData.id)) {
  34472. return null; // null since geometry could be something else than a box...
  34473. }
  34474. var geometry = new Geometry(parsedVertexData.id, scene);
  34475. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  34476. if (parsedVertexData.delayLoadingFile) {
  34477. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34478. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  34479. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  34480. geometry._delayInfo = [];
  34481. if (parsedVertexData.hasUVs) {
  34482. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34483. }
  34484. if (parsedVertexData.hasUVs2) {
  34485. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34486. }
  34487. if (parsedVertexData.hasUVs3) {
  34488. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34489. }
  34490. if (parsedVertexData.hasUVs4) {
  34491. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34492. }
  34493. if (parsedVertexData.hasUVs5) {
  34494. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34495. }
  34496. if (parsedVertexData.hasUVs6) {
  34497. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34498. }
  34499. if (parsedVertexData.hasColors) {
  34500. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34501. }
  34502. if (parsedVertexData.hasMatricesIndices) {
  34503. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34504. }
  34505. if (parsedVertexData.hasMatricesWeights) {
  34506. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34507. }
  34508. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  34509. }
  34510. else {
  34511. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  34512. }
  34513. scene.pushGeometry(geometry, true);
  34514. return geometry;
  34515. };
  34516. return Geometry;
  34517. })();
  34518. BABYLON.Geometry = Geometry;
  34519. /////// Primitives //////////////////////////////////////////////
  34520. var Geometry;
  34521. (function (Geometry) {
  34522. var Primitives;
  34523. (function (Primitives) {
  34524. /// Abstract class
  34525. var _Primitive = (function (_super) {
  34526. __extends(_Primitive, _super);
  34527. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  34528. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  34529. this._canBeRegenerated = _canBeRegenerated;
  34530. this._beingRegenerated = true;
  34531. this.regenerate();
  34532. this._beingRegenerated = false;
  34533. }
  34534. _Primitive.prototype.canBeRegenerated = function () {
  34535. return this._canBeRegenerated;
  34536. };
  34537. _Primitive.prototype.regenerate = function () {
  34538. if (!this._canBeRegenerated) {
  34539. return;
  34540. }
  34541. this._beingRegenerated = true;
  34542. this.setAllVerticesData(this._regenerateVertexData(), false);
  34543. this._beingRegenerated = false;
  34544. };
  34545. _Primitive.prototype.asNewGeometry = function (id) {
  34546. return _super.prototype.copy.call(this, id);
  34547. };
  34548. // overrides
  34549. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  34550. if (!this._beingRegenerated) {
  34551. return;
  34552. }
  34553. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  34554. };
  34555. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  34556. if (!this._beingRegenerated) {
  34557. return;
  34558. }
  34559. _super.prototype.setVerticesData.call(this, kind, data, false);
  34560. };
  34561. // to override
  34562. // protected
  34563. _Primitive.prototype._regenerateVertexData = function () {
  34564. throw new Error("Abstract method");
  34565. };
  34566. _Primitive.prototype.copy = function (id) {
  34567. throw new Error("Must be overriden in sub-classes.");
  34568. };
  34569. _Primitive.prototype.serialize = function () {
  34570. var serializationObject = _super.prototype.serialize.call(this);
  34571. serializationObject.canBeRegenerated = this.canBeRegenerated();
  34572. return serializationObject;
  34573. };
  34574. return _Primitive;
  34575. })(Geometry);
  34576. Primitives._Primitive = _Primitive;
  34577. var Ribbon = (function (_super) {
  34578. __extends(Ribbon, _super);
  34579. // Members
  34580. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  34581. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34582. _super.call(this, id, scene, canBeRegenerated, mesh);
  34583. this.pathArray = pathArray;
  34584. this.closeArray = closeArray;
  34585. this.closePath = closePath;
  34586. this.offset = offset;
  34587. this.side = side;
  34588. }
  34589. Ribbon.prototype._regenerateVertexData = function () {
  34590. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  34591. };
  34592. Ribbon.prototype.copy = function (id) {
  34593. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  34594. };
  34595. return Ribbon;
  34596. })(_Primitive);
  34597. Primitives.Ribbon = Ribbon;
  34598. var Box = (function (_super) {
  34599. __extends(Box, _super);
  34600. // Members
  34601. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  34602. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34603. _super.call(this, id, scene, canBeRegenerated, mesh);
  34604. this.size = size;
  34605. this.side = side;
  34606. }
  34607. Box.prototype._regenerateVertexData = function () {
  34608. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  34609. };
  34610. Box.prototype.copy = function (id) {
  34611. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34612. };
  34613. Box.prototype.serialize = function () {
  34614. var serializationObject = _super.prototype.serialize.call(this);
  34615. serializationObject.size = this.size;
  34616. return serializationObject;
  34617. };
  34618. Box.Parse = function (parsedBox, scene) {
  34619. if (scene.getGeometryByID(parsedBox.id)) {
  34620. return null; // null since geometry could be something else than a box...
  34621. }
  34622. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  34623. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  34624. scene.pushGeometry(box, true);
  34625. return box;
  34626. };
  34627. return Box;
  34628. })(_Primitive);
  34629. Primitives.Box = Box;
  34630. var Sphere = (function (_super) {
  34631. __extends(Sphere, _super);
  34632. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  34633. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34634. _super.call(this, id, scene, canBeRegenerated, mesh);
  34635. this.segments = segments;
  34636. this.diameter = diameter;
  34637. this.side = side;
  34638. }
  34639. Sphere.prototype._regenerateVertexData = function () {
  34640. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  34641. };
  34642. Sphere.prototype.copy = function (id) {
  34643. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  34644. };
  34645. Sphere.prototype.serialize = function () {
  34646. var serializationObject = _super.prototype.serialize.call(this);
  34647. serializationObject.segments = this.segments;
  34648. serializationObject.diameter = this.diameter;
  34649. return serializationObject;
  34650. };
  34651. Sphere.Parse = function (parsedSphere, scene) {
  34652. if (scene.getGeometryByID(parsedSphere.id)) {
  34653. return null; // null since geometry could be something else than a sphere...
  34654. }
  34655. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34656. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34657. scene.pushGeometry(sphere, true);
  34658. return sphere;
  34659. };
  34660. return Sphere;
  34661. })(_Primitive);
  34662. Primitives.Sphere = Sphere;
  34663. var Disc = (function (_super) {
  34664. __extends(Disc, _super);
  34665. // Members
  34666. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  34667. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34668. _super.call(this, id, scene, canBeRegenerated, mesh);
  34669. this.radius = radius;
  34670. this.tessellation = tessellation;
  34671. this.side = side;
  34672. }
  34673. Disc.prototype._regenerateVertexData = function () {
  34674. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34675. };
  34676. Disc.prototype.copy = function (id) {
  34677. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34678. };
  34679. return Disc;
  34680. })(_Primitive);
  34681. Primitives.Disc = Disc;
  34682. var Cylinder = (function (_super) {
  34683. __extends(Cylinder, _super);
  34684. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  34685. if (subdivisions === void 0) { subdivisions = 1; }
  34686. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34687. _super.call(this, id, scene, canBeRegenerated, mesh);
  34688. this.height = height;
  34689. this.diameterTop = diameterTop;
  34690. this.diameterBottom = diameterBottom;
  34691. this.tessellation = tessellation;
  34692. this.subdivisions = subdivisions;
  34693. this.side = side;
  34694. }
  34695. Cylinder.prototype._regenerateVertexData = function () {
  34696. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34697. };
  34698. Cylinder.prototype.copy = function (id) {
  34699. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34700. };
  34701. Cylinder.prototype.serialize = function () {
  34702. var serializationObject = _super.prototype.serialize.call(this);
  34703. serializationObject.height = this.height;
  34704. serializationObject.diameterTop = this.diameterTop;
  34705. serializationObject.diameterBottom = this.diameterBottom;
  34706. serializationObject.tessellation = this.tessellation;
  34707. return serializationObject;
  34708. };
  34709. Cylinder.Parse = function (parsedCylinder, scene) {
  34710. if (scene.getGeometryByID(parsedCylinder.id)) {
  34711. return null; // null since geometry could be something else than a cylinder...
  34712. }
  34713. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34714. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34715. scene.pushGeometry(cylinder, true);
  34716. return cylinder;
  34717. };
  34718. return Cylinder;
  34719. })(_Primitive);
  34720. Primitives.Cylinder = Cylinder;
  34721. var Torus = (function (_super) {
  34722. __extends(Torus, _super);
  34723. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  34724. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34725. _super.call(this, id, scene, canBeRegenerated, mesh);
  34726. this.diameter = diameter;
  34727. this.thickness = thickness;
  34728. this.tessellation = tessellation;
  34729. this.side = side;
  34730. }
  34731. Torus.prototype._regenerateVertexData = function () {
  34732. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34733. };
  34734. Torus.prototype.copy = function (id) {
  34735. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34736. };
  34737. Torus.prototype.serialize = function () {
  34738. var serializationObject = _super.prototype.serialize.call(this);
  34739. serializationObject.diameter = this.diameter;
  34740. serializationObject.thickness = this.thickness;
  34741. serializationObject.tessellation = this.tessellation;
  34742. return serializationObject;
  34743. };
  34744. Torus.Parse = function (parsedTorus, scene) {
  34745. if (scene.getGeometryByID(parsedTorus.id)) {
  34746. return null; // null since geometry could be something else than a torus...
  34747. }
  34748. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34749. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34750. scene.pushGeometry(torus, true);
  34751. return torus;
  34752. };
  34753. return Torus;
  34754. })(_Primitive);
  34755. Primitives.Torus = Torus;
  34756. var Ground = (function (_super) {
  34757. __extends(Ground, _super);
  34758. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  34759. _super.call(this, id, scene, canBeRegenerated, mesh);
  34760. this.width = width;
  34761. this.height = height;
  34762. this.subdivisions = subdivisions;
  34763. }
  34764. Ground.prototype._regenerateVertexData = function () {
  34765. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34766. };
  34767. Ground.prototype.copy = function (id) {
  34768. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34769. };
  34770. Ground.prototype.serialize = function () {
  34771. var serializationObject = _super.prototype.serialize.call(this);
  34772. serializationObject.width = this.width;
  34773. serializationObject.height = this.height;
  34774. serializationObject.subdivisions = this.subdivisions;
  34775. return serializationObject;
  34776. };
  34777. Ground.Parse = function (parsedGround, scene) {
  34778. if (scene.getGeometryByID(parsedGround.id)) {
  34779. return null; // null since geometry could be something else than a ground...
  34780. }
  34781. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34782. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34783. scene.pushGeometry(ground, true);
  34784. return ground;
  34785. };
  34786. return Ground;
  34787. })(_Primitive);
  34788. Primitives.Ground = Ground;
  34789. var TiledGround = (function (_super) {
  34790. __extends(TiledGround, _super);
  34791. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  34792. _super.call(this, id, scene, canBeRegenerated, mesh);
  34793. this.xmin = xmin;
  34794. this.zmin = zmin;
  34795. this.xmax = xmax;
  34796. this.zmax = zmax;
  34797. this.subdivisions = subdivisions;
  34798. this.precision = precision;
  34799. }
  34800. TiledGround.prototype._regenerateVertexData = function () {
  34801. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34802. };
  34803. TiledGround.prototype.copy = function (id) {
  34804. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34805. };
  34806. return TiledGround;
  34807. })(_Primitive);
  34808. Primitives.TiledGround = TiledGround;
  34809. var Plane = (function (_super) {
  34810. __extends(Plane, _super);
  34811. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  34812. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34813. _super.call(this, id, scene, canBeRegenerated, mesh);
  34814. this.size = size;
  34815. this.side = side;
  34816. }
  34817. Plane.prototype._regenerateVertexData = function () {
  34818. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34819. };
  34820. Plane.prototype.copy = function (id) {
  34821. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34822. };
  34823. Plane.prototype.serialize = function () {
  34824. var serializationObject = _super.prototype.serialize.call(this);
  34825. serializationObject.size = this.size;
  34826. return serializationObject;
  34827. };
  34828. Plane.Parse = function (parsedPlane, scene) {
  34829. if (scene.getGeometryByID(parsedPlane.id)) {
  34830. return null; // null since geometry could be something else than a ground...
  34831. }
  34832. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34833. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34834. scene.pushGeometry(plane, true);
  34835. return plane;
  34836. };
  34837. return Plane;
  34838. })(_Primitive);
  34839. Primitives.Plane = Plane;
  34840. var TorusKnot = (function (_super) {
  34841. __extends(TorusKnot, _super);
  34842. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  34843. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34844. _super.call(this, id, scene, canBeRegenerated, mesh);
  34845. this.radius = radius;
  34846. this.tube = tube;
  34847. this.radialSegments = radialSegments;
  34848. this.tubularSegments = tubularSegments;
  34849. this.p = p;
  34850. this.q = q;
  34851. this.side = side;
  34852. }
  34853. TorusKnot.prototype._regenerateVertexData = function () {
  34854. 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 });
  34855. };
  34856. TorusKnot.prototype.copy = function (id) {
  34857. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34858. };
  34859. TorusKnot.prototype.serialize = function () {
  34860. var serializationObject = _super.prototype.serialize.call(this);
  34861. serializationObject.radius = this.radius;
  34862. serializationObject.tube = this.tube;
  34863. serializationObject.radialSegments = this.radialSegments;
  34864. serializationObject.tubularSegments = this.tubularSegments;
  34865. serializationObject.p = this.p;
  34866. serializationObject.q = this.q;
  34867. return serializationObject;
  34868. };
  34869. ;
  34870. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  34871. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34872. return null; // null since geometry could be something else than a ground...
  34873. }
  34874. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34875. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34876. scene.pushGeometry(torusKnot, true);
  34877. return torusKnot;
  34878. };
  34879. return TorusKnot;
  34880. })(_Primitive);
  34881. Primitives.TorusKnot = TorusKnot;
  34882. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  34883. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  34884. })(BABYLON || (BABYLON = {}));
  34885. var BABYLON;
  34886. (function (BABYLON) {
  34887. var GroundMesh = (function (_super) {
  34888. __extends(GroundMesh, _super);
  34889. function GroundMesh(name, scene) {
  34890. _super.call(this, name, scene);
  34891. this.generateOctree = false;
  34892. this._worldInverse = new BABYLON.Matrix();
  34893. }
  34894. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  34895. get: function () {
  34896. return this._subdivisions;
  34897. },
  34898. enumerable: true,
  34899. configurable: true
  34900. });
  34901. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  34902. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  34903. this._subdivisions = chunksCount;
  34904. this.subdivide(this._subdivisions);
  34905. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  34906. };
  34907. /**
  34908. * Returns a height (y) value in the Worl system :
  34909. * the ground altitude at the coordinates (x, z) expressed in the World system.
  34910. * Returns the ground y position if (x, z) are outside the ground surface.
  34911. * Not pertinent if the ground is rotated.
  34912. */
  34913. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  34914. // express x and y in the ground local system
  34915. x -= this.position.x;
  34916. z -= this.position.z;
  34917. x /= this.scaling.x;
  34918. z /= this.scaling.z;
  34919. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34920. return this.position.y;
  34921. }
  34922. if (!this._heightQuads || this._heightQuads.length == 0) {
  34923. this._initHeightQuads();
  34924. this._computeHeightQuads();
  34925. }
  34926. var facet = this._getFacetAt(x, z);
  34927. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  34928. // return y in the World system
  34929. return y * this.scaling.y + this.position.y;
  34930. };
  34931. /**
  34932. * Returns a normalized vector (Vector3) orthogonal to the ground
  34933. * at the ground coordinates (x, z) expressed in the World system.
  34934. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  34935. * Not pertinent if the ground is rotated.
  34936. */
  34937. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  34938. var normal = new BABYLON.Vector3(0, 1, 0);
  34939. this.getNormalAtCoordinatesToRef(x, z, normal);
  34940. return normal;
  34941. };
  34942. /**
  34943. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  34944. * at the ground coordinates (x, z) expressed in the World system.
  34945. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  34946. * Not pertinent if the ground is rotated.
  34947. */
  34948. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  34949. // express x and y in the ground local system
  34950. x -= this.position.x;
  34951. z -= this.position.z;
  34952. x /= this.scaling.x;
  34953. z /= this.scaling.z;
  34954. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34955. return;
  34956. }
  34957. if (!this._heightQuads || this._heightQuads.length == 0) {
  34958. this._initHeightQuads();
  34959. this._computeHeightQuads();
  34960. }
  34961. var facet = this._getFacetAt(x, z);
  34962. ref.x = facet.x;
  34963. ref.y = facet.y;
  34964. ref.z = facet.z;
  34965. };
  34966. /**
  34967. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  34968. * if the ground has been updated.
  34969. * This can be used in the render loop
  34970. */
  34971. GroundMesh.prototype.updateCoordinateHeights = function () {
  34972. if (!this._heightQuads || this._heightQuads.length == 0) {
  34973. this._initHeightQuads();
  34974. }
  34975. this._computeHeightQuads();
  34976. };
  34977. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  34978. GroundMesh.prototype._getFacetAt = function (x, z) {
  34979. // retrieve col and row from x, z coordinates in the ground local system
  34980. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  34981. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  34982. var quad = this._heightQuads[row * this._subdivisions + col];
  34983. var facet;
  34984. if (z < quad.slope.x * x + quad.slope.y) {
  34985. facet = quad.facet1;
  34986. }
  34987. else {
  34988. facet = quad.facet2;
  34989. }
  34990. return facet;
  34991. };
  34992. // Creates and populates the heightMap array with "facet" elements :
  34993. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34994. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34995. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34996. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34997. GroundMesh.prototype._initHeightQuads = function () {
  34998. this._heightQuads = new Array();
  34999. for (var row = 0; row < this._subdivisions; row++) {
  35000. for (var col = 0; col < this._subdivisions; col++) {
  35001. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  35002. this._heightQuads[row * this._subdivisions + col] = quad;
  35003. }
  35004. }
  35005. };
  35006. // Compute each quad element values and update the the heightMap array :
  35007. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  35008. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  35009. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  35010. GroundMesh.prototype._computeHeightQuads = function () {
  35011. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35012. var v1 = BABYLON.Tmp.Vector3[3];
  35013. var v2 = BABYLON.Tmp.Vector3[2];
  35014. var v3 = BABYLON.Tmp.Vector3[1];
  35015. var v4 = BABYLON.Tmp.Vector3[0];
  35016. var v1v2 = BABYLON.Tmp.Vector3[4];
  35017. var v1v3 = BABYLON.Tmp.Vector3[5];
  35018. var v1v4 = BABYLON.Tmp.Vector3[6];
  35019. var norm1 = BABYLON.Tmp.Vector3[7];
  35020. var norm2 = BABYLON.Tmp.Vector3[8];
  35021. var i = 0;
  35022. var j = 0;
  35023. var k = 0;
  35024. var cd = 0; // 2D slope coefficient : z = cd * x + h
  35025. var h = 0;
  35026. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  35027. var d2 = 0;
  35028. for (var row = 0; row < this._subdivisions; row++) {
  35029. for (var col = 0; col < this._subdivisions; col++) {
  35030. i = col * 3;
  35031. j = row * (this._subdivisions + 1) * 3;
  35032. k = (row + 1) * (this._subdivisions + 1) * 3;
  35033. v1.x = positions[j + i];
  35034. v1.y = positions[j + i + 1];
  35035. v1.z = positions[j + i + 2];
  35036. v2.x = positions[j + i + 3];
  35037. v2.y = positions[j + i + 4];
  35038. v2.z = positions[j + i + 5];
  35039. v3.x = positions[k + i];
  35040. v3.y = positions[k + i + 1];
  35041. v3.z = positions[k + i + 2];
  35042. v4.x = positions[k + i + 3];
  35043. v4.y = positions[k + i + 4];
  35044. v4.z = positions[k + i + 5];
  35045. // 2D slope V1V4
  35046. cd = (v4.z - v1.z) / (v4.x - v1.x);
  35047. h = v1.z - cd * v1.x; // v1 belongs to the slope
  35048. // facet equations :
  35049. // we compute each facet normal vector
  35050. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  35051. // we compute the value d by applying the equation to v1 which belongs to the plane
  35052. // then we store the facet equation in a Vector4
  35053. v2.subtractToRef(v1, v1v2);
  35054. v3.subtractToRef(v1, v1v3);
  35055. v4.subtractToRef(v1, v1v4);
  35056. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  35057. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  35058. norm1.normalize();
  35059. norm2.normalize();
  35060. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  35061. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  35062. var quad = this._heightQuads[row * this._subdivisions + col];
  35063. quad.slope.copyFromFloats(cd, h);
  35064. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  35065. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  35066. }
  35067. }
  35068. };
  35069. return GroundMesh;
  35070. })(BABYLON.Mesh);
  35071. BABYLON.GroundMesh = GroundMesh;
  35072. })(BABYLON || (BABYLON = {}));
  35073. var BABYLON;
  35074. (function (BABYLON) {
  35075. var LinesMesh = (function (_super) {
  35076. __extends(LinesMesh, _super);
  35077. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  35078. if (parent === void 0) { parent = null; }
  35079. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  35080. this.color = new BABYLON.Color3(1, 1, 1);
  35081. this.alpha = 1;
  35082. this._positionBuffer = {};
  35083. if (source) {
  35084. this.color = source.color.clone();
  35085. this.alpha = source.alpha;
  35086. }
  35087. this._intersectionThreshold = 0.1;
  35088. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  35089. attributes: [BABYLON.VertexBuffer.PositionKind],
  35090. uniforms: ["worldViewProjection", "color"],
  35091. needAlphaBlending: true
  35092. });
  35093. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  35094. }
  35095. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  35096. /**
  35097. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35098. * This margin is expressed in world space coordinates, so its value may vary.
  35099. * Default value is 0.1
  35100. * @returns the intersection Threshold value.
  35101. */
  35102. get: function () {
  35103. return this._intersectionThreshold;
  35104. },
  35105. /**
  35106. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35107. * This margin is expressed in world space coordinates, so its value may vary.
  35108. * @param value the new threshold to apply
  35109. */
  35110. set: function (value) {
  35111. if (this._intersectionThreshold === value) {
  35112. return;
  35113. }
  35114. this._intersectionThreshold = value;
  35115. if (this.geometry) {
  35116. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  35117. }
  35118. },
  35119. enumerable: true,
  35120. configurable: true
  35121. });
  35122. Object.defineProperty(LinesMesh.prototype, "material", {
  35123. get: function () {
  35124. return this._colorShader;
  35125. },
  35126. enumerable: true,
  35127. configurable: true
  35128. });
  35129. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  35130. get: function () {
  35131. return false;
  35132. },
  35133. enumerable: true,
  35134. configurable: true
  35135. });
  35136. LinesMesh.prototype.createInstance = function (name) {
  35137. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  35138. return null;
  35139. };
  35140. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  35141. var engine = this.getScene().getEngine();
  35142. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  35143. // VBOs
  35144. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  35145. // Color
  35146. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  35147. };
  35148. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  35149. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  35150. return;
  35151. }
  35152. var engine = this.getScene().getEngine();
  35153. // Draw order
  35154. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  35155. };
  35156. LinesMesh.prototype.dispose = function (doNotRecurse) {
  35157. this._colorShader.dispose();
  35158. _super.prototype.dispose.call(this, doNotRecurse);
  35159. };
  35160. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  35161. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  35162. };
  35163. return LinesMesh;
  35164. })(BABYLON.Mesh);
  35165. BABYLON.LinesMesh = LinesMesh;
  35166. })(BABYLON || (BABYLON = {}));
  35167. var BABYLON;
  35168. (function (BABYLON) {
  35169. var DefaultLoadingScreen = (function () {
  35170. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  35171. var _this = this;
  35172. if (_loadingText === void 0) { _loadingText = ""; }
  35173. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  35174. this._renderingCanvas = _renderingCanvas;
  35175. this._loadingText = _loadingText;
  35176. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  35177. // Resize
  35178. this._resizeLoadingUI = function () {
  35179. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  35180. _this._loadingDiv.style.position = "absolute";
  35181. _this._loadingDiv.style.left = canvasRect.left + "px";
  35182. _this._loadingDiv.style.top = canvasRect.top + "px";
  35183. _this._loadingDiv.style.width = canvasRect.width + "px";
  35184. _this._loadingDiv.style.height = canvasRect.height + "px";
  35185. };
  35186. }
  35187. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  35188. var _this = this;
  35189. if (this._loadingDiv) {
  35190. // Do not add a loading screen if there is already one
  35191. return;
  35192. }
  35193. this._loadingDiv = document.createElement("div");
  35194. this._loadingDiv.id = "babylonjsLoadingDiv";
  35195. this._loadingDiv.style.opacity = "0";
  35196. this._loadingDiv.style.transition = "opacity 1.5s ease";
  35197. // Loading text
  35198. this._loadingTextDiv = document.createElement("div");
  35199. this._loadingTextDiv.style.position = "absolute";
  35200. this._loadingTextDiv.style.left = "0";
  35201. this._loadingTextDiv.style.top = "50%";
  35202. this._loadingTextDiv.style.marginTop = "80px";
  35203. this._loadingTextDiv.style.width = "100%";
  35204. this._loadingTextDiv.style.height = "20px";
  35205. this._loadingTextDiv.style.fontFamily = "Arial";
  35206. this._loadingTextDiv.style.fontSize = "14px";
  35207. this._loadingTextDiv.style.color = "white";
  35208. this._loadingTextDiv.style.textAlign = "center";
  35209. this._loadingTextDiv.innerHTML = "Loading";
  35210. this._loadingDiv.appendChild(this._loadingTextDiv);
  35211. //set the predefined text
  35212. this._loadingTextDiv.innerHTML = this._loadingText;
  35213. // Loading img
  35214. var imgBack = new Image();
  35215. 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==";
  35216. imgBack.style.position = "absolute";
  35217. imgBack.style.left = "50%";
  35218. imgBack.style.top = "50%";
  35219. imgBack.style.marginLeft = "-50px";
  35220. imgBack.style.marginTop = "-50px";
  35221. imgBack.style.transition = "transform 1.0s ease";
  35222. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  35223. var deg = 360;
  35224. var onTransitionEnd = function () {
  35225. deg += 360;
  35226. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  35227. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  35228. };
  35229. imgBack.addEventListener("transitionend", onTransitionEnd);
  35230. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  35231. this._loadingDiv.appendChild(imgBack);
  35232. // front image
  35233. var imgFront = new Image();
  35234. 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=";
  35235. imgFront.style.position = "absolute";
  35236. imgFront.style.left = "50%";
  35237. imgFront.style.top = "50%";
  35238. imgFront.style.marginLeft = "-50px";
  35239. imgFront.style.marginTop = "-50px";
  35240. this._loadingDiv.appendChild(imgFront);
  35241. this._resizeLoadingUI();
  35242. window.addEventListener("resize", this._resizeLoadingUI);
  35243. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35244. document.body.appendChild(this._loadingDiv);
  35245. setTimeout(function () {
  35246. _this._loadingDiv.style.opacity = "1";
  35247. imgBack.style.transform = "rotateZ(360deg)";
  35248. imgBack.style.webkitTransform = "rotateZ(360deg)";
  35249. }, 0);
  35250. };
  35251. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  35252. var _this = this;
  35253. if (!this._loadingDiv) {
  35254. return;
  35255. }
  35256. var onTransitionEnd = function () {
  35257. if (!_this._loadingDiv) {
  35258. return;
  35259. }
  35260. document.body.removeChild(_this._loadingDiv);
  35261. window.removeEventListener("resize", _this._resizeLoadingUI);
  35262. _this._loadingDiv = null;
  35263. };
  35264. this._loadingDiv.style.opacity = "0";
  35265. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  35266. };
  35267. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  35268. set: function (text) {
  35269. this._loadingText = text;
  35270. if (this._loadingTextDiv) {
  35271. this._loadingTextDiv.innerHTML = this._loadingText;
  35272. }
  35273. },
  35274. enumerable: true,
  35275. configurable: true
  35276. });
  35277. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  35278. get: function () {
  35279. return this._loadingDivBackgroundColor;
  35280. },
  35281. set: function (color) {
  35282. this._loadingDivBackgroundColor = color;
  35283. if (!this._loadingDiv) {
  35284. return;
  35285. }
  35286. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35287. },
  35288. enumerable: true,
  35289. configurable: true
  35290. });
  35291. return DefaultLoadingScreen;
  35292. })();
  35293. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  35294. })(BABYLON || (BABYLON = {}));
  35295. var BABYLON;
  35296. (function (BABYLON) {
  35297. var AudioEngine = (function () {
  35298. function AudioEngine() {
  35299. this._audioContext = null;
  35300. this._audioContextInitialized = false;
  35301. this.canUseWebAudio = false;
  35302. this.WarnedWebAudioUnsupported = false;
  35303. this.unlocked = false;
  35304. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35305. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35306. this.canUseWebAudio = true;
  35307. }
  35308. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35309. this._unlockiOSaudio();
  35310. }
  35311. else {
  35312. this.unlocked = true;
  35313. }
  35314. }
  35315. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35316. get: function () {
  35317. if (!this._audioContextInitialized) {
  35318. this._initializeAudioContext();
  35319. }
  35320. return this._audioContext;
  35321. },
  35322. enumerable: true,
  35323. configurable: true
  35324. });
  35325. AudioEngine.prototype._unlockiOSaudio = function () {
  35326. var _this = this;
  35327. var unlockaudio = function () {
  35328. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35329. var source = _this.audioContext.createBufferSource();
  35330. source.buffer = buffer;
  35331. source.connect(_this.audioContext.destination);
  35332. source.start(0);
  35333. setTimeout(function () {
  35334. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35335. _this.unlocked = true;
  35336. window.removeEventListener('touchend', unlockaudio, false);
  35337. if (_this.onAudioUnlocked) {
  35338. _this.onAudioUnlocked();
  35339. }
  35340. }
  35341. }, 0);
  35342. };
  35343. window.addEventListener('touchend', unlockaudio, false);
  35344. };
  35345. AudioEngine.prototype._initializeAudioContext = function () {
  35346. try {
  35347. if (this.canUseWebAudio) {
  35348. this._audioContext = new AudioContext();
  35349. // create a global volume gain node
  35350. this.masterGain = this._audioContext.createGain();
  35351. this.masterGain.gain.value = 1;
  35352. this.masterGain.connect(this._audioContext.destination);
  35353. this._audioContextInitialized = true;
  35354. }
  35355. }
  35356. catch (e) {
  35357. this.canUseWebAudio = false;
  35358. BABYLON.Tools.Error("Web Audio: " + e.message);
  35359. }
  35360. };
  35361. AudioEngine.prototype.dispose = function () {
  35362. if (this.canUseWebAudio && this._audioContextInitialized) {
  35363. if (this._connectedAnalyser) {
  35364. this._connectedAnalyser.stopDebugCanvas();
  35365. this._connectedAnalyser.dispose();
  35366. this.masterGain.disconnect();
  35367. this.masterGain.connect(this._audioContext.destination);
  35368. this._connectedAnalyser = null;
  35369. }
  35370. this.masterGain.gain.value = 1;
  35371. }
  35372. this.WarnedWebAudioUnsupported = false;
  35373. };
  35374. AudioEngine.prototype.getGlobalVolume = function () {
  35375. if (this.canUseWebAudio && this._audioContextInitialized) {
  35376. return this.masterGain.gain.value;
  35377. }
  35378. else {
  35379. return -1;
  35380. }
  35381. };
  35382. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35383. if (this.canUseWebAudio && this._audioContextInitialized) {
  35384. this.masterGain.gain.value = newVolume;
  35385. }
  35386. };
  35387. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35388. if (this._connectedAnalyser) {
  35389. this._connectedAnalyser.stopDebugCanvas();
  35390. }
  35391. if (this.canUseWebAudio && this._audioContextInitialized) {
  35392. this._connectedAnalyser = analyser;
  35393. this.masterGain.disconnect();
  35394. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35395. }
  35396. };
  35397. return AudioEngine;
  35398. })();
  35399. BABYLON.AudioEngine = AudioEngine;
  35400. })(BABYLON || (BABYLON = {}));
  35401. var BABYLON;
  35402. (function (BABYLON) {
  35403. var Sound = (function () {
  35404. /**
  35405. * Create a sound and attach it to a scene
  35406. * @param name Name of your sound
  35407. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35408. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35409. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35410. */
  35411. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35412. var _this = this;
  35413. this.autoplay = false;
  35414. this.loop = false;
  35415. this.useCustomAttenuation = false;
  35416. this.spatialSound = false;
  35417. this.refDistance = 1;
  35418. this.rolloffFactor = 1;
  35419. this.maxDistance = 100;
  35420. this.distanceModel = "linear";
  35421. this._panningModel = "equalpower";
  35422. this._playbackRate = 1;
  35423. this._streaming = false;
  35424. this._startTime = 0;
  35425. this._startOffset = 0;
  35426. this._position = BABYLON.Vector3.Zero();
  35427. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35428. this._volume = 1;
  35429. this._isLoaded = false;
  35430. this._isReadyToPlay = false;
  35431. this.isPlaying = false;
  35432. this.isPaused = false;
  35433. this._isDirectional = false;
  35434. // Used if you'd like to create a directional sound.
  35435. // If not set, the sound will be omnidirectional
  35436. this._coneInnerAngle = 360;
  35437. this._coneOuterAngle = 360;
  35438. this._coneOuterGain = 0;
  35439. this._isOutputConnected = false;
  35440. this.name = name;
  35441. this._scene = scene;
  35442. this._readyToPlayCallback = readyToPlayCallback;
  35443. // Default custom attenuation function is a linear attenuation
  35444. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  35445. if (currentDistance < maxDistance) {
  35446. return currentVolume * (1 - currentDistance / maxDistance);
  35447. }
  35448. else {
  35449. return 0;
  35450. }
  35451. };
  35452. if (options) {
  35453. this.autoplay = options.autoplay || false;
  35454. this.loop = options.loop || false;
  35455. // if volume === 0, we need another way to check this option
  35456. if (options.volume !== undefined) {
  35457. this._volume = options.volume;
  35458. }
  35459. this.spatialSound = options.spatialSound || false;
  35460. this.maxDistance = options.maxDistance || 100;
  35461. this.useCustomAttenuation = options.useCustomAttenuation || false;
  35462. this.rolloffFactor = options.rolloffFactor || 1;
  35463. this.refDistance = options.refDistance || 1;
  35464. this.distanceModel = options.distanceModel || "linear";
  35465. this._playbackRate = options.playbackRate || 1;
  35466. this._streaming = options.streaming || false;
  35467. }
  35468. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35469. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  35470. this._soundGain.gain.value = this._volume;
  35471. this._inputAudioNode = this._soundGain;
  35472. this._ouputAudioNode = this._soundGain;
  35473. if (this.spatialSound) {
  35474. this._createSpatialParameters();
  35475. }
  35476. this._scene.mainSoundTrack.AddSound(this);
  35477. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  35478. if (urlOrArrayBuffer) {
  35479. // If it's an URL
  35480. if (typeof (urlOrArrayBuffer) === "string") {
  35481. // Loading sound using XHR2
  35482. if (!this._streaming) {
  35483. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  35484. }
  35485. else {
  35486. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  35487. this._htmlAudioElement.controls = false;
  35488. this._htmlAudioElement.loop = this.loop;
  35489. this._htmlAudioElement.crossOrigin = "anonymous";
  35490. this._htmlAudioElement.preload = "auto";
  35491. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  35492. _this._isReadyToPlay = true;
  35493. if (_this.autoplay) {
  35494. _this.play();
  35495. }
  35496. if (_this._readyToPlayCallback) {
  35497. _this._readyToPlayCallback();
  35498. }
  35499. });
  35500. document.body.appendChild(this._htmlAudioElement);
  35501. }
  35502. }
  35503. else {
  35504. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  35505. if (urlOrArrayBuffer.byteLength > 0) {
  35506. this._soundLoaded(urlOrArrayBuffer);
  35507. }
  35508. }
  35509. else {
  35510. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  35511. }
  35512. }
  35513. }
  35514. }
  35515. else {
  35516. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  35517. this._scene.mainSoundTrack.AddSound(this);
  35518. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  35519. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  35520. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  35521. }
  35522. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  35523. if (this._readyToPlayCallback) {
  35524. window.setTimeout(function () {
  35525. _this._readyToPlayCallback();
  35526. }, 1000);
  35527. }
  35528. }
  35529. }
  35530. Sound.prototype.dispose = function () {
  35531. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  35532. if (this.isPlaying) {
  35533. this.stop();
  35534. }
  35535. this._isReadyToPlay = false;
  35536. if (this.soundTrackId === -1) {
  35537. this._scene.mainSoundTrack.RemoveSound(this);
  35538. }
  35539. else {
  35540. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  35541. }
  35542. if (this._soundGain) {
  35543. this._soundGain.disconnect();
  35544. this._soundGain = null;
  35545. }
  35546. if (this._soundPanner) {
  35547. this._soundPanner.disconnect();
  35548. this._soundPanner = null;
  35549. }
  35550. if (this._soundSource) {
  35551. this._soundSource.disconnect();
  35552. this._soundSource = null;
  35553. }
  35554. this._audioBuffer = null;
  35555. if (this._htmlAudioElement) {
  35556. this._htmlAudioElement.pause();
  35557. this._htmlAudioElement.src = "";
  35558. document.body.removeChild(this._htmlAudioElement);
  35559. }
  35560. if (this._connectedMesh) {
  35561. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35562. this._connectedMesh = null;
  35563. }
  35564. }
  35565. };
  35566. Sound.prototype._soundLoaded = function (audioData) {
  35567. var _this = this;
  35568. this._isLoaded = true;
  35569. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  35570. _this._audioBuffer = buffer;
  35571. _this._isReadyToPlay = true;
  35572. if (_this.autoplay) {
  35573. _this.play();
  35574. }
  35575. if (_this._readyToPlayCallback) {
  35576. _this._readyToPlayCallback();
  35577. }
  35578. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  35579. };
  35580. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  35581. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35582. this._audioBuffer = audioBuffer;
  35583. this._isReadyToPlay = true;
  35584. }
  35585. };
  35586. Sound.prototype.updateOptions = function (options) {
  35587. if (options) {
  35588. this.loop = options.loop || this.loop;
  35589. this.maxDistance = options.maxDistance || this.maxDistance;
  35590. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  35591. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  35592. this.refDistance = options.refDistance || this.refDistance;
  35593. this.distanceModel = options.distanceModel || this.distanceModel;
  35594. this._playbackRate = options.playbackRate || this._playbackRate;
  35595. this._updateSpatialParameters();
  35596. if (this.isPlaying) {
  35597. if (this._streaming) {
  35598. this._htmlAudioElement.playbackRate = this._playbackRate;
  35599. }
  35600. else {
  35601. this._soundSource.playbackRate.value = this._playbackRate;
  35602. }
  35603. }
  35604. }
  35605. };
  35606. Sound.prototype._createSpatialParameters = function () {
  35607. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35608. if (this._scene.headphone) {
  35609. this._panningModel = "HRTF";
  35610. }
  35611. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  35612. this._updateSpatialParameters();
  35613. this._soundPanner.connect(this._ouputAudioNode);
  35614. this._inputAudioNode = this._soundPanner;
  35615. }
  35616. };
  35617. Sound.prototype._updateSpatialParameters = function () {
  35618. if (this.spatialSound) {
  35619. if (this.useCustomAttenuation) {
  35620. // Tricks to disable in a way embedded Web Audio attenuation
  35621. this._soundPanner.distanceModel = "linear";
  35622. this._soundPanner.maxDistance = Number.MAX_VALUE;
  35623. this._soundPanner.refDistance = 1;
  35624. this._soundPanner.rolloffFactor = 1;
  35625. this._soundPanner.panningModel = this._panningModel;
  35626. }
  35627. else {
  35628. this._soundPanner.distanceModel = this.distanceModel;
  35629. this._soundPanner.maxDistance = this.maxDistance;
  35630. this._soundPanner.refDistance = this.refDistance;
  35631. this._soundPanner.rolloffFactor = this.rolloffFactor;
  35632. this._soundPanner.panningModel = this._panningModel;
  35633. }
  35634. }
  35635. };
  35636. Sound.prototype.switchPanningModelToHRTF = function () {
  35637. this._panningModel = "HRTF";
  35638. this._switchPanningModel();
  35639. };
  35640. Sound.prototype.switchPanningModelToEqualPower = function () {
  35641. this._panningModel = "equalpower";
  35642. this._switchPanningModel();
  35643. };
  35644. Sound.prototype._switchPanningModel = function () {
  35645. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35646. this._soundPanner.panningModel = this._panningModel;
  35647. }
  35648. };
  35649. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35650. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35651. if (this._isOutputConnected) {
  35652. this._ouputAudioNode.disconnect();
  35653. }
  35654. this._ouputAudioNode.connect(soundTrackAudioNode);
  35655. this._isOutputConnected = true;
  35656. }
  35657. };
  35658. /**
  35659. * Transform this sound into a directional source
  35660. * @param coneInnerAngle Size of the inner cone in degree
  35661. * @param coneOuterAngle Size of the outer cone in degree
  35662. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  35663. */
  35664. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  35665. if (coneOuterAngle < coneInnerAngle) {
  35666. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  35667. return;
  35668. }
  35669. this._coneInnerAngle = coneInnerAngle;
  35670. this._coneOuterAngle = coneOuterAngle;
  35671. this._coneOuterGain = coneOuterGain;
  35672. this._isDirectional = true;
  35673. if (this.isPlaying && this.loop) {
  35674. this.stop();
  35675. this.play();
  35676. }
  35677. };
  35678. Sound.prototype.setPosition = function (newPosition) {
  35679. this._position = newPosition;
  35680. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35681. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35682. }
  35683. };
  35684. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  35685. this._localDirection = newLocalDirection;
  35686. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  35687. this._updateDirection();
  35688. }
  35689. };
  35690. Sound.prototype._updateDirection = function () {
  35691. var mat = this._connectedMesh.getWorldMatrix();
  35692. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  35693. direction.normalize();
  35694. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  35695. };
  35696. Sound.prototype.updateDistanceFromListener = function () {
  35697. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  35698. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  35699. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  35700. }
  35701. };
  35702. Sound.prototype.setAttenuationFunction = function (callback) {
  35703. this._customAttenuationFunction = callback;
  35704. };
  35705. /**
  35706. * Play the sound
  35707. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35708. * @param offset (optional) Start the sound setting it at a specific time
  35709. */
  35710. Sound.prototype.play = function (time, offset) {
  35711. var _this = this;
  35712. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35713. try {
  35714. if (this._startOffset < 0) {
  35715. time = -this._startOffset;
  35716. this._startOffset = 0;
  35717. }
  35718. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35719. if (!this._soundSource || !this._streamingSource) {
  35720. if (this.spatialSound) {
  35721. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35722. if (this._isDirectional) {
  35723. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35724. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35725. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35726. if (this._connectedMesh) {
  35727. this._updateDirection();
  35728. }
  35729. else {
  35730. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35731. }
  35732. }
  35733. }
  35734. }
  35735. if (this._streaming) {
  35736. if (!this._streamingSource) {
  35737. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35738. this._htmlAudioElement.onended = function () { _this._onended(); };
  35739. this._htmlAudioElement.playbackRate = this._playbackRate;
  35740. }
  35741. this._streamingSource.disconnect();
  35742. this._streamingSource.connect(this._inputAudioNode);
  35743. this._htmlAudioElement.play();
  35744. }
  35745. else {
  35746. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35747. this._soundSource.buffer = this._audioBuffer;
  35748. this._soundSource.connect(this._inputAudioNode);
  35749. this._soundSource.loop = this.loop;
  35750. this._soundSource.playbackRate.value = this._playbackRate;
  35751. this._soundSource.onended = function () { _this._onended(); };
  35752. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  35753. }
  35754. this._startTime = startTime;
  35755. this.isPlaying = true;
  35756. this.isPaused = false;
  35757. }
  35758. catch (ex) {
  35759. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35760. }
  35761. }
  35762. };
  35763. Sound.prototype._onended = function () {
  35764. this.isPlaying = false;
  35765. if (this.onended) {
  35766. this.onended();
  35767. }
  35768. };
  35769. /**
  35770. * Stop the sound
  35771. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35772. */
  35773. Sound.prototype.stop = function (time) {
  35774. if (this.isPlaying) {
  35775. if (this._streaming) {
  35776. this._htmlAudioElement.pause();
  35777. // Test needed for Firefox or it will generate an Invalid State Error
  35778. if (this._htmlAudioElement.currentTime > 0) {
  35779. this._htmlAudioElement.currentTime = 0;
  35780. }
  35781. }
  35782. else {
  35783. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35784. this._soundSource.stop(stopTime);
  35785. this._soundSource.onended = null;
  35786. if (!this.isPaused) {
  35787. this._startOffset = 0;
  35788. }
  35789. }
  35790. this.isPlaying = false;
  35791. }
  35792. };
  35793. Sound.prototype.pause = function () {
  35794. if (this.isPlaying) {
  35795. this.isPaused = true;
  35796. if (this._streaming) {
  35797. this._htmlAudioElement.pause();
  35798. }
  35799. else {
  35800. this.stop(0);
  35801. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35802. }
  35803. }
  35804. };
  35805. Sound.prototype.setVolume = function (newVolume, time) {
  35806. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35807. if (time) {
  35808. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35809. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35810. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35811. }
  35812. else {
  35813. this._soundGain.gain.value = newVolume;
  35814. }
  35815. }
  35816. this._volume = newVolume;
  35817. };
  35818. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35819. this._playbackRate = newPlaybackRate;
  35820. if (this.isPlaying) {
  35821. if (this._streaming) {
  35822. this._htmlAudioElement.playbackRate = this._playbackRate;
  35823. }
  35824. else {
  35825. this._soundSource.playbackRate.value = this._playbackRate;
  35826. }
  35827. }
  35828. };
  35829. Sound.prototype.getVolume = function () {
  35830. return this._volume;
  35831. };
  35832. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35833. var _this = this;
  35834. if (this._connectedMesh) {
  35835. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35836. this._registerFunc = null;
  35837. }
  35838. this._connectedMesh = meshToConnectTo;
  35839. if (!this.spatialSound) {
  35840. this.spatialSound = true;
  35841. this._createSpatialParameters();
  35842. if (this.isPlaying && this.loop) {
  35843. this.stop();
  35844. this.play();
  35845. }
  35846. }
  35847. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35848. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35849. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35850. };
  35851. Sound.prototype.detachFromMesh = function () {
  35852. if (this._connectedMesh) {
  35853. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35854. this._registerFunc = null;
  35855. this._connectedMesh = null;
  35856. }
  35857. };
  35858. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35859. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35860. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35861. this._updateDirection();
  35862. }
  35863. };
  35864. Sound.prototype.clone = function () {
  35865. var _this = this;
  35866. if (!this._streaming) {
  35867. var setBufferAndRun = function () {
  35868. if (_this._isReadyToPlay) {
  35869. clonedSound._audioBuffer = _this.getAudioBuffer();
  35870. clonedSound._isReadyToPlay = true;
  35871. if (clonedSound.autoplay) {
  35872. clonedSound.play();
  35873. }
  35874. }
  35875. else {
  35876. window.setTimeout(setBufferAndRun, 300);
  35877. }
  35878. };
  35879. var currentOptions = {
  35880. autoplay: this.autoplay, loop: this.loop,
  35881. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35882. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35883. refDistance: this.refDistance, distanceModel: this.distanceModel
  35884. };
  35885. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35886. if (this.useCustomAttenuation) {
  35887. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35888. }
  35889. clonedSound.setPosition(this._position);
  35890. clonedSound.setPlaybackRate(this._playbackRate);
  35891. setBufferAndRun();
  35892. return clonedSound;
  35893. }
  35894. else {
  35895. return null;
  35896. }
  35897. };
  35898. Sound.prototype.getAudioBuffer = function () {
  35899. return this._audioBuffer;
  35900. };
  35901. Sound.prototype.serialize = function () {
  35902. var serializationObject = {
  35903. name: this.name,
  35904. url: this.name,
  35905. autoplay: this.autoplay,
  35906. loop: this.loop,
  35907. volume: this._volume,
  35908. spatialSound: this.spatialSound,
  35909. maxDistance: this.maxDistance,
  35910. rolloffFactor: this.rolloffFactor,
  35911. refDistance: this.refDistance,
  35912. distanceModel: this.distanceModel,
  35913. playbackRate: this._playbackRate,
  35914. panningModel: this._panningModel,
  35915. soundTrackId: this.soundTrackId
  35916. };
  35917. if (this.spatialSound) {
  35918. if (this._connectedMesh)
  35919. serializationObject.connectedMeshId = this._connectedMesh.id;
  35920. serializationObject.position = this._position.asArray();
  35921. serializationObject.refDistance = this.refDistance;
  35922. serializationObject.distanceModel = this.distanceModel;
  35923. serializationObject.isDirectional = this._isDirectional;
  35924. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  35925. serializationObject.coneInnerAngle = this._coneInnerAngle;
  35926. serializationObject.coneOuterAngle = this._coneOuterAngle;
  35927. serializationObject.coneOuterGain = this._coneOuterGain;
  35928. }
  35929. return serializationObject;
  35930. };
  35931. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35932. var soundName = parsedSound.name;
  35933. var soundUrl;
  35934. if (parsedSound.url) {
  35935. soundUrl = rootUrl + parsedSound.url;
  35936. }
  35937. else {
  35938. soundUrl = rootUrl + soundName;
  35939. }
  35940. var options = {
  35941. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35942. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35943. rolloffFactor: parsedSound.rolloffFactor,
  35944. refDistance: parsedSound.refDistance,
  35945. distanceModel: parsedSound.distanceModel,
  35946. playbackRate: parsedSound.playbackRate
  35947. };
  35948. var newSound;
  35949. if (!sourceSound) {
  35950. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35951. scene._addPendingData(newSound);
  35952. }
  35953. else {
  35954. var setBufferAndRun = function () {
  35955. if (sourceSound._isReadyToPlay) {
  35956. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35957. newSound._isReadyToPlay = true;
  35958. if (newSound.autoplay) {
  35959. newSound.play();
  35960. }
  35961. }
  35962. else {
  35963. window.setTimeout(setBufferAndRun, 300);
  35964. }
  35965. };
  35966. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35967. setBufferAndRun();
  35968. }
  35969. if (parsedSound.position) {
  35970. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35971. newSound.setPosition(soundPosition);
  35972. }
  35973. if (parsedSound.isDirectional) {
  35974. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35975. if (parsedSound.localDirectionToMesh) {
  35976. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35977. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35978. }
  35979. }
  35980. if (parsedSound.connectedMeshId) {
  35981. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35982. if (connectedMesh) {
  35983. newSound.attachToMesh(connectedMesh);
  35984. }
  35985. }
  35986. return newSound;
  35987. };
  35988. return Sound;
  35989. })();
  35990. BABYLON.Sound = Sound;
  35991. })(BABYLON || (BABYLON = {}));
  35992. var BABYLON;
  35993. (function (BABYLON) {
  35994. var SoundTrack = (function () {
  35995. function SoundTrack(scene, options) {
  35996. this.id = -1;
  35997. this._isMainTrack = false;
  35998. this._isInitialized = false;
  35999. this._scene = scene;
  36000. this.soundCollection = new Array();
  36001. this._options = options;
  36002. if (!this._isMainTrack) {
  36003. this._scene.soundTracks.push(this);
  36004. this.id = this._scene.soundTracks.length - 1;
  36005. }
  36006. }
  36007. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  36008. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36009. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  36010. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  36011. if (this._options) {
  36012. if (this._options.volume) {
  36013. this._outputAudioNode.gain.value = this._options.volume;
  36014. }
  36015. if (this._options.mainTrack) {
  36016. this._isMainTrack = this._options.mainTrack;
  36017. }
  36018. }
  36019. this._isInitialized = true;
  36020. }
  36021. };
  36022. SoundTrack.prototype.dispose = function () {
  36023. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36024. if (this._connectedAnalyser) {
  36025. this._connectedAnalyser.stopDebugCanvas();
  36026. }
  36027. while (this.soundCollection.length) {
  36028. this.soundCollection[0].dispose();
  36029. }
  36030. if (this._outputAudioNode) {
  36031. this._outputAudioNode.disconnect();
  36032. }
  36033. this._outputAudioNode = null;
  36034. }
  36035. };
  36036. SoundTrack.prototype.AddSound = function (sound) {
  36037. if (!this._isInitialized) {
  36038. this._initializeSoundTrackAudioGraph();
  36039. }
  36040. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36041. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  36042. }
  36043. if (sound.soundTrackId) {
  36044. if (sound.soundTrackId === -1) {
  36045. this._scene.mainSoundTrack.RemoveSound(sound);
  36046. }
  36047. else {
  36048. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  36049. }
  36050. }
  36051. this.soundCollection.push(sound);
  36052. sound.soundTrackId = this.id;
  36053. };
  36054. SoundTrack.prototype.RemoveSound = function (sound) {
  36055. var index = this.soundCollection.indexOf(sound);
  36056. if (index !== -1) {
  36057. this.soundCollection.splice(index, 1);
  36058. }
  36059. };
  36060. SoundTrack.prototype.setVolume = function (newVolume) {
  36061. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36062. this._outputAudioNode.gain.value = newVolume;
  36063. }
  36064. };
  36065. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  36066. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36067. for (var i = 0; i < this.soundCollection.length; i++) {
  36068. this.soundCollection[i].switchPanningModelToHRTF();
  36069. }
  36070. }
  36071. };
  36072. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  36073. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36074. for (var i = 0; i < this.soundCollection.length; i++) {
  36075. this.soundCollection[i].switchPanningModelToEqualPower();
  36076. }
  36077. }
  36078. };
  36079. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  36080. if (this._connectedAnalyser) {
  36081. this._connectedAnalyser.stopDebugCanvas();
  36082. }
  36083. this._connectedAnalyser = analyser;
  36084. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36085. this._outputAudioNode.disconnect();
  36086. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  36087. }
  36088. };
  36089. return SoundTrack;
  36090. })();
  36091. BABYLON.SoundTrack = SoundTrack;
  36092. })(BABYLON || (BABYLON = {}));
  36093. var BABYLON;
  36094. (function (BABYLON) {
  36095. var DebugLayer = (function () {
  36096. function DebugLayer(scene) {
  36097. var _this = this;
  36098. this._transformationMatrix = BABYLON.Matrix.Identity();
  36099. this._enabled = false;
  36100. this._labelsEnabled = false;
  36101. this._displayStatistics = true;
  36102. this._displayTree = false;
  36103. this._displayLogs = false;
  36104. this._skeletonViewers = new Array();
  36105. this._identityMatrix = BABYLON.Matrix.Identity();
  36106. this.axisRatio = 0.02;
  36107. this.accentColor = "orange";
  36108. this._scene = scene;
  36109. this._syncPositions = function () {
  36110. var engine = _this._scene.getEngine();
  36111. var canvasRect = engine.getRenderingCanvasClientRect();
  36112. if (_this._showUI) {
  36113. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  36114. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  36115. _this._statsDiv.style.width = "400px";
  36116. _this._statsDiv.style.height = "auto";
  36117. _this._statsSubsetDiv.style.maxHeight = "240px";
  36118. _this._optionsDiv.style.left = "0px";
  36119. _this._optionsDiv.style.top = "10px";
  36120. _this._optionsDiv.style.width = "200px";
  36121. _this._optionsDiv.style.height = "auto";
  36122. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  36123. _this._logDiv.style.left = "0px";
  36124. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  36125. _this._logDiv.style.width = "600px";
  36126. _this._logDiv.style.height = "160px";
  36127. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  36128. _this._treeDiv.style.top = "10px";
  36129. _this._treeDiv.style.width = "300px";
  36130. _this._treeDiv.style.height = "auto";
  36131. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  36132. }
  36133. _this._globalDiv.style.left = canvasRect.left + "px";
  36134. _this._globalDiv.style.top = canvasRect.top + "px";
  36135. _this._drawingCanvas.style.left = "0px";
  36136. _this._drawingCanvas.style.top = "0px";
  36137. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  36138. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  36139. var devicePixelRatio = window.devicePixelRatio || 1;
  36140. var context = _this._drawingContext;
  36141. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  36142. context.mozBackingStorePixelRatio ||
  36143. context.msBackingStorePixelRatio ||
  36144. context.oBackingStorePixelRatio ||
  36145. context.backingStorePixelRatio || 1;
  36146. _this._ratio = devicePixelRatio / backingStoreRatio;
  36147. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  36148. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  36149. };
  36150. this._onCanvasClick = function (evt) {
  36151. _this._clickPosition = {
  36152. x: evt.clientX * _this._ratio,
  36153. y: evt.clientY * _this._ratio
  36154. };
  36155. };
  36156. this._syncUI = function () {
  36157. if (_this._showUI) {
  36158. if (_this._displayStatistics) {
  36159. _this._displayStats();
  36160. _this._statsDiv.style.display = "";
  36161. }
  36162. else {
  36163. _this._statsDiv.style.display = "none";
  36164. }
  36165. if (_this._displayLogs) {
  36166. _this._logDiv.style.display = "";
  36167. }
  36168. else {
  36169. _this._logDiv.style.display = "none";
  36170. }
  36171. if (_this._displayTree) {
  36172. _this._treeDiv.style.display = "";
  36173. if (_this._needToRefreshMeshesTree) {
  36174. _this._needToRefreshMeshesTree = false;
  36175. _this._refreshMeshesTreeContent();
  36176. }
  36177. }
  36178. else {
  36179. _this._treeDiv.style.display = "none";
  36180. }
  36181. }
  36182. };
  36183. this._syncData = function () {
  36184. if (_this._labelsEnabled || !_this._showUI) {
  36185. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  36186. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  36187. var engine = _this._scene.getEngine();
  36188. var viewport = _this._camera.viewport;
  36189. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  36190. // Meshes
  36191. var meshes = _this._camera.getActiveMeshes();
  36192. var index;
  36193. var projectedPosition;
  36194. for (index = 0; index < meshes.length; index++) {
  36195. var mesh = meshes.data[index];
  36196. var position = mesh.getBoundingInfo().boundingSphere.center;
  36197. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36198. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  36199. _this._renderAxis(projectedPosition, mesh, globalViewport);
  36200. }
  36201. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  36202. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  36203. }
  36204. }
  36205. // Cameras
  36206. var cameras = _this._scene.cameras;
  36207. for (index = 0; index < cameras.length; index++) {
  36208. var camera = cameras[index];
  36209. if (camera === _this._camera) {
  36210. continue;
  36211. }
  36212. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36213. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  36214. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  36215. _this._camera.detachControl(engine.getRenderingCanvas());
  36216. _this._camera = camera;
  36217. _this._camera.attachControl(engine.getRenderingCanvas());
  36218. }, function () { return "purple"; });
  36219. }
  36220. }
  36221. // Lights
  36222. var lights = _this._scene.lights;
  36223. for (index = 0; index < lights.length; index++) {
  36224. var light = lights[index];
  36225. if (light.position) {
  36226. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  36227. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  36228. _this._renderLabel(light.name, projectedPosition, -20, function () {
  36229. light.setEnabled(!light.isEnabled());
  36230. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  36231. }
  36232. }
  36233. }
  36234. }
  36235. _this._clickPosition = undefined;
  36236. };
  36237. }
  36238. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  36239. while (this._treeSubsetDiv.hasChildNodes()) {
  36240. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  36241. }
  36242. // Add meshes
  36243. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  36244. sortedArray.sort(function (a, b) {
  36245. if (a.name === b.name) {
  36246. return 0;
  36247. }
  36248. return (a.name > b.name) ? 1 : -1;
  36249. });
  36250. for (var index = 0; index < sortedArray.length; index++) {
  36251. var mesh = sortedArray[index];
  36252. if (!mesh.isEnabled()) {
  36253. continue;
  36254. }
  36255. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  36256. m.isVisible = element.checked;
  36257. }, mesh);
  36258. }
  36259. };
  36260. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  36261. this._drawingContext.beginPath();
  36262. this._drawingContext.moveTo(zero.x, zero.y);
  36263. this._drawingContext.lineTo(unit.x, unit.y);
  36264. this._drawingContext.strokeStyle = color;
  36265. this._drawingContext.lineWidth = 4;
  36266. this._drawingContext.stroke();
  36267. this._drawingContext.font = "normal 14px Segoe UI";
  36268. this._drawingContext.fillStyle = color;
  36269. this._drawingContext.fillText(label, unitText.x, unitText.y);
  36270. };
  36271. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  36272. var position = mesh.getBoundingInfo().boundingSphere.center;
  36273. var worldMatrix = mesh.getWorldMatrix();
  36274. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  36275. var unit = (unprojectedVector.subtract(position)).length();
  36276. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36277. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36278. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  36279. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36280. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36281. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  36282. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  36283. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  36284. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  36285. };
  36286. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  36287. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  36288. this._drawingContext.font = "normal 12px Segoe UI";
  36289. var textMetrics = this._drawingContext.measureText(text);
  36290. var centerX = projectedPosition.x - textMetrics.width / 2;
  36291. var centerY = projectedPosition.y;
  36292. var clientRect = this._drawingCanvas.getBoundingClientRect();
  36293. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  36294. onClick();
  36295. }
  36296. this._drawingContext.beginPath();
  36297. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  36298. this._drawingContext.fillStyle = getFillStyle();
  36299. this._drawingContext.globalAlpha = 0.5;
  36300. this._drawingContext.fill();
  36301. this._drawingContext.globalAlpha = 1.0;
  36302. this._drawingContext.strokeStyle = '#FFFFFF';
  36303. this._drawingContext.lineWidth = 1;
  36304. this._drawingContext.stroke();
  36305. this._drawingContext.fillStyle = "#FFFFFF";
  36306. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  36307. this._drawingContext.beginPath();
  36308. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  36309. this._drawingContext.fill();
  36310. }
  36311. };
  36312. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  36313. if (!this._clickPosition) {
  36314. return false;
  36315. }
  36316. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  36317. return false;
  36318. }
  36319. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  36320. return false;
  36321. }
  36322. return true;
  36323. };
  36324. DebugLayer.prototype.isVisible = function () {
  36325. return this._enabled;
  36326. };
  36327. DebugLayer.prototype.hide = function () {
  36328. if (!this._enabled) {
  36329. return;
  36330. }
  36331. this._enabled = false;
  36332. var engine = this._scene.getEngine();
  36333. this._scene.unregisterBeforeRender(this._syncData);
  36334. this._scene.unregisterAfterRender(this._syncUI);
  36335. this._rootElement.removeChild(this._globalDiv);
  36336. this._scene.forceShowBoundingBoxes = false;
  36337. this._scene.forceWireframe = false;
  36338. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  36339. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  36340. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  36341. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  36342. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  36343. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  36344. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  36345. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  36346. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  36347. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  36348. this._scene.shadowsEnabled = true;
  36349. this._scene.particlesEnabled = true;
  36350. this._scene.postProcessesEnabled = true;
  36351. this._scene.collisionsEnabled = true;
  36352. this._scene.lightsEnabled = true;
  36353. this._scene.texturesEnabled = true;
  36354. this._scene.lensFlaresEnabled = true;
  36355. this._scene.proceduralTexturesEnabled = true;
  36356. this._scene.renderTargetsEnabled = true;
  36357. this._scene.probesEnabled = true;
  36358. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  36359. this._clearSkeletonViewers();
  36360. };
  36361. DebugLayer.prototype._clearSkeletonViewers = function () {
  36362. for (var index = 0; index < this._skeletonViewers.length; index++) {
  36363. this._skeletonViewers[index].dispose();
  36364. }
  36365. this._skeletonViewers = [];
  36366. };
  36367. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  36368. if (showUI === void 0) { showUI = true; }
  36369. if (camera === void 0) { camera = null; }
  36370. if (rootElement === void 0) { rootElement = null; }
  36371. if (this._enabled) {
  36372. return;
  36373. }
  36374. this._enabled = true;
  36375. if (camera) {
  36376. this._camera = camera;
  36377. }
  36378. else {
  36379. this._camera = this._scene.activeCamera;
  36380. }
  36381. this._showUI = showUI;
  36382. var engine = this._scene.getEngine();
  36383. this._globalDiv = document.createElement("div");
  36384. this._rootElement = rootElement || document.body;
  36385. this._rootElement.appendChild(this._globalDiv);
  36386. this._generateDOMelements();
  36387. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  36388. this._syncPositions();
  36389. this._scene.registerBeforeRender(this._syncData);
  36390. this._scene.registerAfterRender(this._syncUI);
  36391. };
  36392. DebugLayer.prototype._clearLabels = function () {
  36393. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  36394. for (var index = 0; index < this._scene.meshes.length; index++) {
  36395. var mesh = this._scene.meshes[index];
  36396. mesh.renderOverlay = false;
  36397. }
  36398. };
  36399. DebugLayer.prototype._generateheader = function (root, text) {
  36400. var header = document.createElement("div");
  36401. header.innerHTML = text + "&nbsp;";
  36402. header.style.textAlign = "right";
  36403. header.style.width = "100%";
  36404. header.style.color = "white";
  36405. header.style.backgroundColor = "Black";
  36406. header.style.padding = "5px 5px 4px 0px";
  36407. header.style.marginLeft = "-5px";
  36408. header.style.fontWeight = "bold";
  36409. root.appendChild(header);
  36410. };
  36411. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  36412. var label = document.createElement("label");
  36413. label.style.display = "inline";
  36414. label.innerHTML = title;
  36415. label.style.color = color;
  36416. root.appendChild(label);
  36417. root.appendChild(document.createElement("br"));
  36418. };
  36419. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  36420. if (tag === void 0) { tag = null; }
  36421. var label = document.createElement("label");
  36422. label.style.display = "inline";
  36423. var boundingBoxesCheckbox = document.createElement("input");
  36424. boundingBoxesCheckbox.type = "checkbox";
  36425. boundingBoxesCheckbox.checked = initialState;
  36426. boundingBoxesCheckbox.style.display = "inline";
  36427. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  36428. boundingBoxesCheckbox.style.verticalAlign = "sub";
  36429. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  36430. task(evt.target, tag);
  36431. });
  36432. label.appendChild(boundingBoxesCheckbox);
  36433. var container = document.createElement("span");
  36434. var leftPart = document.createElement("span");
  36435. var rightPart = document.createElement("span");
  36436. rightPart.style.cssFloat = "right";
  36437. leftPart.innerHTML = leftTitle;
  36438. rightPart.innerHTML = rightTitle;
  36439. rightPart.style.fontSize = "12px";
  36440. rightPart.style.maxWidth = "200px";
  36441. container.appendChild(leftPart);
  36442. container.appendChild(rightPart);
  36443. label.appendChild(container);
  36444. root.appendChild(label);
  36445. root.appendChild(document.createElement("br"));
  36446. };
  36447. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  36448. if (tag === void 0) { tag = null; }
  36449. var label = document.createElement("label");
  36450. label.style.display = "inline";
  36451. var checkBox = document.createElement("input");
  36452. checkBox.type = "checkbox";
  36453. checkBox.checked = initialState;
  36454. checkBox.style.display = "inline";
  36455. checkBox.style.margin = "0px 5px 0px 0px";
  36456. checkBox.style.verticalAlign = "sub";
  36457. checkBox.addEventListener("change", function (evt) {
  36458. task(evt.target, tag);
  36459. });
  36460. label.appendChild(checkBox);
  36461. label.appendChild(document.createTextNode(title));
  36462. root.appendChild(label);
  36463. root.appendChild(document.createElement("br"));
  36464. };
  36465. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  36466. if (tag === void 0) { tag = null; }
  36467. var button = document.createElement("button");
  36468. button.innerHTML = title;
  36469. button.style.height = "24px";
  36470. button.style.width = "150px";
  36471. button.style.marginBottom = "5px";
  36472. button.style.color = "#444444";
  36473. button.style.border = "1px solid white";
  36474. button.className = "debugLayerButton";
  36475. button.addEventListener("click", function (evt) {
  36476. task(evt.target, tag);
  36477. });
  36478. root.appendChild(button);
  36479. root.appendChild(document.createElement("br"));
  36480. };
  36481. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  36482. if (tag === void 0) { tag = null; }
  36483. var label = document.createElement("label");
  36484. label.style.display = "inline";
  36485. var boundingBoxesRadio = document.createElement("input");
  36486. boundingBoxesRadio.type = "radio";
  36487. boundingBoxesRadio.name = name;
  36488. boundingBoxesRadio.checked = initialState;
  36489. boundingBoxesRadio.style.display = "inline";
  36490. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  36491. boundingBoxesRadio.style.verticalAlign = "sub";
  36492. boundingBoxesRadio.addEventListener("change", function (evt) {
  36493. task(evt.target, tag);
  36494. });
  36495. label.appendChild(boundingBoxesRadio);
  36496. label.appendChild(document.createTextNode(title));
  36497. root.appendChild(label);
  36498. root.appendChild(document.createElement("br"));
  36499. };
  36500. DebugLayer.prototype._generateDOMelements = function () {
  36501. var _this = this;
  36502. this._globalDiv.id = "DebugLayer";
  36503. this._globalDiv.style.position = "absolute";
  36504. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  36505. this._globalDiv.style.fontSize = "14px";
  36506. this._globalDiv.style.color = "white";
  36507. // Drawing canvas
  36508. this._drawingCanvas = document.createElement("canvas");
  36509. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  36510. this._drawingCanvas.style.position = "absolute";
  36511. this._drawingCanvas.style.pointerEvents = "none";
  36512. this._drawingCanvas.style.backgroundColor = "transparent";
  36513. this._drawingContext = this._drawingCanvas.getContext("2d");
  36514. this._globalDiv.appendChild(this._drawingCanvas);
  36515. if (this._showUI) {
  36516. var background = "rgba(128, 128, 128, 0.4)";
  36517. var border = "rgb(180, 180, 180) solid 1px";
  36518. // Stats
  36519. this._statsDiv = document.createElement("div");
  36520. this._statsDiv.id = "DebugLayerStats";
  36521. this._statsDiv.style.border = border;
  36522. this._statsDiv.style.position = "absolute";
  36523. this._statsDiv.style.background = background;
  36524. this._statsDiv.style.padding = "0px 0px 0px 5px";
  36525. this._generateheader(this._statsDiv, "STATISTICS");
  36526. this._statsSubsetDiv = document.createElement("div");
  36527. this._statsSubsetDiv.style.paddingTop = "5px";
  36528. this._statsSubsetDiv.style.paddingBottom = "5px";
  36529. this._statsSubsetDiv.style.overflowY = "auto";
  36530. this._statsDiv.appendChild(this._statsSubsetDiv);
  36531. // Tree
  36532. this._treeDiv = document.createElement("div");
  36533. this._treeDiv.id = "DebugLayerTree";
  36534. this._treeDiv.style.border = border;
  36535. this._treeDiv.style.position = "absolute";
  36536. this._treeDiv.style.background = background;
  36537. this._treeDiv.style.padding = "0px 0px 0px 5px";
  36538. this._treeDiv.style.display = "none";
  36539. this._generateheader(this._treeDiv, "MESHES TREE");
  36540. this._treeSubsetDiv = document.createElement("div");
  36541. this._treeSubsetDiv.style.paddingTop = "5px";
  36542. this._treeSubsetDiv.style.paddingRight = "5px";
  36543. this._treeSubsetDiv.style.overflowY = "auto";
  36544. this._treeSubsetDiv.style.maxHeight = "300px";
  36545. this._treeDiv.appendChild(this._treeSubsetDiv);
  36546. this._needToRefreshMeshesTree = true;
  36547. // Logs
  36548. this._logDiv = document.createElement("div");
  36549. this._logDiv.style.border = border;
  36550. this._logDiv.id = "DebugLayerLogs";
  36551. this._logDiv.style.position = "absolute";
  36552. this._logDiv.style.background = background;
  36553. this._logDiv.style.padding = "0px 0px 0px 5px";
  36554. this._logDiv.style.display = "none";
  36555. this._generateheader(this._logDiv, "LOGS");
  36556. this._logSubsetDiv = document.createElement("div");
  36557. this._logSubsetDiv.style.height = "127px";
  36558. this._logSubsetDiv.style.paddingTop = "5px";
  36559. this._logSubsetDiv.style.overflowY = "auto";
  36560. this._logSubsetDiv.style.fontSize = "12px";
  36561. this._logSubsetDiv.style.fontFamily = "consolas";
  36562. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  36563. this._logDiv.appendChild(this._logSubsetDiv);
  36564. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  36565. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  36566. };
  36567. // Options
  36568. this._optionsDiv = document.createElement("div");
  36569. this._optionsDiv.id = "DebugLayerOptions";
  36570. this._optionsDiv.style.border = border;
  36571. this._optionsDiv.style.position = "absolute";
  36572. this._optionsDiv.style.background = background;
  36573. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  36574. this._optionsDiv.style.overflowY = "auto";
  36575. this._generateheader(this._optionsDiv, "OPTIONS");
  36576. this._optionsSubsetDiv = document.createElement("div");
  36577. this._optionsSubsetDiv.style.paddingTop = "5px";
  36578. this._optionsSubsetDiv.style.paddingBottom = "5px";
  36579. this._optionsSubsetDiv.style.overflowY = "auto";
  36580. this._optionsSubsetDiv.style.maxHeight = "200px";
  36581. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  36582. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  36583. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  36584. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  36585. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  36586. _this._displayTree = element.checked;
  36587. _this._needToRefreshMeshesTree = true;
  36588. });
  36589. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36590. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  36591. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  36592. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  36593. _this._labelsEnabled = element.checked;
  36594. if (!_this._labelsEnabled) {
  36595. _this._clearLabels();
  36596. }
  36597. });
  36598. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  36599. if (element.checked) {
  36600. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  36601. }
  36602. else {
  36603. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  36604. }
  36605. });
  36606. ;
  36607. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36608. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  36609. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  36610. if (element.checked) {
  36611. _this._scene.forceWireframe = false;
  36612. _this._scene.forcePointsCloud = false;
  36613. }
  36614. });
  36615. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  36616. if (element.checked) {
  36617. _this._scene.forceWireframe = true;
  36618. _this._scene.forcePointsCloud = false;
  36619. }
  36620. });
  36621. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  36622. if (element.checked) {
  36623. _this._scene.forceWireframe = false;
  36624. _this._scene.forcePointsCloud = true;
  36625. }
  36626. });
  36627. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36628. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  36629. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  36630. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  36631. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  36632. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  36633. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  36634. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  36635. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  36636. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  36637. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  36638. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  36639. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  36640. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36641. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  36642. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  36643. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  36644. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  36645. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  36646. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  36647. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  36648. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  36649. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  36650. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  36651. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  36652. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  36653. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  36654. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  36655. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  36656. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  36657. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36658. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  36659. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  36660. if (element.checked) {
  36661. _this._scene.headphone = true;
  36662. }
  36663. });
  36664. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  36665. if (element.checked) {
  36666. _this._scene.headphone = false;
  36667. }
  36668. });
  36669. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  36670. _this._scene.audioEnabled = !element.checked;
  36671. });
  36672. }
  36673. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36674. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  36675. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  36676. if (!element.checked) {
  36677. _this._clearSkeletonViewers();
  36678. return;
  36679. }
  36680. for (var index = 0; index < _this._scene.meshes.length; index++) {
  36681. var mesh = _this._scene.meshes[index];
  36682. if (mesh.skeleton) {
  36683. var found = false;
  36684. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  36685. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  36686. found = true;
  36687. break;
  36688. }
  36689. }
  36690. if (found) {
  36691. continue;
  36692. }
  36693. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  36694. viewer.isEnabled = true;
  36695. _this._skeletonViewers.push(viewer);
  36696. }
  36697. }
  36698. });
  36699. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36700. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  36701. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  36702. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  36703. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  36704. if (_this._camera) {
  36705. console.log(_this._camera);
  36706. }
  36707. else {
  36708. console.warn("No camera defined, or debug layer created before camera creation!");
  36709. }
  36710. });
  36711. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36712. this._globalDiv.appendChild(this._statsDiv);
  36713. this._globalDiv.appendChild(this._logDiv);
  36714. this._globalDiv.appendChild(this._optionsDiv);
  36715. this._globalDiv.appendChild(this._treeDiv);
  36716. }
  36717. };
  36718. DebugLayer.prototype._displayStats = function () {
  36719. var scene = this._scene;
  36720. var engine = scene.getEngine();
  36721. var glInfo = engine.getGlInfo();
  36722. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  36723. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36724. + "<b>Count</b><br>"
  36725. + "Total meshes: " + scene.meshes.length + "<br>"
  36726. + "Total lights: " + scene.lights.length + "<br>"
  36727. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  36728. + "Total materials: " + scene.materials.length + "<br>"
  36729. + "Total textures: " + scene.textures.length + "<br>"
  36730. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  36731. + "Active indices: " + scene.getActiveIndices() + "<br>"
  36732. + "Active bones: " + scene.getActiveBones() + "<br>"
  36733. + "Active particles: " + scene.getActiveParticles() + "<br>"
  36734. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  36735. + "<b>Duration</b><br>"
  36736. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  36737. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  36738. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  36739. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  36740. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  36741. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  36742. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  36743. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  36744. + "</div>"
  36745. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36746. + "<b>Extensions</b><br>"
  36747. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  36748. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  36749. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  36750. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  36751. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  36752. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  36753. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  36754. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  36755. + "</div><br>"
  36756. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36757. + "<b>Caps.</b><br>"
  36758. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  36759. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  36760. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  36761. + "<b>Info</b><br>"
  36762. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  36763. + glInfo.version + "<br>"
  36764. + "</div><br>"
  36765. + glInfo.renderer + "<br>";
  36766. if (this.customStatsFunction) {
  36767. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  36768. }
  36769. };
  36770. return DebugLayer;
  36771. })();
  36772. BABYLON.DebugLayer = DebugLayer;
  36773. })(BABYLON || (BABYLON = {}));
  36774. var BABYLON;
  36775. (function (BABYLON) {
  36776. var SIMDVector3 = (function () {
  36777. function SIMDVector3() {
  36778. }
  36779. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  36780. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  36781. var m0 = SIMD.float32x4.load(transformation.m, 0);
  36782. var m1 = SIMD.float32x4.load(transformation.m, 4);
  36783. var m2 = SIMD.float32x4.load(transformation.m, 8);
  36784. var m3 = SIMD.float32x4.load(transformation.m, 12);
  36785. 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));
  36786. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  36787. SIMD.float32x4.storeXYZ(result._data, 0, r);
  36788. };
  36789. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  36790. var v0 = SIMD.float32x4.splat(x);
  36791. var v1 = SIMD.float32x4.splat(y);
  36792. var v2 = SIMD.float32x4.splat(z);
  36793. var m0 = SIMD.float32x4.load(transformation.m, 0);
  36794. var m1 = SIMD.float32x4.load(transformation.m, 4);
  36795. var m2 = SIMD.float32x4.load(transformation.m, 8);
  36796. var m3 = SIMD.float32x4.load(transformation.m, 12);
  36797. 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));
  36798. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  36799. SIMD.float32x4.storeXYZ(result._data, 0, r);
  36800. };
  36801. return SIMDVector3;
  36802. })();
  36803. BABYLON.SIMDVector3 = SIMDVector3;
  36804. var SIMDMatrix = (function () {
  36805. function SIMDMatrix() {
  36806. }
  36807. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  36808. if (offset === void 0) { offset = 0; }
  36809. var tm = this.m;
  36810. var om = other.m;
  36811. var om0 = SIMD.float32x4.load(om, 0);
  36812. var om1 = SIMD.float32x4.load(om, 4);
  36813. var om2 = SIMD.float32x4.load(om, 8);
  36814. var om3 = SIMD.float32x4.load(om, 12);
  36815. var tm0 = SIMD.float32x4.load(tm, 0);
  36816. 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)))));
  36817. var tm1 = SIMD.float32x4.load(tm, 4);
  36818. 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)))));
  36819. var tm2 = SIMD.float32x4.load(tm, 8);
  36820. 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)))));
  36821. var tm3 = SIMD.float32x4.load(tm, 12);
  36822. 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)))));
  36823. };
  36824. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  36825. var src = this.m;
  36826. var dest = other.m;
  36827. var row0, row1, row2, row3;
  36828. var tmp1;
  36829. var minor0, minor1, minor2, minor3;
  36830. var det;
  36831. // Load the 4 rows
  36832. var src0 = SIMD.float32x4.load(src, 0);
  36833. var src1 = SIMD.float32x4.load(src, 4);
  36834. var src2 = SIMD.float32x4.load(src, 8);
  36835. var src3 = SIMD.float32x4.load(src, 12);
  36836. // Transpose the source matrix. Sort of. Not a true transpose operation
  36837. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  36838. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  36839. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  36840. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  36841. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  36842. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  36843. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  36844. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  36845. // This is a true transposition, but it will lead to an incorrect result
  36846. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  36847. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  36848. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  36849. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  36850. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  36851. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  36852. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  36853. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  36854. // ----
  36855. tmp1 = SIMD.float32x4.mul(row2, row3);
  36856. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36857. minor0 = SIMD.float32x4.mul(row1, tmp1);
  36858. minor1 = SIMD.float32x4.mul(row0, tmp1);
  36859. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36860. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  36861. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  36862. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  36863. // ----
  36864. tmp1 = SIMD.float32x4.mul(row1, row2);
  36865. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36866. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  36867. minor3 = SIMD.float32x4.mul(row0, tmp1);
  36868. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36869. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  36870. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  36871. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  36872. // ----
  36873. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  36874. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36875. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  36876. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  36877. minor2 = SIMD.float32x4.mul(row0, tmp1);
  36878. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36879. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  36880. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  36881. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  36882. // ----
  36883. tmp1 = SIMD.float32x4.mul(row0, row1);
  36884. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36885. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  36886. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  36887. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36888. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  36889. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  36890. // ----
  36891. tmp1 = SIMD.float32x4.mul(row0, row3);
  36892. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36893. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  36894. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  36895. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36896. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  36897. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  36898. // ----
  36899. tmp1 = SIMD.float32x4.mul(row0, row2);
  36900. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36901. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  36902. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  36903. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36904. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  36905. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  36906. // Compute determinant
  36907. det = SIMD.float32x4.mul(row0, minor0);
  36908. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  36909. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  36910. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  36911. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  36912. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  36913. // These shuffles aren't necessary if the faulty transposition is done
  36914. // up at the top of this function.
  36915. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  36916. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  36917. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  36918. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  36919. // Compute final values by multiplying with 1/det
  36920. minor0 = SIMD.float32x4.mul(det, minor0);
  36921. minor1 = SIMD.float32x4.mul(det, minor1);
  36922. minor2 = SIMD.float32x4.mul(det, minor2);
  36923. minor3 = SIMD.float32x4.mul(det, minor3);
  36924. SIMD.float32x4.store(dest, 0, minor0);
  36925. SIMD.float32x4.store(dest, 4, minor1);
  36926. SIMD.float32x4.store(dest, 8, minor2);
  36927. SIMD.float32x4.store(dest, 12, minor3);
  36928. return this;
  36929. };
  36930. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  36931. var out = result.m;
  36932. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  36933. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  36934. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  36935. // cc.kmVec3Subtract(f, pCenter, pEye);
  36936. var f = SIMD.float32x4.sub(center, eye);
  36937. // cc.kmVec3Normalize(f, f);
  36938. var tmp = SIMD.float32x4.mul(f, f);
  36939. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36940. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36941. // cc.kmVec3Assign(up, pUp);
  36942. // cc.kmVec3Normalize(up, up);
  36943. tmp = SIMD.float32x4.mul(up, up);
  36944. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36945. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36946. // cc.kmVec3Cross(s, f, up);
  36947. 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)));
  36948. // cc.kmVec3Normalize(s, s);
  36949. tmp = SIMD.float32x4.mul(s, s);
  36950. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36951. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36952. // cc.kmVec3Cross(u, s, f);
  36953. 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)));
  36954. // cc.kmVec3Normalize(s, s);
  36955. tmp = SIMD.float32x4.mul(s, s);
  36956. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36957. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36958. var zero = SIMD.float32x4.splat(0.0);
  36959. s = SIMD.float32x4.neg(s);
  36960. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  36961. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  36962. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  36963. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  36964. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  36965. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  36966. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  36967. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  36968. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  36969. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  36970. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  36971. var b3 = SIMD.float32x4.neg(eye);
  36972. b3 = SIMD.float32x4.withW(b3, 1.0);
  36973. 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)))));
  36974. 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)))));
  36975. 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)))));
  36976. 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)))));
  36977. };
  36978. return SIMDMatrix;
  36979. })();
  36980. BABYLON.SIMDMatrix = SIMDMatrix;
  36981. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  36982. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  36983. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  36984. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  36985. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  36986. var SIMDHelper = (function () {
  36987. function SIMDHelper() {
  36988. }
  36989. Object.defineProperty(SIMDHelper, "IsEnabled", {
  36990. get: function () {
  36991. return SIMDHelper._isEnabled;
  36992. },
  36993. enumerable: true,
  36994. configurable: true
  36995. });
  36996. SIMDHelper.DisableSIMD = function () {
  36997. // Replace functions
  36998. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  36999. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  37000. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  37001. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  37002. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  37003. SIMDHelper._isEnabled = false;
  37004. };
  37005. SIMDHelper.EnableSIMD = function () {
  37006. if (window.SIMD === undefined) {
  37007. return;
  37008. }
  37009. // Replace functions
  37010. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  37011. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  37012. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  37013. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  37014. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  37015. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  37016. get: function () { return this._data[0]; },
  37017. set: function (value) {
  37018. if (!this._data) {
  37019. this._data = new Float32Array(3);
  37020. }
  37021. this._data[0] = value;
  37022. }
  37023. });
  37024. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  37025. get: function () { return this._data[1]; },
  37026. set: function (value) {
  37027. this._data[1] = value;
  37028. }
  37029. });
  37030. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  37031. get: function () { return this._data[2]; },
  37032. set: function (value) {
  37033. this._data[2] = value;
  37034. }
  37035. });
  37036. SIMDHelper._isEnabled = true;
  37037. };
  37038. SIMDHelper._isEnabled = false;
  37039. return SIMDHelper;
  37040. })();
  37041. BABYLON.SIMDHelper = SIMDHelper;
  37042. })(BABYLON || (BABYLON = {}));
  37043. var BABYLON;
  37044. (function (BABYLON) {
  37045. /**
  37046. * This class describe a rectangle that were added to the map.
  37047. * You have access to its coordinates either in pixel or normalized (UV)
  37048. */
  37049. var PackedRect = (function () {
  37050. function PackedRect(root, parent, pos, size) {
  37051. this._pos = pos;
  37052. this._size = size;
  37053. this._root = root;
  37054. this._parent = parent;
  37055. }
  37056. Object.defineProperty(PackedRect.prototype, "pos", {
  37057. /**
  37058. * @returns the position of this node into the map
  37059. */
  37060. get: function () {
  37061. return this._pos;
  37062. },
  37063. enumerable: true,
  37064. configurable: true
  37065. });
  37066. Object.defineProperty(PackedRect.prototype, "contentSize", {
  37067. /**
  37068. * @returns the size of the rectangle this node handles
  37069. */
  37070. get: function () {
  37071. return this._contentSize;
  37072. },
  37073. enumerable: true,
  37074. configurable: true
  37075. });
  37076. Object.defineProperty(PackedRect.prototype, "UVs", {
  37077. /**
  37078. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  37079. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  37080. */
  37081. get: function () {
  37082. return this.getUVsForCustomSize(this._root._size);
  37083. },
  37084. enumerable: true,
  37085. configurable: true
  37086. });
  37087. /**
  37088. * 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.
  37089. * This method will return the UVs for this part by given the custom size of what you really use
  37090. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  37091. */
  37092. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  37093. var mainWidth = this._root._size.width;
  37094. var mainHeight = this._root._size.height;
  37095. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  37096. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  37097. var uvs = new Array();
  37098. uvs.push(topLeft);
  37099. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  37100. uvs.push(rightBottom);
  37101. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  37102. return uvs;
  37103. };
  37104. /**
  37105. * Free this rectangle from the map.
  37106. * Call this method when you no longer need the rectangle to be in the map.
  37107. */
  37108. PackedRect.prototype.freeContent = function () {
  37109. if (!this.contentSize) {
  37110. return;
  37111. }
  37112. this._contentSize = null;
  37113. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  37114. this.attemptDefrag();
  37115. };
  37116. Object.defineProperty(PackedRect.prototype, "isUsed", {
  37117. get: function () {
  37118. return this._contentSize != null || this._leftNode != null;
  37119. },
  37120. enumerable: true,
  37121. configurable: true
  37122. });
  37123. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  37124. var node = this.findNode(contentSize);
  37125. // Not enough space...
  37126. if (!node) {
  37127. return null;
  37128. }
  37129. node.splitNode(contentSize);
  37130. return node;
  37131. };
  37132. PackedRect.prototype.findNode = function (size) {
  37133. var resNode = null;
  37134. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  37135. if (this.isUsed) {
  37136. if (this._leftNode) {
  37137. resNode = this._leftNode.findNode(size);
  37138. }
  37139. if (!resNode && this._rightNode) {
  37140. resNode = this._rightNode.findNode(size);
  37141. }
  37142. if (!resNode && this._bottomNode) {
  37143. resNode = this._bottomNode.findNode(size);
  37144. }
  37145. }
  37146. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  37147. resNode = this;
  37148. }
  37149. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  37150. resNode = this;
  37151. }
  37152. return resNode;
  37153. };
  37154. PackedRect.prototype.splitNode = function (contentSize) {
  37155. // 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)
  37156. if (!this._contentSize && this._initialSize) {
  37157. 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));
  37158. return this._leftNode.splitNode(contentSize);
  37159. }
  37160. else {
  37161. this._contentSize = contentSize.clone();
  37162. this._initialSize = contentSize.clone();
  37163. if (contentSize.width !== this._size.width) {
  37164. 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));
  37165. }
  37166. if (contentSize.height !== this._size.height) {
  37167. 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));
  37168. }
  37169. return this;
  37170. }
  37171. };
  37172. PackedRect.prototype.attemptDefrag = function () {
  37173. if (!this.isUsed && this.isRecursiveFree) {
  37174. this.clearNode();
  37175. if (this._parent) {
  37176. this._parent.attemptDefrag();
  37177. }
  37178. }
  37179. };
  37180. PackedRect.prototype.clearNode = function () {
  37181. this._initialSize = null;
  37182. this._rightNode = null;
  37183. this._bottomNode = null;
  37184. };
  37185. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  37186. get: function () {
  37187. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  37188. },
  37189. enumerable: true,
  37190. configurable: true
  37191. });
  37192. PackedRect.prototype.evalFreeSize = function (size) {
  37193. var levelSize = 0;
  37194. if (!this.isUsed) {
  37195. if (this._initialSize) {
  37196. levelSize = this._initialSize.surface;
  37197. }
  37198. else {
  37199. levelSize = this._size.surface;
  37200. }
  37201. }
  37202. if (this._rightNode) {
  37203. levelSize += this._rightNode.evalFreeSize(0);
  37204. }
  37205. if (this._bottomNode) {
  37206. levelSize += this._bottomNode.evalFreeSize(0);
  37207. }
  37208. return levelSize + size;
  37209. };
  37210. return PackedRect;
  37211. })();
  37212. BABYLON.PackedRect = PackedRect;
  37213. /**
  37214. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  37215. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  37216. * 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.
  37217. */
  37218. var RectPackingMap = (function (_super) {
  37219. __extends(RectPackingMap, _super);
  37220. /**
  37221. * Create an instance of the object with a dimension using the given size
  37222. * @param size The dimension of the rectangle that will contain all the sub ones.
  37223. */
  37224. function RectPackingMap(size) {
  37225. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  37226. this._root = this;
  37227. }
  37228. /**
  37229. * Add a rectangle, finding the best location to store it into the map
  37230. * @param size the dimension of the rectangle to store
  37231. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  37232. */
  37233. RectPackingMap.prototype.addRect = function (size) {
  37234. var node = this.findAndSplitNode(size);
  37235. return node;
  37236. };
  37237. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  37238. /**
  37239. * Return the current space free normalized between [0;1]
  37240. * @returns {}
  37241. */
  37242. get: function () {
  37243. var freeSize = 0;
  37244. freeSize = this.evalFreeSize(freeSize);
  37245. return freeSize / (this._size.width * this._size.height);
  37246. },
  37247. enumerable: true,
  37248. configurable: true
  37249. });
  37250. return RectPackingMap;
  37251. })(PackedRect);
  37252. BABYLON.RectPackingMap = RectPackingMap;
  37253. })(BABYLON || (BABYLON = {}));
  37254. var BABYLON;
  37255. (function (BABYLON) {
  37256. var DynamicFloatArrayElementInfo = (function () {
  37257. function DynamicFloatArrayElementInfo() {
  37258. }
  37259. return DynamicFloatArrayElementInfo;
  37260. })();
  37261. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  37262. /**
  37263. * 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.
  37264. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  37265. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  37266. * 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.
  37267. * 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.
  37268. * 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".
  37269. */
  37270. var DynamicFloatArray = (function () {
  37271. /**
  37272. * Construct an instance of the dynamic float array
  37273. * @param stride size of one element in float (i.e. not bytes!)
  37274. * @param initialElementCount the number of available entries at construction
  37275. */
  37276. function DynamicFloatArray(stride, initialElementCount) {
  37277. this.compareValueOffset = null;
  37278. this.sortingAscending = true;
  37279. this._stride = stride;
  37280. this.buffer = new Float32Array(stride * initialElementCount);
  37281. this._lastUsed = 0;
  37282. this._firstFree = 0;
  37283. this._allEntries = new Array(initialElementCount);
  37284. this._freeEntries = new Array(initialElementCount);
  37285. for (var i = 0; i < initialElementCount; i++) {
  37286. var element = new DynamicFloatArrayElementInfo();
  37287. element.offset = i * stride;
  37288. this._allEntries[i] = element;
  37289. this._freeEntries[initialElementCount - i - 1] = element;
  37290. }
  37291. }
  37292. /**
  37293. * Allocate an element in the array.
  37294. * @return the element info instance that contains the offset into the main buffer of the element's location.
  37295. * Beware, this offset may change when you call pack()
  37296. */
  37297. DynamicFloatArray.prototype.allocElement = function () {
  37298. if (this._freeEntries.length === 0) {
  37299. this._growBuffer();
  37300. }
  37301. var el = this._freeEntries.pop();
  37302. this._lastUsed = Math.max(el.offset, this._lastUsed);
  37303. if (el.offset === this._firstFree) {
  37304. if (this._freeEntries.length > 0) {
  37305. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  37306. }
  37307. else {
  37308. this._firstFree += this._stride;
  37309. }
  37310. }
  37311. return el;
  37312. };
  37313. /**
  37314. * Free the element corresponding to the given element info
  37315. * @param elInfo the element that describe the allocated element
  37316. */
  37317. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  37318. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  37319. this._freeEntries.push(elInfo);
  37320. };
  37321. /**
  37322. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  37323. * 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().
  37324. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  37325. */
  37326. DynamicFloatArray.prototype.pack = function () {
  37327. // no free slot? no need to pack
  37328. if (this._freeEntries.length === 0) {
  37329. return this.buffer;
  37330. }
  37331. // If the buffer is already packed the last used will always be lower than the first free
  37332. // 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.
  37333. if (this._lastUsed < this._firstFree) {
  37334. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  37335. return elementsBuffer_1;
  37336. }
  37337. var s = this._stride;
  37338. // 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
  37339. var lastFree = new DynamicFloatArrayElementInfo();
  37340. lastFree.offset = this.totalElementCount * s;
  37341. this._freeEntries.push(lastFree);
  37342. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  37343. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37344. var firstFreeSlotOffset = sortedFree[0].offset;
  37345. var freeZoneSize = 1;
  37346. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  37347. var prevOffset = sortedFree[0].offset;
  37348. for (var i = 1; i < sortedFree.length; i++) {
  37349. // 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
  37350. if (firstFreeSlotOffset >= occupiedZoneSize) {
  37351. break;
  37352. }
  37353. var curFree = sortedFree[i];
  37354. var curOffset = curFree.offset;
  37355. // Compute the distance between this offset and the previous
  37356. var distance = curOffset - prevOffset;
  37357. // If the distance is the stride size, they are adjacent, it good, move to the next
  37358. if (distance === s) {
  37359. // Free zone is one element bigger
  37360. ++freeZoneSize;
  37361. // as we're about to iterate to the next, the cur becomes the previous...
  37362. prevOffset = curOffset;
  37363. continue;
  37364. }
  37365. // Distance is bigger, which means there's x element between the previous free and this one
  37366. var usedRange = (distance / s) - 1;
  37367. // Two cases the free zone is smaller than the data to move or bigger
  37368. // Copy what can fit in the free zone
  37369. var curMoveOffset = curOffset - s;
  37370. var copyCount = Math.min(freeZoneSize, usedRange);
  37371. for (var j = 0; j < copyCount; j++) {
  37372. var freeI = firstFreeSlotOffset / s;
  37373. var curI = curMoveOffset / s;
  37374. var moveEl = sortedAll[curI];
  37375. this._moveElement(moveEl, firstFreeSlotOffset);
  37376. var replacedEl = sortedAll[freeI];
  37377. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  37378. replacedEl.offset = curMoveOffset;
  37379. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  37380. sortedAll[freeI] = moveEl;
  37381. sortedAll[curI] = replacedEl;
  37382. curMoveOffset -= s;
  37383. firstFreeSlotOffset += s;
  37384. }
  37385. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  37386. if (freeZoneSize <= usedRange) {
  37387. firstFreeSlotOffset = curMoveOffset + s;
  37388. freeZoneSize = 1 + copyCount;
  37389. }
  37390. else {
  37391. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  37392. }
  37393. // as we're about to iterate to the next, the cur becomes the previous...
  37394. prevOffset = curOffset;
  37395. }
  37396. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  37397. this._lastUsed = firstFreeSlotOffset - s;
  37398. this._firstFree = firstFreeSlotOffset;
  37399. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  37400. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  37401. this._allEntries = sortedAll;
  37402. return elementsBuffer;
  37403. };
  37404. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  37405. for (var i = 0; i < this._stride; i++) {
  37406. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  37407. }
  37408. element.offset = destOffset;
  37409. };
  37410. DynamicFloatArray.prototype._growBuffer = function () {
  37411. // Allocate the new buffer with 50% more entries, copy the content of the current one
  37412. var newElCount = Math.floor(this.totalElementCount * 1.5);
  37413. var newBuffer = new Float32Array(newElCount * this._stride);
  37414. newBuffer.set(this.buffer);
  37415. var curCount = this.totalElementCount;
  37416. var addedCount = newElCount - this.totalElementCount;
  37417. for (var i = 0; i < addedCount; i++) {
  37418. var element = new DynamicFloatArrayElementInfo();
  37419. element.offset = (curCount + i) * this.stride;
  37420. this._allEntries.push(element);
  37421. this._freeEntries[addedCount - i - 1] = element;
  37422. }
  37423. this._firstFree = curCount * this.stride;
  37424. this.buffer = newBuffer;
  37425. };
  37426. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  37427. /**
  37428. * Get the total count of entries that can fit in the current buffer
  37429. * @returns the elements count
  37430. */
  37431. get: function () {
  37432. return this._allEntries.length;
  37433. },
  37434. enumerable: true,
  37435. configurable: true
  37436. });
  37437. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  37438. /**
  37439. * Get the count of free entries that can still be allocated without resizing the buffer
  37440. * @returns the free elements count
  37441. */
  37442. get: function () {
  37443. return this._freeEntries.length;
  37444. },
  37445. enumerable: true,
  37446. configurable: true
  37447. });
  37448. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  37449. /**
  37450. * Get the count of allocated elements
  37451. * @returns the allocated elements count
  37452. */
  37453. get: function () {
  37454. return this._allEntries.length - this._freeEntries.length;
  37455. },
  37456. enumerable: true,
  37457. configurable: true
  37458. });
  37459. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  37460. /**
  37461. * Return the size of one element in float
  37462. * @returns the size in float
  37463. */
  37464. get: function () {
  37465. return this._stride;
  37466. },
  37467. enumerable: true,
  37468. configurable: true
  37469. });
  37470. DynamicFloatArray.prototype.sort = function () {
  37471. var _this = this;
  37472. if (!this.compareValueOffset) {
  37473. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  37474. }
  37475. var count = this.usedElementCount;
  37476. // Do we have to (re)create the sort table?
  37477. if (!this._sortTable || this._sortTable.length < count) {
  37478. // 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...
  37479. var newCount = Math.min(this.totalElementCount, count * 2);
  37480. this._sortTable = new Array(newCount);
  37481. }
  37482. if (!this._sortedTable || this._sortedTable.length !== count) {
  37483. this._sortedTable = new Array(count);
  37484. }
  37485. // Because, you know...
  37486. this.pack();
  37487. //let stride = this.stride;
  37488. //for (let i = 0; i < count; i++) {
  37489. // let si = this._sortTable[i];
  37490. // if (!si) {
  37491. // si = new SortInfo();
  37492. // this._sortTable[i] = si;
  37493. // }
  37494. // si.entry = this._allEntries[i];
  37495. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  37496. // si.swapedOffset = null;
  37497. // this._sortedTable[i] = si;
  37498. //}
  37499. var curOffset = 0;
  37500. var stride = this.stride;
  37501. for (var i = 0; i < count; i++, curOffset += stride) {
  37502. var si = this._sortTable[i];
  37503. if (!si) {
  37504. si = new SortInfo();
  37505. this._sortTable[i] = si;
  37506. }
  37507. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  37508. si.offset = curOffset;
  37509. si.swapedOffset = null;
  37510. this._sortedTable[i] = si;
  37511. }
  37512. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  37513. if (this.sortingAscending) {
  37514. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  37515. }
  37516. else {
  37517. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  37518. }
  37519. var swapElements = function (src, dst) {
  37520. for (var i = 0; i < stride; i++) {
  37521. var tps = _this.buffer[dst + i];
  37522. _this.buffer[dst + i] = _this.buffer[src + i];
  37523. _this.buffer[src + i] = tps;
  37524. }
  37525. };
  37526. // 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:
  37527. // 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),
  37528. // and I still want something with a good algorithm complexity.
  37529. // 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,
  37530. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  37531. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  37532. // 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
  37533. // until we find a SortInfo object without a swapedOffset which means we got the right location
  37534. // 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
  37535. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  37536. for (var i = 0; i < count; i++) {
  37537. // Get the element to move
  37538. var sourceSI = this._sortedTable[i];
  37539. var destSI = this._sortTable[i];
  37540. var sourceOff = sourceSI.offset;
  37541. // If the source changed location, find the new one
  37542. if (sourceSI.swapedOffset) {
  37543. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  37544. var curSI = sourceSI;
  37545. while (curSI.swapedOffset) {
  37546. curSI = this._sortTable[curSI.swapedOffset / stride];
  37547. }
  37548. // Finally get the right location
  37549. sourceOff = curSI.offset;
  37550. }
  37551. // Tag the element being replaced with its new location
  37552. destSI.swapedOffset = sourceOff;
  37553. // Swap elements (only if needed)
  37554. if (sourceOff !== destSI.offset) {
  37555. swapElements(sourceOff, destSI.offset);
  37556. }
  37557. // Update the offset in the corresponding DFAE
  37558. //sourceSI.entry.offset = destSI.entry.offset;
  37559. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  37560. }
  37561. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37562. return true;
  37563. };
  37564. return DynamicFloatArray;
  37565. })();
  37566. BABYLON.DynamicFloatArray = DynamicFloatArray;
  37567. var SortInfo = (function () {
  37568. function SortInfo() {
  37569. this.compareData = this.offset = this.swapedOffset = null;
  37570. }
  37571. return SortInfo;
  37572. })();
  37573. })(BABYLON || (BABYLON = {}));
  37574. var BABYLON;
  37575. (function (BABYLON) {
  37576. /**
  37577. * This class given information about a given character.
  37578. */
  37579. var CharInfo = (function () {
  37580. function CharInfo() {
  37581. }
  37582. return CharInfo;
  37583. })();
  37584. BABYLON.CharInfo = CharInfo;
  37585. var FontTexture = (function (_super) {
  37586. __extends(FontTexture, _super);
  37587. /**
  37588. * Create a new instance of the FontTexture class
  37589. * @param name the name of the texture
  37590. * @param font the font to use, use the W3C CSS notation
  37591. * @param scene the scene that owns the texture
  37592. * @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
  37593. * @param samplingMode the texture sampling mode
  37594. * @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.
  37595. */
  37596. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  37597. if (maxCharCount === void 0) { maxCharCount = 200; }
  37598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37599. if (superSample === void 0) { superSample = false; }
  37600. _super.call(this, null, scene, true, false, samplingMode);
  37601. this._charInfos = {};
  37602. this._curCharCount = 0;
  37603. this._lastUpdateCharCount = -1;
  37604. this._usedCounter = 1;
  37605. this.name = name;
  37606. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37607. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37608. this._superSample = false;
  37609. if (superSample) {
  37610. var sfont = this.getSuperSampleFont(font);
  37611. if (sfont) {
  37612. this._superSample = true;
  37613. font = sfont;
  37614. }
  37615. }
  37616. // First canvas creation to determine the size of the texture to create
  37617. this._canvas = document.createElement("canvas");
  37618. this._context = this._canvas.getContext("2d");
  37619. this._context.font = font;
  37620. this._context.fillStyle = "white";
  37621. this._cachedFontId = null;
  37622. var res = this.getFontHeight(font);
  37623. this._lineHeightSuper = res.height;
  37624. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  37625. this._offset = res.offset - 1;
  37626. var maxCharWidth = this._context.measureText("W").width;
  37627. this._spaceWidthSuper = this._context.measureText(" ").width;
  37628. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  37629. // This is an approximate size, but should always be able to fit at least the maxCharCount
  37630. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  37631. var edge = Math.sqrt(totalEstSurface);
  37632. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  37633. // Create the texture that will store the font characters
  37634. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  37635. var textureSize = this.getSize();
  37636. this.hasAlpha = true;
  37637. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  37638. this._canvas = document.createElement("canvas");
  37639. this._canvas.width = textureSize.width;
  37640. this._canvas.height = textureSize.height;
  37641. this._context = this._canvas.getContext("2d");
  37642. this._context.textBaseline = "top";
  37643. this._context.font = font;
  37644. this._context.fillStyle = "white";
  37645. this._context.imageSmoothingEnabled = false;
  37646. this._currentFreePosition = BABYLON.Vector2.Zero();
  37647. // Add the basic ASCII based characters
  37648. for (var i = 0x20; i < 0x7F; i++) {
  37649. var c = String.fromCharCode(i);
  37650. this.getChar(c);
  37651. }
  37652. this.update();
  37653. }
  37654. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  37655. get: function () {
  37656. return this._superSample;
  37657. },
  37658. enumerable: true,
  37659. configurable: true
  37660. });
  37661. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  37662. get: function () {
  37663. return this._spaceWidth;
  37664. },
  37665. enumerable: true,
  37666. configurable: true
  37667. });
  37668. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  37669. get: function () {
  37670. return this._lineHeight;
  37671. },
  37672. enumerable: true,
  37673. configurable: true
  37674. });
  37675. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  37676. if (supersample === void 0) { supersample = false; }
  37677. var s = scene;
  37678. if (!s.__fontTextureCache__) {
  37679. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  37680. }
  37681. var dic = s.__fontTextureCache__;
  37682. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  37683. var ft = dic.get(lfn);
  37684. if (ft) {
  37685. ++ft._usedCounter;
  37686. return ft;
  37687. }
  37688. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  37689. ft._cachedFontId = lfn;
  37690. dic.add(lfn, ft);
  37691. return ft;
  37692. };
  37693. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  37694. if (supersample === void 0) { supersample = false; }
  37695. var s = scene;
  37696. var dic = s.__fontTextureCache__;
  37697. if (!dic) {
  37698. return;
  37699. }
  37700. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  37701. var font = dic.get(lfn);
  37702. if (--font._usedCounter === 0) {
  37703. dic.remove(lfn);
  37704. font.dispose();
  37705. }
  37706. };
  37707. /**
  37708. * Make sure the given char is present in the font map.
  37709. * @param char the character to get or add
  37710. * @return the CharInfo instance corresponding to the given character
  37711. */
  37712. FontTexture.prototype.getChar = function (char) {
  37713. if (char.length !== 1) {
  37714. return null;
  37715. }
  37716. var info = this._charInfos[char];
  37717. if (info) {
  37718. return info;
  37719. }
  37720. info = new CharInfo();
  37721. var measure = this._context.measureText(char);
  37722. var textureSize = this.getSize();
  37723. // we reached the end of the current line?
  37724. var width = Math.round(measure.width);
  37725. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  37726. var yMargin = xMargin;
  37727. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  37728. this._currentFreePosition.x = 0;
  37729. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  37730. // No more room?
  37731. if (this._currentFreePosition.y > textureSize.height) {
  37732. return this.getChar("!");
  37733. }
  37734. }
  37735. // Draw the character in the texture
  37736. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  37737. // Fill the CharInfo object
  37738. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  37739. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  37740. info.charWidth = this._superSample ? (width / 2) : width;
  37741. // Add the info structure
  37742. this._charInfos[char] = info;
  37743. this._curCharCount++;
  37744. // Set the next position
  37745. this._currentFreePosition.x += width + xMargin;
  37746. return info;
  37747. };
  37748. FontTexture.prototype.measureText = function (text, tabulationSize) {
  37749. if (tabulationSize === void 0) { tabulationSize = 4; }
  37750. var maxWidth = 0;
  37751. var curWidth = 0;
  37752. var lineCount = 1;
  37753. var charxpos = 0;
  37754. // Parse each char of the string
  37755. for (var _i = 0; _i < text.length; _i++) {
  37756. var char = text[_i];
  37757. // Next line feed?
  37758. if (char === "\n") {
  37759. maxWidth = Math.max(maxWidth, curWidth);
  37760. charxpos = 0;
  37761. curWidth = 0;
  37762. ++lineCount;
  37763. continue;
  37764. }
  37765. // Tabulation ?
  37766. if (char === "\t") {
  37767. var nextPos = charxpos + tabulationSize;
  37768. nextPos = nextPos - (nextPos % tabulationSize);
  37769. curWidth += (nextPos - charxpos) * this.spaceWidth;
  37770. charxpos = nextPos;
  37771. continue;
  37772. }
  37773. if (char < " ") {
  37774. continue;
  37775. }
  37776. curWidth += this.getChar(char).charWidth;
  37777. ++charxpos;
  37778. }
  37779. maxWidth = Math.max(maxWidth, curWidth);
  37780. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  37781. };
  37782. FontTexture.prototype.getSuperSampleFont = function (font) {
  37783. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  37784. 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*$/;
  37785. var res = font.toLocaleLowerCase().match(regex);
  37786. if (res == null) {
  37787. return null;
  37788. }
  37789. var size = parseInt(res[4]);
  37790. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  37791. var newFont = "";
  37792. for (var j = 1; j < res.length; j++) {
  37793. if (res[j] != null) {
  37794. newFont += res[j] + " ";
  37795. }
  37796. }
  37797. return newFont;
  37798. };
  37799. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  37800. FontTexture.prototype.getFontHeight = function (font) {
  37801. var fontDraw = document.createElement("canvas");
  37802. var ctx = fontDraw.getContext('2d');
  37803. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  37804. ctx.textBaseline = 'top';
  37805. ctx.fillStyle = 'white';
  37806. ctx.font = font;
  37807. ctx.fillText('jH|', 0, 0);
  37808. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  37809. var start = -1;
  37810. var end = -1;
  37811. for (var row = 0; row < fontDraw.height; row++) {
  37812. for (var column = 0; column < fontDraw.width; column++) {
  37813. var index = (row * fontDraw.width + column) * 4;
  37814. if (pixels[index] === 0) {
  37815. if (column === fontDraw.width - 1 && start !== -1) {
  37816. end = row;
  37817. row = fontDraw.height;
  37818. break;
  37819. }
  37820. continue;
  37821. }
  37822. else {
  37823. if (start === -1) {
  37824. start = row;
  37825. }
  37826. break;
  37827. }
  37828. }
  37829. }
  37830. return { height: (end - start) + 1, offset: start - 1 };
  37831. };
  37832. Object.defineProperty(FontTexture.prototype, "canRescale", {
  37833. get: function () {
  37834. return false;
  37835. },
  37836. enumerable: true,
  37837. configurable: true
  37838. });
  37839. FontTexture.prototype.getContext = function () {
  37840. return this._context;
  37841. };
  37842. /**
  37843. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  37844. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  37845. */
  37846. FontTexture.prototype.update = function () {
  37847. // Update only if there's new char added since the previous update
  37848. if (this._lastUpdateCharCount < this._curCharCount) {
  37849. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  37850. this._lastUpdateCharCount = this._curCharCount;
  37851. }
  37852. };
  37853. // cloning should be prohibited, there's no point to duplicate this texture at all
  37854. FontTexture.prototype.clone = function () {
  37855. return null;
  37856. };
  37857. /**
  37858. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  37859. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  37860. */
  37861. FontTexture.prototype.incCachedFontTextureCounter = function () {
  37862. ++this._usedCounter;
  37863. };
  37864. /**
  37865. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  37866. */
  37867. FontTexture.prototype.decCachedFontTextureCounter = function () {
  37868. var s = this.getScene();
  37869. var dic = s.__fontTextureCache__;
  37870. if (!dic) {
  37871. return;
  37872. }
  37873. if (--this._usedCounter === 0) {
  37874. dic.remove(this._cachedFontId);
  37875. this.dispose();
  37876. }
  37877. };
  37878. return FontTexture;
  37879. })(BABYLON.Texture);
  37880. BABYLON.FontTexture = FontTexture;
  37881. })(BABYLON || (BABYLON = {}));
  37882. var BABYLON;
  37883. (function (BABYLON) {
  37884. var MapTexture = (function (_super) {
  37885. __extends(MapTexture, _super);
  37886. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  37887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37888. if (useMipMap === void 0) { useMipMap = false; }
  37889. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  37890. this.name = name;
  37891. this._size = size;
  37892. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37893. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37894. // Create the rectPackMap that will allocate portion of the texture
  37895. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  37896. // Create the texture that will store the content
  37897. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  37898. }
  37899. /**
  37900. * Allocate a rectangle of a given size in the texture map
  37901. * @param size the size of the rectangle to allocation
  37902. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  37903. */
  37904. MapTexture.prototype.allocateRect = function (size) {
  37905. return this._rectPackingMap.addRect(size);
  37906. };
  37907. /**
  37908. * Free a given rectangle from the texture map
  37909. * @param rectInfo the instance corresponding to the rect to free.
  37910. */
  37911. MapTexture.prototype.freeRect = function (rectInfo) {
  37912. if (rectInfo) {
  37913. rectInfo.freeContent();
  37914. }
  37915. };
  37916. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  37917. /**
  37918. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  37919. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  37920. * @returns {}
  37921. */
  37922. get: function () {
  37923. return this._rectPackingMap.freeSpace;
  37924. },
  37925. enumerable: true,
  37926. configurable: true
  37927. });
  37928. /**
  37929. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  37930. * 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.
  37931. * Don't forget to call unbindTexture when you're done rendering
  37932. * @param rect the zone to render to
  37933. * @param clear true to clear the portion's color/depth data
  37934. */
  37935. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  37936. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  37937. };
  37938. /**
  37939. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  37940. * 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.
  37941. * Don't forget to call unbindTexture when you're done rendering
  37942. * @param pos the position into the texture
  37943. * @param size the portion to fit the clip space to
  37944. * @param clear true to clear the portion's color/depth data
  37945. */
  37946. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  37947. var engine = this.getScene().getEngine();
  37948. engine.bindFramebuffer(this._texture);
  37949. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  37950. if (clear) {
  37951. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  37952. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  37953. }
  37954. };
  37955. /**
  37956. * Unbind the texture map from the rendering engine.
  37957. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  37958. * @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.
  37959. */
  37960. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  37961. // Dump ?
  37962. if (dumpForDebug) {
  37963. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  37964. }
  37965. var engine = this.getScene().getEngine();
  37966. if (this._replacedViewport) {
  37967. engine.setViewport(this._replacedViewport);
  37968. this._replacedViewport = null;
  37969. }
  37970. engine.unBindFramebuffer(this._texture);
  37971. };
  37972. Object.defineProperty(MapTexture.prototype, "canRescale", {
  37973. get: function () {
  37974. return false;
  37975. },
  37976. enumerable: true,
  37977. configurable: true
  37978. });
  37979. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  37980. // Anyway, there's not much point to use this method for this kind of texture I guess
  37981. MapTexture.prototype.clone = function () {
  37982. return null;
  37983. };
  37984. return MapTexture;
  37985. })(BABYLON.Texture);
  37986. BABYLON.MapTexture = MapTexture;
  37987. })(BABYLON || (BABYLON = {}));
  37988. var BABYLON;
  37989. (function (BABYLON) {
  37990. /**
  37991. * Stores 2D Bounding Information.
  37992. * This class handles a circle area and a bounding rectangle one.
  37993. */
  37994. var BoundingInfo2D = (function () {
  37995. function BoundingInfo2D() {
  37996. this.radius = 0;
  37997. this.center = BABYLON.Vector2.Zero();
  37998. this.extent = BABYLON.Vector2.Zero();
  37999. }
  38000. /**
  38001. * Create a BoundingInfo2D object from a given size
  38002. * @param size the size that will be used to set the extend, radius will be computed from it.
  38003. */
  38004. BoundingInfo2D.CreateFromSize = function (size) {
  38005. var r = new BoundingInfo2D();
  38006. BoundingInfo2D.CreateFromSizeToRef(size, r);
  38007. return r;
  38008. };
  38009. /**
  38010. * Create a BoundingInfo2D object from a given radius
  38011. * @param radius the radius to use, the extent will be computed from it.
  38012. */
  38013. BoundingInfo2D.CreateFromRadius = function (radius) {
  38014. var r = new BoundingInfo2D();
  38015. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  38016. return r;
  38017. };
  38018. /**
  38019. * Create a BoundingInfo2D object from a list of points.
  38020. * The resulted object will be the smallest bounding area that includes all the given points.
  38021. * @param points an array of points to compute the bounding object from.
  38022. */
  38023. BoundingInfo2D.CreateFromPoints = function (points) {
  38024. var r = new BoundingInfo2D();
  38025. BoundingInfo2D.CreateFromPointsToRef(points, r);
  38026. return r;
  38027. };
  38028. /**
  38029. * Update a BoundingInfo2D object using the given Size as input
  38030. * @param size the bounding data will be computed from this size.
  38031. * @param b must be a valid/allocated object, it will contain the result of the operation
  38032. */
  38033. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  38034. if (!size) {
  38035. size = BABYLON.Size.Zero();
  38036. }
  38037. b.center.x = +size.width / 2;
  38038. b.center.y = +size.height / 2;
  38039. b.extent.x = b.center.x;
  38040. b.extent.y = b.center.y;
  38041. b.radius = b.extent.length();
  38042. };
  38043. /**
  38044. * Update a BoundingInfo2D object using the given radius as input
  38045. * @param radius the bounding data will be computed from this radius
  38046. * @param b must be a valid/allocated object, it will contain the result of the operation
  38047. */
  38048. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  38049. b.center.x = b.center.y = 0;
  38050. var r = +radius;
  38051. b.extent.x = r;
  38052. b.extent.y = r;
  38053. b.radius = r;
  38054. };
  38055. /**
  38056. * Update a BoundingInfo2D object using the given points array as input
  38057. * @param points the point array to use to update the bounding data
  38058. * @param b must be a valid/allocated object, it will contain the result of the operation
  38059. */
  38060. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  38061. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  38062. for (var _i = 0; _i < points.length; _i++) {
  38063. var p = points[_i];
  38064. xmin = Math.min(p.x, xmin);
  38065. xmax = Math.max(p.x, xmax);
  38066. ymin = Math.min(p.y, ymin);
  38067. ymax = Math.max(p.y, ymax);
  38068. }
  38069. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  38070. };
  38071. /**
  38072. * Update a BoundingInfo2D object using the given min/max values as input
  38073. * @param xmin the smallest x coordinate
  38074. * @param xmax the biggest x coordinate
  38075. * @param ymin the smallest y coordinate
  38076. * @param ymax the buggest y coordinate
  38077. * @param b must be a valid/allocated object, it will contain the result of the operation
  38078. */
  38079. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  38080. var w = xmax - xmin;
  38081. var h = ymax - ymin;
  38082. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  38083. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  38084. b.radius = b.extent.length();
  38085. };
  38086. /**
  38087. * Duplicate this instance and return a new one
  38088. * @return the duplicated instance
  38089. */
  38090. BoundingInfo2D.prototype.clone = function () {
  38091. var r = new BoundingInfo2D();
  38092. r.center = this.center.clone();
  38093. r.radius = this.radius;
  38094. r.extent = this.extent.clone();
  38095. return r;
  38096. };
  38097. BoundingInfo2D.prototype.clear = function () {
  38098. this.center.copyFromFloats(0, 0);
  38099. this.radius = 0;
  38100. this.extent.copyFromFloats(0, 0);
  38101. };
  38102. BoundingInfo2D.prototype.copyFrom = function (src) {
  38103. this.center.copyFrom(src.center);
  38104. this.radius = src.radius;
  38105. this.extent.copyFrom(src.extent);
  38106. };
  38107. /**
  38108. * return the max extend of the bounding info
  38109. */
  38110. BoundingInfo2D.prototype.max = function () {
  38111. var r = BABYLON.Vector2.Zero();
  38112. this.maxToRef(r);
  38113. return r;
  38114. };
  38115. /**
  38116. * Update a vector2 with the max extend of the bounding info
  38117. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  38118. */
  38119. BoundingInfo2D.prototype.maxToRef = function (result) {
  38120. result.x = this.center.x + this.extent.x;
  38121. result.y = this.center.y + this.extent.y;
  38122. };
  38123. /**
  38124. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  38125. * @param matrix the transformation matrix to apply
  38126. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  38127. */
  38128. BoundingInfo2D.prototype.transform = function (matrix) {
  38129. var r = new BoundingInfo2D();
  38130. this.transformToRef(matrix, r);
  38131. return r;
  38132. };
  38133. /**
  38134. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  38135. * @param other the second BoundingInfo2D to compute the union with this one
  38136. * @return a new instance containing the result of the union
  38137. */
  38138. BoundingInfo2D.prototype.union = function (other) {
  38139. var r = new BoundingInfo2D();
  38140. this.unionToRef(other, r);
  38141. return r;
  38142. };
  38143. /**
  38144. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  38145. * 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.
  38146. * @param matrix The matrix to use to compute the transformation
  38147. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  38148. */
  38149. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  38150. // Construct a bounding box based on the extent values
  38151. var p = BoundingInfo2D._transform;
  38152. p[0].x = this.center.x + this.extent.x;
  38153. p[0].y = this.center.y + this.extent.y;
  38154. p[1].x = this.center.x + this.extent.x;
  38155. p[1].y = this.center.y - this.extent.y;
  38156. p[2].x = this.center.x - this.extent.x;
  38157. p[2].y = this.center.y - this.extent.y;
  38158. p[3].x = this.center.x - this.extent.x;
  38159. p[3].y = this.center.y + this.extent.y;
  38160. // Transform the four points of the bounding box with the matrix
  38161. for (var i = 0; i < 4; i++) {
  38162. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  38163. }
  38164. BoundingInfo2D.CreateFromPointsToRef(p, result);
  38165. };
  38166. /**
  38167. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  38168. * 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.
  38169. * @param other the second object used to compute the union
  38170. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  38171. */
  38172. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  38173. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  38174. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  38175. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  38176. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  38177. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  38178. };
  38179. /**
  38180. * Check if the given point is inside the BoundingInfo.
  38181. * The test is first made on the radius, then inside the rectangle described by the extent
  38182. * @param pickPosition the position to test
  38183. * @return true if the point is inside, false otherwise
  38184. */
  38185. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  38186. // is it inside the radius?
  38187. var pickLocal = pickPosition.subtract(this.center);
  38188. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  38189. // is it inside the rectangle?
  38190. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  38191. }
  38192. return false;
  38193. };
  38194. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  38195. return BoundingInfo2D;
  38196. })();
  38197. BABYLON.BoundingInfo2D = BoundingInfo2D;
  38198. })(BABYLON || (BABYLON = {}));
  38199. var BABYLON;
  38200. (function (BABYLON) {
  38201. /**
  38202. * Base class implementing the ILocable interface.
  38203. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  38204. */
  38205. var LockableBase = (function () {
  38206. function LockableBase() {
  38207. }
  38208. LockableBase.prototype.isLocked = function () {
  38209. return this._isLocked;
  38210. };
  38211. LockableBase.prototype.lock = function () {
  38212. if (this._isLocked) {
  38213. return true;
  38214. }
  38215. this.onLock();
  38216. this._isLocked = true;
  38217. return false;
  38218. };
  38219. /**
  38220. * Protected handler that will be called when the instance is about to be locked.
  38221. */
  38222. LockableBase.prototype.onLock = function () {
  38223. };
  38224. return LockableBase;
  38225. })();
  38226. BABYLON.LockableBase = LockableBase;
  38227. var SolidColorBrush2D = (function (_super) {
  38228. __extends(SolidColorBrush2D, _super);
  38229. function SolidColorBrush2D(color, lock) {
  38230. if (lock === void 0) { lock = false; }
  38231. _super.call(this);
  38232. this._color = color;
  38233. if (lock) {
  38234. {
  38235. this.lock();
  38236. }
  38237. }
  38238. }
  38239. /**
  38240. * Return true if the brush is transparent, false if it's totally opaque
  38241. */
  38242. SolidColorBrush2D.prototype.isTransparent = function () {
  38243. return this._color && this._color.a < 1.0;
  38244. };
  38245. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  38246. /**
  38247. * The color used by this instance to render
  38248. * @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.
  38249. */
  38250. get: function () {
  38251. return this._color;
  38252. },
  38253. set: function (value) {
  38254. if (this.isLocked()) {
  38255. return;
  38256. }
  38257. this._color = value;
  38258. },
  38259. enumerable: true,
  38260. configurable: true
  38261. });
  38262. /**
  38263. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  38264. */
  38265. SolidColorBrush2D.prototype.toString = function () {
  38266. return this._color.toHexString();
  38267. };
  38268. SolidColorBrush2D = __decorate([
  38269. BABYLON.className("SolidColorBrush2D")
  38270. ], SolidColorBrush2D);
  38271. return SolidColorBrush2D;
  38272. })(LockableBase);
  38273. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  38274. var GradientColorBrush2D = (function (_super) {
  38275. __extends(GradientColorBrush2D, _super);
  38276. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  38277. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  38278. if (rotation === void 0) { rotation = 0; }
  38279. if (scale === void 0) { scale = 1; }
  38280. if (lock === void 0) { lock = false; }
  38281. _super.call(this);
  38282. this._color1 = color1;
  38283. this._color2 = color2;
  38284. this._translation = translation;
  38285. this._rotation = rotation;
  38286. this._scale = scale;
  38287. if (lock) {
  38288. this.lock();
  38289. }
  38290. }
  38291. /**
  38292. * Return true if the brush is transparent, false if it's totally opaque
  38293. */
  38294. GradientColorBrush2D.prototype.isTransparent = function () {
  38295. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  38296. };
  38297. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  38298. /**
  38299. * First color, the blend will start from this color
  38300. */
  38301. get: function () {
  38302. return this._color1;
  38303. },
  38304. set: function (value) {
  38305. if (this.isLocked()) {
  38306. return;
  38307. }
  38308. this._color1 = value;
  38309. },
  38310. enumerable: true,
  38311. configurable: true
  38312. });
  38313. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  38314. /**
  38315. * Second color, the blend will end to this color
  38316. */
  38317. get: function () {
  38318. return this._color2;
  38319. },
  38320. set: function (value) {
  38321. if (this.isLocked()) {
  38322. return;
  38323. }
  38324. this._color2 = value;
  38325. },
  38326. enumerable: true,
  38327. configurable: true
  38328. });
  38329. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  38330. /**
  38331. * Translation vector to apply on the blend
  38332. * Default is [0;0]
  38333. */
  38334. get: function () {
  38335. return this._translation;
  38336. },
  38337. set: function (value) {
  38338. if (this.isLocked()) {
  38339. return;
  38340. }
  38341. this._translation = value;
  38342. },
  38343. enumerable: true,
  38344. configurable: true
  38345. });
  38346. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  38347. /**
  38348. * Rotation in radian to apply to the brush
  38349. * Default direction of the brush is vertical, you can change this using this property.
  38350. * Default is 0.
  38351. */
  38352. get: function () {
  38353. return this._rotation;
  38354. },
  38355. set: function (value) {
  38356. if (this.isLocked()) {
  38357. return;
  38358. }
  38359. this._rotation = value;
  38360. },
  38361. enumerable: true,
  38362. configurable: true
  38363. });
  38364. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  38365. /**
  38366. * Scale factor to apply to the gradient.
  38367. * Default is 1: no scale.
  38368. */
  38369. get: function () {
  38370. return this._scale;
  38371. },
  38372. set: function (value) {
  38373. if (this.isLocked()) {
  38374. return;
  38375. }
  38376. this._scale = value;
  38377. },
  38378. enumerable: true,
  38379. configurable: true
  38380. });
  38381. /**
  38382. * Return a string describing the brush
  38383. */
  38384. GradientColorBrush2D.prototype.toString = function () {
  38385. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  38386. };
  38387. /**
  38388. * Build a unique key string for the given parameters
  38389. */
  38390. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  38391. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  38392. };
  38393. GradientColorBrush2D = __decorate([
  38394. BABYLON.className("GradientColorBrush2D")
  38395. ], GradientColorBrush2D);
  38396. return GradientColorBrush2D;
  38397. })(LockableBase);
  38398. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  38399. })(BABYLON || (BABYLON = {}));
  38400. var BABYLON;
  38401. (function (BABYLON) {
  38402. var Prim2DClassInfo = (function () {
  38403. function Prim2DClassInfo() {
  38404. }
  38405. return Prim2DClassInfo;
  38406. })();
  38407. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  38408. var Prim2DPropInfo = (function () {
  38409. function Prim2DPropInfo() {
  38410. }
  38411. Prim2DPropInfo.PROPKIND_MODEL = 1;
  38412. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  38413. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  38414. return Prim2DPropInfo;
  38415. })();
  38416. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  38417. /**
  38418. * Custom type of the propertyChanged observable
  38419. */
  38420. var PropertyChangedInfo = (function () {
  38421. function PropertyChangedInfo() {
  38422. }
  38423. return PropertyChangedInfo;
  38424. })();
  38425. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  38426. var ClassTreeInfo = (function () {
  38427. function ClassTreeInfo(baseClass, type, classContentFactory) {
  38428. this._baseClass = baseClass;
  38429. this._type = type;
  38430. this._subClasses = new Array();
  38431. this._levelContent = new BABYLON.StringDictionary();
  38432. this._classContentFactory = classContentFactory;
  38433. }
  38434. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  38435. get: function () {
  38436. if (!this._classContent) {
  38437. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  38438. }
  38439. return this._classContent;
  38440. },
  38441. enumerable: true,
  38442. configurable: true
  38443. });
  38444. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  38445. get: function () {
  38446. return this._type;
  38447. },
  38448. enumerable: true,
  38449. configurable: true
  38450. });
  38451. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  38452. get: function () {
  38453. return this._levelContent;
  38454. },
  38455. enumerable: true,
  38456. configurable: true
  38457. });
  38458. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  38459. get: function () {
  38460. if (!this._fullContent) {
  38461. var dic = new BABYLON.StringDictionary();
  38462. var curLevel = this;
  38463. while (curLevel) {
  38464. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  38465. curLevel = curLevel._baseClass;
  38466. }
  38467. this._fullContent = dic;
  38468. }
  38469. return this._fullContent;
  38470. },
  38471. enumerable: true,
  38472. configurable: true
  38473. });
  38474. ClassTreeInfo.prototype.getLevelOf = function (type) {
  38475. // Are we already there?
  38476. if (type === this._type) {
  38477. return this;
  38478. }
  38479. var baseProto = Object.getPrototypeOf(type);
  38480. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  38481. if (!curProtoContent) {
  38482. this.getLevelOf(baseProto);
  38483. }
  38484. return this.getOrAddType(baseProto, type);
  38485. };
  38486. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  38487. // Are we at the level corresponding to the baseType?
  38488. // If so, get or add the level we're looking for
  38489. if (baseType === this._type) {
  38490. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  38491. var subType = _a[_i];
  38492. if (subType.type === type) {
  38493. return subType.node;
  38494. }
  38495. }
  38496. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  38497. var info = { type: type, node: node };
  38498. this._subClasses.push(info);
  38499. return info.node;
  38500. }
  38501. // Recurse down to keep looking for the node corresponding to the baseTypeName
  38502. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  38503. var subType = _c[_b];
  38504. var info = subType.node.getOrAddType(baseType, type);
  38505. if (info) {
  38506. return info;
  38507. }
  38508. }
  38509. return null;
  38510. };
  38511. ClassTreeInfo.get = function (type) {
  38512. var dic = type["__classTreeInfo"];
  38513. if (!dic) {
  38514. return null;
  38515. }
  38516. return dic.getLevelOf(type);
  38517. };
  38518. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  38519. var dic = type["__classTreeInfo"];
  38520. if (!dic) {
  38521. dic = new ClassTreeInfo(null, type, classContentFactory);
  38522. type["__classTreeInfo"] = dic;
  38523. }
  38524. return dic;
  38525. };
  38526. return ClassTreeInfo;
  38527. })();
  38528. BABYLON.ClassTreeInfo = ClassTreeInfo;
  38529. var SmartPropertyPrim = (function () {
  38530. function SmartPropertyPrim() {
  38531. this._flags = 0;
  38532. this._modelKey = null;
  38533. this._instanceDirtyFlags = 0;
  38534. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  38535. this.animations = new Array();
  38536. }
  38537. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  38538. /**
  38539. * Check if the object is disposed or not.
  38540. * @returns true if the object is dispose, false otherwise.
  38541. */
  38542. get: function () {
  38543. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  38544. },
  38545. enumerable: true,
  38546. configurable: true
  38547. });
  38548. /**
  38549. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  38550. * @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.
  38551. */
  38552. SmartPropertyPrim.prototype.dispose = function () {
  38553. if (this.isDisposed) {
  38554. return false;
  38555. }
  38556. // Don't set to null, it may upset somebody...
  38557. this.animations.splice(0);
  38558. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  38559. return true;
  38560. };
  38561. /**
  38562. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  38563. * Look at Sprite2D for more information
  38564. */
  38565. SmartPropertyPrim.prototype.getAnimatables = function () {
  38566. return new Array();
  38567. };
  38568. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  38569. /**
  38570. * Property giving the Model Key associated to the property.
  38571. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  38572. * @returns the model key string.
  38573. */
  38574. get: function () {
  38575. var _this = this;
  38576. // No need to compute it?
  38577. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  38578. return this._modelKey;
  38579. }
  38580. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  38581. var propDic = this.propDic;
  38582. propDic.forEach(function (k, v) {
  38583. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  38584. var propVal = _this[v.name];
  38585. // 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
  38586. if (propVal && propVal.constructor === Array) {
  38587. var firstVal = propVal[0];
  38588. if (!firstVal) {
  38589. propVal = 0;
  38590. }
  38591. else {
  38592. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  38593. }
  38594. }
  38595. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  38596. }
  38597. });
  38598. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  38599. this._modelKey = modelKey;
  38600. return modelKey;
  38601. },
  38602. enumerable: true,
  38603. configurable: true
  38604. });
  38605. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  38606. /**
  38607. * States if the Primitive is dirty and should be rendered again next time.
  38608. * @returns true is dirty, false otherwise
  38609. */
  38610. get: function () {
  38611. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  38612. },
  38613. enumerable: true,
  38614. configurable: true
  38615. });
  38616. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  38617. /**
  38618. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  38619. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  38620. */
  38621. get: function () {
  38622. if (!this._propInfo) {
  38623. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  38624. if (!cti) {
  38625. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  38626. }
  38627. this._propInfo = cti.fullContent;
  38628. }
  38629. return this._propInfo;
  38630. },
  38631. enumerable: true,
  38632. configurable: true
  38633. });
  38634. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  38635. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  38636. var node = dic.getLevelOf(target);
  38637. var propInfo = node.levelContent.get(propId.toString());
  38638. if (propInfo) {
  38639. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  38640. }
  38641. // Create, setup and add the PropInfo object to our prop dictionary
  38642. propInfo = new Prim2DPropInfo();
  38643. propInfo.id = propId;
  38644. propInfo.flagId = Math.pow(2, propId);
  38645. propInfo.kind = kind;
  38646. propInfo.name = propName;
  38647. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  38648. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  38649. propInfo.typeLevelCompare = typeLevelCompare;
  38650. node.levelContent.add(propName, propInfo);
  38651. return propInfo;
  38652. };
  38653. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  38654. // Nothing to nothing: nothing to do!
  38655. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  38656. return true;
  38657. }
  38658. // Check value unchanged
  38659. if ((curValue != null) && (newValue != null)) {
  38660. if (typeof (curValue.equals) == "function") {
  38661. if (curValue.equals(newValue)) {
  38662. return true;
  38663. }
  38664. }
  38665. else {
  38666. if (curValue === newValue) {
  38667. return true;
  38668. }
  38669. }
  38670. }
  38671. return false;
  38672. };
  38673. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  38674. if (this.isDisposed) {
  38675. return;
  38676. }
  38677. var i = propertyName.indexOf(".");
  38678. if (i !== -1) {
  38679. propertyName = propertyName.substr(0, i);
  38680. }
  38681. var propInfo = this.propDic.get(propertyName);
  38682. if (!propInfo) {
  38683. return;
  38684. }
  38685. var newValue = this[propertyName];
  38686. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  38687. };
  38688. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  38689. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  38690. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  38691. if (this instanceof BABYLON.Prim2DBase) {
  38692. var curprim = this;
  38693. while (curprim) {
  38694. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  38695. if (curprim.isSizeAuto) {
  38696. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  38697. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  38698. }
  38699. if (curprim instanceof BABYLON.Group2D) {
  38700. if (curprim.isRenderableGroup) {
  38701. break;
  38702. }
  38703. }
  38704. curprim = curprim.parent;
  38705. }
  38706. }
  38707. };
  38708. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  38709. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  38710. if (propInfo.dirtyBoundingInfo) {
  38711. this._boundingBoxDirty();
  38712. }
  38713. else if (propInfo.dirtyParentBoundingInfo) {
  38714. var p = this._parent;
  38715. if (p != null) {
  38716. p._boundingBoxDirty();
  38717. }
  38718. }
  38719. // Trigger property changed
  38720. var info = SmartPropertyPrim.propChangedInfo;
  38721. info.oldValue = curValue;
  38722. info.newValue = newValue;
  38723. info.propertyName = propName;
  38724. var propMask = propInfo.flagId;
  38725. this.propertyChanged.notifyObservers(info, propMask);
  38726. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  38727. if (this instanceof BABYLON.Group2D) {
  38728. this.handleGroupChanged(propInfo);
  38729. }
  38730. // Check for parent layout dirty
  38731. if (this instanceof BABYLON.Prim2DBase) {
  38732. var p = this._parent;
  38733. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  38734. p._setLayoutDirty();
  38735. }
  38736. }
  38737. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  38738. var instanceDirty = false;
  38739. if (typeLevelCompare && curValue != null && newValue != null) {
  38740. var cvProto = curValue.__proto__;
  38741. var nvProto = newValue.__proto__;
  38742. instanceDirty = (cvProto === nvProto);
  38743. }
  38744. // Set the dirty flags
  38745. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  38746. if (!this.isDirty) {
  38747. this._setFlags(SmartPropertyPrim.flagModelDirty);
  38748. }
  38749. }
  38750. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  38751. this.onPrimitivePropertyDirty(propMask);
  38752. }
  38753. };
  38754. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  38755. this.onPrimBecomesDirty();
  38756. this._instanceDirtyFlags |= propFlagId;
  38757. };
  38758. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  38759. };
  38760. /**
  38761. * Check if a given set of properties are dirty or not.
  38762. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  38763. * @return true if at least one property is dirty, false if none of them are.
  38764. */
  38765. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  38766. return (this._instanceDirtyFlags & flags) !== 0;
  38767. };
  38768. /**
  38769. * Clear a given set of properties.
  38770. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  38771. * @return the new set of property still marked as dirty
  38772. */
  38773. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  38774. this._instanceDirtyFlags &= ~flags;
  38775. return this._instanceDirtyFlags;
  38776. };
  38777. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  38778. this._instanceDirtyFlags = 0;
  38779. this._clearFlags(SmartPropertyPrim.flagPrimInDirtyList | SmartPropertyPrim.flagNeedRefresh);
  38780. };
  38781. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  38782. /**
  38783. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  38784. */
  38785. get: function () {
  38786. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  38787. this.updateLevelBoundingInfo();
  38788. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  38789. }
  38790. return this._levelBoundingInfo;
  38791. },
  38792. enumerable: true,
  38793. configurable: true
  38794. });
  38795. /**
  38796. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  38797. */
  38798. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  38799. };
  38800. /**
  38801. * Property method called when the Primitive becomes dirty
  38802. */
  38803. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  38804. };
  38805. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  38806. return function (target, propName, descriptor) {
  38807. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  38808. if (piStore) {
  38809. piStore(propInfo);
  38810. }
  38811. var getter = descriptor.get, setter = descriptor.set;
  38812. // Overload the property setter implementation to add our own logic
  38813. descriptor.set = function (val) {
  38814. // check for disposed first, do nothing
  38815. if (this.isDisposed) {
  38816. return;
  38817. }
  38818. var curVal = getter.call(this);
  38819. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  38820. return;
  38821. }
  38822. // Cast the object we're working one
  38823. var prim = this;
  38824. // Change the value
  38825. setter.call(this, val);
  38826. // Notify change, dirty flags update
  38827. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  38828. };
  38829. };
  38830. };
  38831. /**
  38832. * Add an externally attached data from its key.
  38833. * This method call will fail and return false, if such key already exists.
  38834. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  38835. * @param key the unique key that identifies the data
  38836. * @param data the data object to associate to the key for this Engine instance
  38837. * @return true if no such key were already present and the data was added successfully, false otherwise
  38838. */
  38839. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  38840. if (!this._externalData) {
  38841. this._externalData = new BABYLON.StringDictionary();
  38842. }
  38843. return this._externalData.add(key, data);
  38844. };
  38845. /**
  38846. * Get an externally attached data from its key
  38847. * @param key the unique key that identifies the data
  38848. * @return the associated data, if present (can be null), or undefined if not present
  38849. */
  38850. SmartPropertyPrim.prototype.getExternalData = function (key) {
  38851. if (!this._externalData) {
  38852. return null;
  38853. }
  38854. return this._externalData.get(key);
  38855. };
  38856. /**
  38857. * Get an externally attached data from its key, create it using a factory if it's not already present
  38858. * @param key the unique key that identifies the data
  38859. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  38860. * @return the associated data, can be null if the factory returned null.
  38861. */
  38862. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  38863. if (!this._externalData) {
  38864. this._externalData = new BABYLON.StringDictionary();
  38865. }
  38866. return this._externalData.getOrAddWithFactory(key, factory);
  38867. };
  38868. /**
  38869. * Remove an externally attached data from the Engine instance
  38870. * @param key the unique key that identifies the data
  38871. * @return true if the data was successfully removed, false if it doesn't exist
  38872. */
  38873. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  38874. if (!this._externalData) {
  38875. return false;
  38876. }
  38877. return this._externalData.remove(key);
  38878. };
  38879. /**
  38880. * Check if a given flag is set
  38881. * @param flag the flag value
  38882. * @return true if set, false otherwise
  38883. */
  38884. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  38885. return (this._flags & flag) !== 0;
  38886. };
  38887. /**
  38888. * Check if all given flags are set
  38889. * @param flags the flags ORed
  38890. * @return true if all the flags are set, false otherwise
  38891. */
  38892. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  38893. return (this._flags & flags) === flags;
  38894. };
  38895. /**
  38896. * Check if at least one flag of the given flags is set
  38897. * @param flags the flags ORed
  38898. * @return true if at least one flag is set, false otherwise
  38899. */
  38900. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  38901. return (this._flags & flags) !== 0;
  38902. };
  38903. /**
  38904. * Clear the given flags
  38905. * @param flags the flags to clear
  38906. */
  38907. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  38908. this._flags &= ~flags;
  38909. };
  38910. /**
  38911. * Set the given flags to true state
  38912. * @param flags the flags ORed to set
  38913. * @return the flags state before this call
  38914. */
  38915. SmartPropertyPrim.prototype._setFlags = function (flags) {
  38916. var cur = this._flags;
  38917. this._flags |= flags;
  38918. return cur;
  38919. };
  38920. /**
  38921. * Change the state of the given flags
  38922. * @param flags the flags ORed to change
  38923. * @param state true to set them, false to clear them
  38924. */
  38925. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  38926. if (state) {
  38927. this._flags |= flags;
  38928. }
  38929. else {
  38930. this._flags &= ~flags;
  38931. }
  38932. };
  38933. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  38934. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  38935. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  38936. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  38937. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  38938. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  38939. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  38940. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  38941. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  38942. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  38943. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  38944. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  38945. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  38946. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  38947. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  38948. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  38949. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  38950. SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
  38951. SmartPropertyPrim.flagNeedRefresh = 0x0020000; // set if the primitive wasn't successful at refresh
  38952. SmartPropertyPrim = __decorate([
  38953. BABYLON.className("SmartPropertyPrim")
  38954. ], SmartPropertyPrim);
  38955. return SmartPropertyPrim;
  38956. })();
  38957. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  38958. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38959. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38960. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38961. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38962. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  38963. }
  38964. BABYLON.modelLevelProperty = modelLevelProperty;
  38965. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38966. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38967. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38968. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38969. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  38970. }
  38971. BABYLON.instanceLevelProperty = instanceLevelProperty;
  38972. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38973. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38974. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38975. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38976. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  38977. }
  38978. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  38979. })(BABYLON || (BABYLON = {}));
  38980. var BABYLON;
  38981. (function (BABYLON) {
  38982. var PrepareRender2DContext = (function () {
  38983. function PrepareRender2DContext() {
  38984. this.forceRefreshPrimitive = false;
  38985. }
  38986. return PrepareRender2DContext;
  38987. })();
  38988. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  38989. var Render2DContext = (function () {
  38990. function Render2DContext(renderMode) {
  38991. this._renderMode = renderMode;
  38992. this.useInstancing = false;
  38993. this.groupInfoPartData = null;
  38994. this.partDataStartIndex = this.partDataEndIndex = null;
  38995. this.instancedBuffers = null;
  38996. }
  38997. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  38998. /**
  38999. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  39000. */
  39001. get: function () {
  39002. return this._renderMode;
  39003. },
  39004. enumerable: true,
  39005. configurable: true
  39006. });
  39007. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  39008. /**
  39009. * The set of primitives to render is opaque.
  39010. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  39011. */
  39012. get: function () {
  39013. return Render2DContext._renderModeOpaque;
  39014. },
  39015. enumerable: true,
  39016. configurable: true
  39017. });
  39018. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  39019. /**
  39020. * The set of primitives to render is using Alpha Test (aka masking).
  39021. * 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.
  39022. */
  39023. get: function () {
  39024. return Render2DContext._renderModeAlphaTest;
  39025. },
  39026. enumerable: true,
  39027. configurable: true
  39028. });
  39029. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  39030. /**
  39031. * The set of primitives to render is transparent.
  39032. * 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.
  39033. */
  39034. get: function () {
  39035. return Render2DContext._renderModeTransparent;
  39036. },
  39037. enumerable: true,
  39038. configurable: true
  39039. });
  39040. Render2DContext._renderModeOpaque = 1;
  39041. Render2DContext._renderModeAlphaTest = 2;
  39042. Render2DContext._renderModeTransparent = 3;
  39043. return Render2DContext;
  39044. })();
  39045. BABYLON.Render2DContext = Render2DContext;
  39046. /**
  39047. * This class store information for the pointerEventObservable Observable.
  39048. * 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.
  39049. */
  39050. var PrimitivePointerInfo = (function () {
  39051. function PrimitivePointerInfo() {
  39052. this.primitivePointerPos = BABYLON.Vector2.Zero();
  39053. this.tilt = BABYLON.Vector2.Zero();
  39054. this.cancelBubble = false;
  39055. }
  39056. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  39057. // 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.
  39058. /**
  39059. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  39060. * Bubbles: yes
  39061. */
  39062. get: function () {
  39063. return PrimitivePointerInfo._pointerOver;
  39064. },
  39065. enumerable: true,
  39066. configurable: true
  39067. });
  39068. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  39069. /**
  39070. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  39071. * Bubbles: no
  39072. */
  39073. get: function () {
  39074. return PrimitivePointerInfo._pointerEnter;
  39075. },
  39076. enumerable: true,
  39077. configurable: true
  39078. });
  39079. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  39080. /**
  39081. * 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.
  39082. * Bubbles: yes
  39083. */
  39084. get: function () {
  39085. return PrimitivePointerInfo._pointerDown;
  39086. },
  39087. enumerable: true,
  39088. configurable: true
  39089. });
  39090. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  39091. /**
  39092. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  39093. * Bubbles: yes
  39094. */
  39095. get: function () {
  39096. return PrimitivePointerInfo._pointerMouseWheel;
  39097. },
  39098. enumerable: true,
  39099. configurable: true
  39100. });
  39101. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  39102. /**
  39103. * 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.
  39104. * Bubbles: yes
  39105. */
  39106. get: function () {
  39107. return PrimitivePointerInfo._pointerMove;
  39108. },
  39109. enumerable: true,
  39110. configurable: true
  39111. });
  39112. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  39113. /**
  39114. * 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.
  39115. * Bubbles: yes
  39116. */
  39117. get: function () {
  39118. return PrimitivePointerInfo._pointerUp;
  39119. },
  39120. enumerable: true,
  39121. configurable: true
  39122. });
  39123. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  39124. /**
  39125. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  39126. * Bubbles: yes
  39127. */
  39128. get: function () {
  39129. return PrimitivePointerInfo._pointerOut;
  39130. },
  39131. enumerable: true,
  39132. configurable: true
  39133. });
  39134. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  39135. /**
  39136. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  39137. * Bubbles: no
  39138. */
  39139. get: function () {
  39140. return PrimitivePointerInfo._pointerLeave;
  39141. },
  39142. enumerable: true,
  39143. configurable: true
  39144. });
  39145. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  39146. /**
  39147. * 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.
  39148. * Bubbles: yes
  39149. */
  39150. get: function () {
  39151. return PrimitivePointerInfo._pointerGotCapture;
  39152. },
  39153. enumerable: true,
  39154. configurable: true
  39155. });
  39156. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  39157. /**
  39158. * This event type is raised after pointer capture is released for a pointer.
  39159. * Bubbles: yes
  39160. */
  39161. get: function () {
  39162. return PrimitivePointerInfo._pointerLostCapture;
  39163. },
  39164. enumerable: true,
  39165. configurable: true
  39166. });
  39167. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  39168. get: function () {
  39169. return PrimitivePointerInfo._mouseWheelPrecision;
  39170. },
  39171. enumerable: true,
  39172. configurable: true
  39173. });
  39174. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  39175. this.relatedTarget = prim;
  39176. this.relatedTargetPointerPos = primPointerPos;
  39177. };
  39178. PrimitivePointerInfo.getEventTypeName = function (mask) {
  39179. switch (mask) {
  39180. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  39181. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  39182. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  39183. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  39184. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  39185. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  39186. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  39187. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  39188. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  39189. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  39190. }
  39191. };
  39192. PrimitivePointerInfo._pointerOver = 0x0001;
  39193. PrimitivePointerInfo._pointerEnter = 0x0002;
  39194. PrimitivePointerInfo._pointerDown = 0x0004;
  39195. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  39196. PrimitivePointerInfo._pointerMove = 0x0010;
  39197. PrimitivePointerInfo._pointerUp = 0x0020;
  39198. PrimitivePointerInfo._pointerOut = 0x0040;
  39199. PrimitivePointerInfo._pointerLeave = 0x0080;
  39200. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  39201. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  39202. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  39203. return PrimitivePointerInfo;
  39204. })();
  39205. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  39206. /**
  39207. * Defines the horizontal and vertical alignment information for a Primitive.
  39208. */
  39209. var PrimitiveAlignment = (function () {
  39210. function PrimitiveAlignment(changeCallback) {
  39211. this._changedCallback = changeCallback;
  39212. this._horizontal = PrimitiveAlignment.AlignLeft;
  39213. this._vertical = PrimitiveAlignment.AlignBottom;
  39214. }
  39215. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  39216. /**
  39217. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  39218. */
  39219. get: function () { return PrimitiveAlignment._AlignLeft; },
  39220. enumerable: true,
  39221. configurable: true
  39222. });
  39223. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  39224. /**
  39225. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  39226. */
  39227. get: function () { return PrimitiveAlignment._AlignTop; },
  39228. enumerable: true,
  39229. configurable: true
  39230. });
  39231. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  39232. /**
  39233. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  39234. */
  39235. get: function () { return PrimitiveAlignment._AlignRight; },
  39236. enumerable: true,
  39237. configurable: true
  39238. });
  39239. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  39240. /**
  39241. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  39242. */
  39243. get: function () { return PrimitiveAlignment._AlignBottom; },
  39244. enumerable: true,
  39245. configurable: true
  39246. });
  39247. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  39248. /**
  39249. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  39250. */
  39251. get: function () { return PrimitiveAlignment._AlignCenter; },
  39252. enumerable: true,
  39253. configurable: true
  39254. });
  39255. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  39256. /**
  39257. * The content is stretched toward the opposite edges of the Primitive
  39258. */
  39259. get: function () { return PrimitiveAlignment._AlignStretch; },
  39260. enumerable: true,
  39261. configurable: true
  39262. });
  39263. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  39264. /**
  39265. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  39266. */
  39267. get: function () {
  39268. return this._horizontal;
  39269. },
  39270. set: function (value) {
  39271. if (this._horizontal === value) {
  39272. return;
  39273. }
  39274. this._horizontal = value;
  39275. this._changedCallback();
  39276. },
  39277. enumerable: true,
  39278. configurable: true
  39279. });
  39280. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  39281. /**
  39282. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  39283. */
  39284. get: function () {
  39285. return this._vertical;
  39286. },
  39287. set: function (value) {
  39288. if (this._vertical === value) {
  39289. return;
  39290. }
  39291. this._vertical = value;
  39292. this._changedCallback();
  39293. },
  39294. enumerable: true,
  39295. configurable: true
  39296. });
  39297. /**
  39298. * Set the horizontal alignment from a string value.
  39299. * @param text can be either: 'left','right','center','stretch'
  39300. */
  39301. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  39302. var v = text.trim().toLocaleLowerCase();
  39303. switch (v) {
  39304. case "left":
  39305. this.horizontal = PrimitiveAlignment.AlignLeft;
  39306. return;
  39307. case "right":
  39308. this.horizontal = PrimitiveAlignment.AlignRight;
  39309. return;
  39310. case "center":
  39311. this.horizontal = PrimitiveAlignment.AlignCenter;
  39312. return;
  39313. case "stretch":
  39314. this.horizontal = PrimitiveAlignment.AlignStretch;
  39315. return;
  39316. }
  39317. };
  39318. /**
  39319. * Set the vertical alignment from a string value.
  39320. * @param text can be either: 'top','bottom','center','stretch'
  39321. */
  39322. PrimitiveAlignment.prototype.setVertical = function (text) {
  39323. var v = text.trim().toLocaleLowerCase();
  39324. switch (v) {
  39325. case "top":
  39326. this.vertical = PrimitiveAlignment.AlignTop;
  39327. return;
  39328. case "bottom":
  39329. this.vertical = PrimitiveAlignment.AlignBottom;
  39330. return;
  39331. case "center":
  39332. this.vertical = PrimitiveAlignment.AlignCenter;
  39333. return;
  39334. case "stretch":
  39335. this.vertical = PrimitiveAlignment.AlignStretch;
  39336. return;
  39337. }
  39338. };
  39339. /**
  39340. * Set the horizontal and or vertical alignments from a string value.
  39341. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  39342. */
  39343. PrimitiveAlignment.prototype.fromString = function (value) {
  39344. var m = value.trim().split(",");
  39345. for (var _i = 0; _i < m.length; _i++) {
  39346. var v = m[_i];
  39347. v = v.toLocaleLowerCase().trim();
  39348. // Horizontal
  39349. var i = v.indexOf("h:");
  39350. if (i === -1) {
  39351. i = v.indexOf("horizontal:");
  39352. }
  39353. if (i !== -1) {
  39354. v = v.substr(v.indexOf(":") + 1);
  39355. this.setHorizontal(v);
  39356. continue;
  39357. }
  39358. // Vertical
  39359. i = v.indexOf("v:");
  39360. if (i === -1) {
  39361. i = v.indexOf("vertical:");
  39362. }
  39363. if (i !== -1) {
  39364. v = v.substr(v.indexOf(":") + 1);
  39365. this.setVertical(v);
  39366. continue;
  39367. }
  39368. }
  39369. };
  39370. PrimitiveAlignment._AlignLeft = 1;
  39371. PrimitiveAlignment._AlignTop = 1; // Same as left
  39372. PrimitiveAlignment._AlignRight = 2;
  39373. PrimitiveAlignment._AlignBottom = 2; // Same as right
  39374. PrimitiveAlignment._AlignCenter = 3;
  39375. PrimitiveAlignment._AlignStretch = 4;
  39376. return PrimitiveAlignment;
  39377. })();
  39378. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  39379. /**
  39380. * Stores information about a Primitive that was intersected
  39381. */
  39382. var PrimitiveIntersectedInfo = (function () {
  39383. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  39384. this.prim = prim;
  39385. this.intersectionLocation = intersectionLocation;
  39386. }
  39387. return PrimitiveIntersectedInfo;
  39388. })();
  39389. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  39390. /**
  39391. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  39392. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  39393. */
  39394. var PrimitiveThickness = (function () {
  39395. function PrimitiveThickness(parentAccess, changedCallback) {
  39396. this._parentAccess = parentAccess;
  39397. this._changedCallback = changedCallback;
  39398. this._pixels = new Array(4);
  39399. this._percentages = new Array(4);
  39400. this._setType(0, PrimitiveThickness.Auto);
  39401. this._setType(1, PrimitiveThickness.Auto);
  39402. this._setType(2, PrimitiveThickness.Auto);
  39403. this._setType(3, PrimitiveThickness.Auto);
  39404. this._pixels[0] = 0;
  39405. this._pixels[1] = 0;
  39406. this._pixels[2] = 0;
  39407. this._pixels[3] = 0;
  39408. }
  39409. /**
  39410. * Set the thickness from a string value
  39411. * @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.
  39412. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39413. */
  39414. PrimitiveThickness.prototype.fromString = function (thickness) {
  39415. this._clear();
  39416. var m = thickness.trim().split(",");
  39417. // Special case, one value to apply to all edges
  39418. if (m.length === 1 && thickness.indexOf(":") === -1) {
  39419. this._setStringValue(m[0], 0, false);
  39420. this._setStringValue(m[0], 1, false);
  39421. this._setStringValue(m[0], 2, false);
  39422. this._setStringValue(m[0], 3, false);
  39423. this._changedCallback();
  39424. return;
  39425. }
  39426. var res = false;
  39427. for (var _i = 0; _i < m.length; _i++) {
  39428. var cm = m[_i];
  39429. res = this._extractString(cm, false) || res;
  39430. }
  39431. if (!res) {
  39432. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  39433. }
  39434. // Check the margin that weren't set and set them in auto
  39435. if ((this._flags & 0x000F) === 0)
  39436. this._flags |= PrimitiveThickness.Pixel << 0;
  39437. if ((this._flags & 0x00F0) === 0)
  39438. this._flags |= PrimitiveThickness.Pixel << 4;
  39439. if ((this._flags & 0x0F00) === 0)
  39440. this._flags |= PrimitiveThickness.Pixel << 8;
  39441. if ((this._flags & 0xF000) === 0)
  39442. this._flags |= PrimitiveThickness.Pixel << 12;
  39443. this._changedCallback();
  39444. };
  39445. /**
  39446. * Set the thickness from multiple string
  39447. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39448. * @param top the top thickness to set
  39449. * @param left the left thickness to set
  39450. * @param right the right thickness to set
  39451. * @param bottom the bottom thickness to set
  39452. */
  39453. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  39454. this._clear();
  39455. this._setStringValue(top, 0, false);
  39456. this._setStringValue(left, 1, false);
  39457. this._setStringValue(right, 2, false);
  39458. this._setStringValue(bottom, 3, false);
  39459. this._changedCallback();
  39460. return this;
  39461. };
  39462. /**
  39463. * Set the thickness from pixel values
  39464. * @param top the top thickness in pixels to set
  39465. * @param left the left thickness in pixels to set
  39466. * @param right the right thickness in pixels to set
  39467. * @param bottom the bottom thickness in pixels to set
  39468. */
  39469. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  39470. this._clear();
  39471. this._pixels[0] = top;
  39472. this._pixels[1] = left;
  39473. this._pixels[2] = right;
  39474. this._pixels[3] = bottom;
  39475. this._changedCallback();
  39476. return this;
  39477. };
  39478. /**
  39479. * Apply the same pixel value to all edges
  39480. * @param margin the value to set, in pixels.
  39481. */
  39482. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  39483. this._clear();
  39484. this._pixels[0] = margin;
  39485. this._pixels[1] = margin;
  39486. this._pixels[2] = margin;
  39487. this._pixels[3] = margin;
  39488. this._changedCallback();
  39489. return this;
  39490. };
  39491. /**
  39492. * Set all edges in auto
  39493. */
  39494. PrimitiveThickness.prototype.auto = function () {
  39495. this._clear();
  39496. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  39497. this._pixels[0] = 0;
  39498. this._pixels[1] = 0;
  39499. this._pixels[2] = 0;
  39500. this._pixels[3] = 0;
  39501. this._changedCallback();
  39502. return this;
  39503. };
  39504. PrimitiveThickness.prototype._clear = function () {
  39505. this._flags = 0;
  39506. this._pixels[0] = 0;
  39507. this._pixels[1] = 0;
  39508. this._pixels[2] = 0;
  39509. this._pixels[3] = 0;
  39510. this._percentages[0] = null;
  39511. this._percentages[1] = null;
  39512. this._percentages[2] = null;
  39513. this._percentages[3] = null;
  39514. };
  39515. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  39516. var v = value.trim().toLocaleLowerCase();
  39517. if (v.indexOf("top:") === 0) {
  39518. v = v.substr(4).trim();
  39519. return this._setStringValue(v, 0, emitChanged);
  39520. }
  39521. if (v.indexOf("left:") === 0) {
  39522. v = v.substr(5).trim();
  39523. return this._setStringValue(v, 1, emitChanged);
  39524. }
  39525. if (v.indexOf("right:") === 0) {
  39526. v = v.substr(6).trim();
  39527. return this._setStringValue(v, 2, emitChanged);
  39528. }
  39529. if (v.indexOf("bottom:") === 0) {
  39530. v = v.substr(7).trim();
  39531. return this._setStringValue(v, 3, emitChanged);
  39532. }
  39533. return false;
  39534. };
  39535. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  39536. // Check for auto
  39537. var v = value.trim().toLocaleLowerCase();
  39538. if (v === "auto") {
  39539. if (this._isType(index, PrimitiveThickness.Auto)) {
  39540. return true;
  39541. }
  39542. this._setType(index, PrimitiveThickness.Auto);
  39543. this._pixels[index] = 0;
  39544. if (emitChanged) {
  39545. this._changedCallback();
  39546. }
  39547. }
  39548. else if (v === "inherit") {
  39549. if (this._isType(index, PrimitiveThickness.Inherit)) {
  39550. return true;
  39551. }
  39552. this._setType(index, PrimitiveThickness.Inherit);
  39553. this._pixels[index] = null;
  39554. if (emitChanged) {
  39555. this._changedCallback();
  39556. }
  39557. }
  39558. else {
  39559. var pI = v.indexOf("%");
  39560. // Check for percentage
  39561. if (pI !== -1) {
  39562. var n_1 = v.substr(0, pI);
  39563. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  39564. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  39565. return true;
  39566. }
  39567. this._setType(index, PrimitiveThickness.Percentage);
  39568. if (isNaN(number_1)) {
  39569. return false;
  39570. }
  39571. this._percentages[index] = number_1;
  39572. if (emitChanged) {
  39573. this._changedCallback();
  39574. }
  39575. return true;
  39576. }
  39577. // Check for pixel
  39578. var n;
  39579. pI = v.indexOf("px");
  39580. if (pI !== -1) {
  39581. n = v.substr(0, pI).trim();
  39582. }
  39583. else {
  39584. n = v;
  39585. }
  39586. var number = Number(n);
  39587. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  39588. return true;
  39589. }
  39590. if (isNaN(number)) {
  39591. return false;
  39592. }
  39593. this._pixels[index] = number;
  39594. this._setType(index, PrimitiveThickness.Pixel);
  39595. if (emitChanged) {
  39596. this._changedCallback();
  39597. }
  39598. return true;
  39599. }
  39600. };
  39601. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  39602. // 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
  39603. value = Math.round(value);
  39604. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  39605. return;
  39606. }
  39607. this._setType(index, PrimitiveThickness.Pixel);
  39608. this._pixels[index] = value;
  39609. if (emitChanged) {
  39610. this._changedCallback();
  39611. }
  39612. };
  39613. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  39614. // Clip Value to bounds
  39615. value = Math.min(1, value);
  39616. value = Math.max(0, value);
  39617. value = Math.round(value * 100) / 100; // 0.01 precision
  39618. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  39619. return;
  39620. }
  39621. this._setType(index, PrimitiveThickness.Percentage);
  39622. this._percentages[index] = value;
  39623. if (emitChanged) {
  39624. this._changedCallback();
  39625. }
  39626. };
  39627. PrimitiveThickness.prototype._getStringValue = function (index) {
  39628. var f = (this._flags >> (index * 4)) & 0xF;
  39629. switch (f) {
  39630. case PrimitiveThickness.Auto:
  39631. return "auto";
  39632. case PrimitiveThickness.Pixel:
  39633. return this._pixels[index] + "px";
  39634. case PrimitiveThickness.Percentage:
  39635. return this._percentages[index] * 100 + "%";
  39636. case PrimitiveThickness.Inherit:
  39637. return "inherit";
  39638. }
  39639. return "";
  39640. };
  39641. PrimitiveThickness.prototype._isType = function (index, type) {
  39642. var f = (this._flags >> (index * 4)) & 0xF;
  39643. return f === type;
  39644. };
  39645. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  39646. var t = (this._flags >> (index * 4)) & 0xF;
  39647. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  39648. var p = this._parentAccess();
  39649. if (p) {
  39650. return p._getType(index, true);
  39651. }
  39652. return PrimitiveThickness.Auto;
  39653. }
  39654. return t;
  39655. };
  39656. PrimitiveThickness.prototype._setType = function (index, type) {
  39657. this._flags &= ~(0xF << (index * 4));
  39658. this._flags |= type << (index * 4);
  39659. };
  39660. PrimitiveThickness.prototype.setTop = function (value) {
  39661. if (typeof value === "string") {
  39662. this._setStringValue(value, 0, true);
  39663. }
  39664. else {
  39665. this.topPixels = value;
  39666. }
  39667. };
  39668. PrimitiveThickness.prototype.setLeft = function (value) {
  39669. if (typeof value === "string") {
  39670. this._setStringValue(value, 1, true);
  39671. }
  39672. else {
  39673. this.leftPixels = value;
  39674. }
  39675. };
  39676. PrimitiveThickness.prototype.setRight = function (value) {
  39677. if (typeof value === "string") {
  39678. this._setStringValue(value, 2, true);
  39679. }
  39680. else {
  39681. this.rightPixels = value;
  39682. }
  39683. };
  39684. PrimitiveThickness.prototype.setBottom = function (value) {
  39685. if (typeof value === "string") {
  39686. this._setStringValue(value, 3, true);
  39687. }
  39688. else {
  39689. this.bottomPixels = value;
  39690. }
  39691. };
  39692. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  39693. /**
  39694. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39695. */
  39696. get: function () {
  39697. return this._getStringValue(0);
  39698. },
  39699. set: function (value) {
  39700. this._setStringValue(value, 0, true);
  39701. },
  39702. enumerable: true,
  39703. configurable: true
  39704. });
  39705. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  39706. /**
  39707. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39708. */
  39709. get: function () {
  39710. return this._getStringValue(1);
  39711. },
  39712. set: function (value) {
  39713. this._setStringValue(value, 1, true);
  39714. },
  39715. enumerable: true,
  39716. configurable: true
  39717. });
  39718. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  39719. /**
  39720. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39721. */
  39722. get: function () {
  39723. return this._getStringValue(2);
  39724. },
  39725. set: function (value) {
  39726. this._setStringValue(value, 2, true);
  39727. },
  39728. enumerable: true,
  39729. configurable: true
  39730. });
  39731. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  39732. /**
  39733. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39734. */
  39735. get: function () {
  39736. return this._getStringValue(3);
  39737. },
  39738. set: function (value) {
  39739. this._setStringValue(value, 3, true);
  39740. },
  39741. enumerable: true,
  39742. configurable: true
  39743. });
  39744. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  39745. /**
  39746. * Get/set the top thickness in pixel.
  39747. */
  39748. get: function () {
  39749. return this._pixels[0];
  39750. },
  39751. set: function (value) {
  39752. this._setPixels(value, 0, true);
  39753. },
  39754. enumerable: true,
  39755. configurable: true
  39756. });
  39757. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  39758. /**
  39759. * Get/set the left thickness in pixel.
  39760. */
  39761. get: function () {
  39762. return this._pixels[1];
  39763. },
  39764. set: function (value) {
  39765. this._setPixels(value, 1, true);
  39766. },
  39767. enumerable: true,
  39768. configurable: true
  39769. });
  39770. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  39771. /**
  39772. * Get/set the right thickness in pixel.
  39773. */
  39774. get: function () {
  39775. return this._pixels[2];
  39776. },
  39777. set: function (value) {
  39778. this._setPixels(value, 2, true);
  39779. },
  39780. enumerable: true,
  39781. configurable: true
  39782. });
  39783. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  39784. /**
  39785. * Get/set the bottom thickness in pixel.
  39786. */
  39787. get: function () {
  39788. return this._pixels[3];
  39789. },
  39790. set: function (value) {
  39791. this._setPixels(value, 3, true);
  39792. },
  39793. enumerable: true,
  39794. configurable: true
  39795. });
  39796. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  39797. /**
  39798. * Get/set the top thickness in percentage.
  39799. * The get will return a valid value only if the edge type is percentage.
  39800. * The Set will change the edge mode if needed
  39801. */
  39802. get: function () {
  39803. return this._percentages[0];
  39804. },
  39805. set: function (value) {
  39806. this._setPercentage(value, 0, true);
  39807. },
  39808. enumerable: true,
  39809. configurable: true
  39810. });
  39811. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  39812. /**
  39813. * Get/set the left thickness in percentage.
  39814. * The get will return a valid value only if the edge mode is percentage.
  39815. * The Set will change the edge mode if needed
  39816. */
  39817. get: function () {
  39818. return this._percentages[1];
  39819. },
  39820. set: function (value) {
  39821. this._setPercentage(value, 1, true);
  39822. },
  39823. enumerable: true,
  39824. configurable: true
  39825. });
  39826. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  39827. /**
  39828. * Get/set the right thickness in percentage.
  39829. * The get will return a valid value only if the edge mode is percentage.
  39830. * The Set will change the edge mode if needed
  39831. */
  39832. get: function () {
  39833. return this._percentages[2];
  39834. },
  39835. set: function (value) {
  39836. this._setPercentage(value, 2, true);
  39837. },
  39838. enumerable: true,
  39839. configurable: true
  39840. });
  39841. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  39842. /**
  39843. * Get/set the bottom thickness in percentage.
  39844. * The get will return a valid value only if the edge mode is percentage.
  39845. * The Set will change the edge mode if needed
  39846. */
  39847. get: function () {
  39848. return this._percentages[3];
  39849. },
  39850. set: function (value) {
  39851. this._setPercentage(value, 3, true);
  39852. },
  39853. enumerable: true,
  39854. configurable: true
  39855. });
  39856. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  39857. /**
  39858. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  39859. */
  39860. get: function () {
  39861. return this._getType(0, false);
  39862. },
  39863. set: function (mode) {
  39864. this._setType(0, mode);
  39865. },
  39866. enumerable: true,
  39867. configurable: true
  39868. });
  39869. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  39870. /**
  39871. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  39872. */
  39873. get: function () {
  39874. return this._getType(1, false);
  39875. },
  39876. set: function (mode) {
  39877. this._setType(1, mode);
  39878. },
  39879. enumerable: true,
  39880. configurable: true
  39881. });
  39882. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  39883. /**
  39884. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  39885. */
  39886. get: function () {
  39887. return this._getType(2, false);
  39888. },
  39889. set: function (mode) {
  39890. this._setType(2, mode);
  39891. },
  39892. enumerable: true,
  39893. configurable: true
  39894. });
  39895. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  39896. /**
  39897. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  39898. */
  39899. get: function () {
  39900. return this._getType(3, false);
  39901. },
  39902. set: function (mode) {
  39903. this._setType(3, mode);
  39904. },
  39905. enumerable: true,
  39906. configurable: true
  39907. });
  39908. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  39909. var type = this._getType(index, false);
  39910. if (type === PrimitiveThickness.Inherit) {
  39911. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  39912. return;
  39913. }
  39914. if (type !== PrimitiveThickness.Percentage) {
  39915. return;
  39916. }
  39917. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  39918. this._pixels[index] = pixels;
  39919. if (emitChanged) {
  39920. this._changedCallback();
  39921. }
  39922. };
  39923. /**
  39924. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  39925. * @param sourceArea the source area
  39926. * @param contentSize the content size to position/resize
  39927. * @param alignment the alignment setting
  39928. * @param dstOffset the position of the content
  39929. * @param dstArea the new size of the content
  39930. */
  39931. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea) {
  39932. // Fetch some data
  39933. var topType = this._getType(0, true);
  39934. var leftType = this._getType(1, true);
  39935. var rightType = this._getType(2, true);
  39936. var bottomType = this._getType(3, true);
  39937. var hasWidth = contentSize && (contentSize.width != null);
  39938. var hasHeight = contentSize && (contentSize.height != null);
  39939. var width = hasWidth ? contentSize.width : 0;
  39940. var height = hasHeight ? contentSize.height : 0;
  39941. var isTopAuto = topType === PrimitiveThickness.Auto;
  39942. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  39943. var isRightAuto = rightType === PrimitiveThickness.Auto;
  39944. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  39945. switch (alignment.horizontal) {
  39946. case PrimitiveAlignment.AlignLeft:
  39947. {
  39948. if (isLeftAuto) {
  39949. dstOffset.x = 0;
  39950. }
  39951. else {
  39952. this._computePixels(1, sourceArea, true);
  39953. dstOffset.x = this.leftPixels;
  39954. }
  39955. dstArea.width = width;
  39956. break;
  39957. }
  39958. case PrimitiveAlignment.AlignRight:
  39959. {
  39960. if (isRightAuto) {
  39961. dstOffset.x = Math.round(sourceArea.width - width);
  39962. }
  39963. else {
  39964. this._computePixels(2, sourceArea, true);
  39965. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  39966. }
  39967. dstArea.width = width;
  39968. break;
  39969. }
  39970. case PrimitiveAlignment.AlignStretch:
  39971. {
  39972. if (isLeftAuto) {
  39973. dstOffset.x = 0;
  39974. }
  39975. else {
  39976. this._computePixels(1, sourceArea, true);
  39977. dstOffset.x = this.leftPixels;
  39978. }
  39979. var right = 0;
  39980. if (!isRightAuto) {
  39981. this._computePixels(2, sourceArea, true);
  39982. right = this.rightPixels;
  39983. }
  39984. dstArea.width = sourceArea.width - (dstOffset.x + right);
  39985. break;
  39986. }
  39987. case PrimitiveAlignment.AlignCenter:
  39988. {
  39989. if (!isLeftAuto) {
  39990. this._computePixels(1, sourceArea, true);
  39991. }
  39992. if (!isRightAuto) {
  39993. this._computePixels(2, sourceArea, true);
  39994. }
  39995. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  39996. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  39997. dstArea.width = width;
  39998. break;
  39999. }
  40000. }
  40001. switch (alignment.vertical) {
  40002. case PrimitiveAlignment.AlignTop:
  40003. {
  40004. if (isTopAuto) {
  40005. dstOffset.y = sourceArea.height - height;
  40006. }
  40007. else {
  40008. this._computePixels(0, sourceArea, true);
  40009. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  40010. }
  40011. dstArea.height = height;
  40012. break;
  40013. }
  40014. case PrimitiveAlignment.AlignBottom:
  40015. {
  40016. if (isBottomAuto) {
  40017. dstOffset.y = 0;
  40018. }
  40019. else {
  40020. this._computePixels(3, sourceArea, true);
  40021. dstOffset.y = this.bottomPixels;
  40022. }
  40023. dstArea.height = height;
  40024. break;
  40025. }
  40026. case PrimitiveAlignment.AlignStretch:
  40027. {
  40028. if (isBottomAuto) {
  40029. dstOffset.y = 0;
  40030. }
  40031. else {
  40032. this._computePixels(3, sourceArea, true);
  40033. dstOffset.y = this.bottomPixels;
  40034. }
  40035. var top_1 = 0;
  40036. if (!isTopAuto) {
  40037. this._computePixels(0, sourceArea, true);
  40038. top_1 = this.topPixels;
  40039. }
  40040. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  40041. break;
  40042. }
  40043. case PrimitiveAlignment.AlignCenter:
  40044. {
  40045. if (!isTopAuto) {
  40046. this._computePixels(0, sourceArea, true);
  40047. }
  40048. if (!isBottomAuto) {
  40049. this._computePixels(3, sourceArea, true);
  40050. }
  40051. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  40052. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  40053. dstArea.height = height;
  40054. break;
  40055. }
  40056. }
  40057. };
  40058. /**
  40059. * Compute an area and its position considering this thickness properties based on a given source area
  40060. * @param sourceArea the source area
  40061. * @param dstOffset the position of the resulting area
  40062. * @param dstArea the size of the resulting area
  40063. */
  40064. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  40065. this._computePixels(0, sourceArea, true);
  40066. this._computePixels(1, sourceArea, true);
  40067. this._computePixels(2, sourceArea, true);
  40068. this._computePixels(3, sourceArea, true);
  40069. dstOffset.x = this.leftPixels;
  40070. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  40071. dstOffset.y = this.bottomPixels;
  40072. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  40073. };
  40074. /**
  40075. * Compute an area considering this thickness properties based on a given source area
  40076. * @param sourceArea the source area
  40077. * @param result the resulting area
  40078. */
  40079. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  40080. this._computePixels(0, sourceArea, true);
  40081. this._computePixels(1, sourceArea, true);
  40082. this._computePixels(2, sourceArea, true);
  40083. this._computePixels(3, sourceArea, true);
  40084. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  40085. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  40086. };
  40087. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  40088. this._computePixels(0, sourceArea, true);
  40089. this._computePixels(1, sourceArea, true);
  40090. this._computePixels(2, sourceArea, true);
  40091. this._computePixels(3, sourceArea, true);
  40092. dstOffset.x = this.leftPixels;
  40093. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  40094. dstOffset.y = this.bottomPixels;
  40095. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  40096. };
  40097. PrimitiveThickness.Auto = 0x1;
  40098. PrimitiveThickness.Inherit = 0x2;
  40099. PrimitiveThickness.Percentage = 0x4;
  40100. PrimitiveThickness.Pixel = 0x8;
  40101. return PrimitiveThickness;
  40102. })();
  40103. BABYLON.PrimitiveThickness = PrimitiveThickness;
  40104. /**
  40105. * Main class used for the Primitive Intersection API
  40106. */
  40107. var IntersectInfo2D = (function () {
  40108. function IntersectInfo2D() {
  40109. this.findFirstOnly = false;
  40110. this.intersectHidden = false;
  40111. this.pickPosition = BABYLON.Vector2.Zero();
  40112. }
  40113. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  40114. /**
  40115. * true if at least one primitive intersected during the test
  40116. */
  40117. get: function () {
  40118. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  40119. },
  40120. enumerable: true,
  40121. configurable: true
  40122. });
  40123. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  40124. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  40125. var cur = _a[_i];
  40126. if (cur.prim === prim) {
  40127. return cur.intersectionLocation;
  40128. }
  40129. }
  40130. return null;
  40131. };
  40132. // Internals, don't use
  40133. IntersectInfo2D.prototype._exit = function (firstLevel) {
  40134. if (firstLevel) {
  40135. this._globalPickPosition = null;
  40136. }
  40137. };
  40138. return IntersectInfo2D;
  40139. })();
  40140. BABYLON.IntersectInfo2D = IntersectInfo2D;
  40141. var Prim2DBase = (function (_super) {
  40142. __extends(Prim2DBase, _super);
  40143. function Prim2DBase(settings) {
  40144. // Avoid checking every time if the object exists
  40145. if (settings == null) {
  40146. settings = {};
  40147. }
  40148. // BASE CLASS CALL
  40149. _super.call(this);
  40150. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  40151. var owner;
  40152. var parent;
  40153. if (Prim2DBase._isCanvasInit) {
  40154. owner = this;
  40155. parent = null;
  40156. this._canvasPreInit(settings);
  40157. }
  40158. else {
  40159. if (settings.parent != null) {
  40160. parent = settings.parent;
  40161. owner = settings.parent.owner;
  40162. if (!owner) {
  40163. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  40164. }
  40165. 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)) {
  40166. 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");
  40167. }
  40168. }
  40169. }
  40170. // Fields initialization
  40171. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40172. this._size = null; //Size.Zero();
  40173. this._scale = new BABYLON.Vector2(1, 1);
  40174. this._actualSize = null;
  40175. this._boundingSize = BABYLON.Size.Zero();
  40176. this._layoutArea = BABYLON.Size.Zero();
  40177. this._layoutAreaPos = BABYLON.Vector2.Zero();
  40178. this._marginOffset = BABYLON.Vector2.Zero();
  40179. this._paddingOffset = BABYLON.Vector2.Zero();
  40180. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  40181. this._parentContentArea = BABYLON.Size.Zero();
  40182. this._lastAutoSizeArea = BABYLON.Size.Zero();
  40183. this._contentArea = new BABYLON.Size(null, null);
  40184. this._pointerEventObservable = new BABYLON.Observable();
  40185. this._boundingInfo = new BABYLON.BoundingInfo2D();
  40186. this._owner = owner;
  40187. this._parent = null;
  40188. this._margin = null;
  40189. this._padding = null;
  40190. this._marginAlignment = null;
  40191. this._id = settings.id;
  40192. this.propertyChanged = new BABYLON.Observable();
  40193. this._children = new Array();
  40194. this._localTransform = new BABYLON.Matrix();
  40195. this._globalTransform = null;
  40196. this._invGlobalTransform = null;
  40197. this._globalTransformProcessStep = 0;
  40198. this._globalTransformStep = 0;
  40199. this._renderGroup = null;
  40200. this._primLinearPosition = 0;
  40201. this._manualZOrder = null;
  40202. this._zOrder = 0;
  40203. this._zMax = 0;
  40204. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40205. var isPickable = true;
  40206. var isContainer = true;
  40207. if (settings.isPickable !== undefined) {
  40208. isPickable = settings.isPickable;
  40209. }
  40210. if (settings.isContainer !== undefined) {
  40211. isContainer = settings.isContainer;
  40212. }
  40213. this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0));
  40214. if (settings.opacity != null) {
  40215. this._opacity = settings.opacity;
  40216. }
  40217. else {
  40218. this._opacity = 1;
  40219. }
  40220. this._updateRenderMode();
  40221. if (settings.childrenFlatZOrder) {
  40222. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40223. }
  40224. // If the parent is given, initialize the hierarchy/owner related data
  40225. if (parent != null) {
  40226. parent.addChild(this);
  40227. this._hierarchyDepth = parent._hierarchyDepth + 1;
  40228. this._patchHierarchy(parent.owner);
  40229. }
  40230. // If it's a group, detect its own states
  40231. if (this.owner && this instanceof BABYLON.Group2D) {
  40232. var group = this;
  40233. group.detectGroupStates();
  40234. }
  40235. // Time to insert children if some are specified
  40236. if (settings.children != null) {
  40237. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  40238. var child = _a[_i];
  40239. this.addChild(child);
  40240. // Good time to patch the hierarchy, it won't go very far if there's no need to
  40241. if (this.owner != null) {
  40242. child._patchHierarchy(this.owner);
  40243. }
  40244. }
  40245. }
  40246. if (settings.zOrder != null) {
  40247. this.zOrder = settings.zOrder;
  40248. }
  40249. // Set the model related properties
  40250. if (settings.position != null) {
  40251. this.position = settings.position;
  40252. }
  40253. else if (settings.x != null || settings.y != null) {
  40254. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  40255. }
  40256. else {
  40257. this._position = null;
  40258. }
  40259. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  40260. if (settings.scale != null) {
  40261. this.scale = settings.scale;
  40262. }
  40263. else {
  40264. if (settings.scaleX != null) {
  40265. this.scaleX = settings.scaleX;
  40266. }
  40267. if (settings.scaleY != null) {
  40268. this.scaleY = settings.scaleY;
  40269. }
  40270. }
  40271. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  40272. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  40273. // Layout Engine
  40274. if (settings.layoutEngine != null) {
  40275. if (typeof settings.layoutEngine === "string") {
  40276. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  40277. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  40278. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40279. }
  40280. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  40281. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  40282. }
  40283. else if (name_1.indexOf("verticalstackpanel") === 0) {
  40284. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  40285. }
  40286. }
  40287. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  40288. this.layoutEngine = settings.layoutEngine;
  40289. }
  40290. }
  40291. // Set the layout/margin stuffs
  40292. if (settings.marginTop) {
  40293. this.margin.setTop(settings.marginTop);
  40294. }
  40295. if (settings.marginLeft) {
  40296. this.margin.setLeft(settings.marginLeft);
  40297. }
  40298. if (settings.marginRight) {
  40299. this.margin.setRight(settings.marginRight);
  40300. }
  40301. if (settings.marginBottom) {
  40302. this.margin.setBottom(settings.marginBottom);
  40303. }
  40304. if (settings.margin) {
  40305. if (typeof settings.margin === "string") {
  40306. this.margin.fromString(settings.margin);
  40307. }
  40308. else {
  40309. this.margin.fromUniformPixels(settings.margin);
  40310. }
  40311. }
  40312. if (settings.marginHAlignment) {
  40313. this.marginAlignment.horizontal = settings.marginHAlignment;
  40314. }
  40315. if (settings.marginVAlignment) {
  40316. this.marginAlignment.vertical = settings.marginVAlignment;
  40317. }
  40318. if (settings.marginAlignment) {
  40319. this.marginAlignment.fromString(settings.marginAlignment);
  40320. }
  40321. if (settings.paddingTop) {
  40322. this.padding.setTop(settings.paddingTop);
  40323. }
  40324. if (settings.paddingLeft) {
  40325. this.padding.setLeft(settings.paddingLeft);
  40326. }
  40327. if (settings.paddingRight) {
  40328. this.padding.setRight(settings.paddingRight);
  40329. }
  40330. if (settings.paddingBottom) {
  40331. this.padding.setBottom(settings.paddingBottom);
  40332. }
  40333. if (settings.padding) {
  40334. this.padding.fromString(settings.padding);
  40335. }
  40336. // Dirty layout and positioning
  40337. this._parentLayoutDirty();
  40338. this._positioningDirty();
  40339. }
  40340. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  40341. get: function () {
  40342. if (!this._actionManager) {
  40343. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  40344. }
  40345. return this._actionManager;
  40346. },
  40347. enumerable: true,
  40348. configurable: true
  40349. });
  40350. /**
  40351. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  40352. * @param predicate the predicate to test on each parent
  40353. * @return the first primitive where the predicate was successful
  40354. */
  40355. Prim2DBase.prototype.traverseUp = function (predicate) {
  40356. var p = this;
  40357. while (p != null) {
  40358. if (predicate(p)) {
  40359. return p;
  40360. }
  40361. p = p._parent;
  40362. }
  40363. return null;
  40364. };
  40365. Object.defineProperty(Prim2DBase.prototype, "owner", {
  40366. /**
  40367. * Retrieve the owner Canvas2D
  40368. */
  40369. get: function () {
  40370. return this._owner;
  40371. },
  40372. enumerable: true,
  40373. configurable: true
  40374. });
  40375. Object.defineProperty(Prim2DBase.prototype, "parent", {
  40376. /**
  40377. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  40378. */
  40379. get: function () {
  40380. return this._parent;
  40381. },
  40382. enumerable: true,
  40383. configurable: true
  40384. });
  40385. Object.defineProperty(Prim2DBase.prototype, "children", {
  40386. /**
  40387. * The array of direct children primitives
  40388. */
  40389. get: function () {
  40390. return this._children;
  40391. },
  40392. enumerable: true,
  40393. configurable: true
  40394. });
  40395. Object.defineProperty(Prim2DBase.prototype, "id", {
  40396. /**
  40397. * The identifier of this primitive, may not be unique, it's for information purpose only
  40398. */
  40399. get: function () {
  40400. return this._id;
  40401. },
  40402. enumerable: true,
  40403. configurable: true
  40404. });
  40405. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  40406. get: function () {
  40407. if (this._actualPosition != null) {
  40408. return this._actualPosition;
  40409. }
  40410. if (this._position != null) {
  40411. return this._position;
  40412. }
  40413. // At least return 0,0, we can't return null on actualPosition
  40414. return Prim2DBase._nullPosition;
  40415. },
  40416. /**
  40417. * DO NOT INVOKE for internal purpose only
  40418. */
  40419. set: function (val) {
  40420. this._actualPosition = val;
  40421. },
  40422. enumerable: true,
  40423. configurable: true
  40424. });
  40425. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  40426. /**
  40427. * Shortcut to actualPosition.x
  40428. */
  40429. get: function () {
  40430. return this.actualPosition.x;
  40431. },
  40432. enumerable: true,
  40433. configurable: true
  40434. });
  40435. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  40436. /**
  40437. * Shortcut to actualPosition.y
  40438. */
  40439. get: function () {
  40440. return this.actualPosition.y;
  40441. },
  40442. enumerable: true,
  40443. configurable: true
  40444. });
  40445. Object.defineProperty(Prim2DBase.prototype, "position", {
  40446. /**
  40447. * Position of the primitive, relative to its parent.
  40448. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  40449. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  40450. * Setting this property may have no effect is specific alignment are in effect.
  40451. */
  40452. get: function () {
  40453. return this._position || Prim2DBase._nullPosition;
  40454. },
  40455. set: function (value) {
  40456. if (!this._checkPositionChange()) {
  40457. return;
  40458. }
  40459. this._position = value;
  40460. this.markAsDirty("actualPosition");
  40461. },
  40462. enumerable: true,
  40463. configurable: true
  40464. });
  40465. Object.defineProperty(Prim2DBase.prototype, "x", {
  40466. /**
  40467. * Direct access to the position.x value of the primitive
  40468. * Use this property when you only want to change one component of the position property
  40469. */
  40470. get: function () {
  40471. if (!this._position) {
  40472. return null;
  40473. }
  40474. return this._position.x;
  40475. },
  40476. set: function (value) {
  40477. if (!this._checkPositionChange()) {
  40478. return;
  40479. }
  40480. if (!this._position) {
  40481. this._position = BABYLON.Vector2.Zero();
  40482. }
  40483. if (this._position.x === value) {
  40484. return;
  40485. }
  40486. this._position.x = value;
  40487. this.markAsDirty("position");
  40488. this.markAsDirty("actualPosition");
  40489. },
  40490. enumerable: true,
  40491. configurable: true
  40492. });
  40493. Object.defineProperty(Prim2DBase.prototype, "y", {
  40494. /**
  40495. * Direct access to the position.y value of the primitive
  40496. * Use this property when you only want to change one component of the position property
  40497. */
  40498. get: function () {
  40499. if (!this._position) {
  40500. return null;
  40501. }
  40502. return this._position.y;
  40503. },
  40504. set: function (value) {
  40505. if (!this._checkPositionChange()) {
  40506. return;
  40507. }
  40508. if (!this._position) {
  40509. this._position = BABYLON.Vector2.Zero();
  40510. }
  40511. if (this._position.y === value) {
  40512. return;
  40513. }
  40514. this._position.y = value;
  40515. this.markAsDirty("position");
  40516. this.markAsDirty("actualPosition");
  40517. },
  40518. enumerable: true,
  40519. configurable: true
  40520. });
  40521. Object.defineProperty(Prim2DBase.prototype, "size", {
  40522. /**
  40523. * Size of the primitive or its bounding area
  40524. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  40525. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  40526. */
  40527. get: function () {
  40528. if (!this._size || this._size.width == null || this._size.height == null) {
  40529. if (Prim2DBase.boundinbBoxReentrency) {
  40530. return Prim2DBase.nullSize;
  40531. }
  40532. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  40533. return this._boundingSize;
  40534. }
  40535. Prim2DBase.boundinbBoxReentrency = true;
  40536. var b = this.boundingInfo;
  40537. Prim2DBase.boundinbBoxReentrency = false;
  40538. return this._boundingSize;
  40539. }
  40540. return this._size;
  40541. },
  40542. set: function (value) {
  40543. this._size = value;
  40544. },
  40545. enumerable: true,
  40546. configurable: true
  40547. });
  40548. Object.defineProperty(Prim2DBase.prototype, "width", {
  40549. /**
  40550. * Direct access to the size.width value of the primitive
  40551. * Use this property when you only want to change one component of the size property
  40552. */
  40553. get: function () {
  40554. if (!this.size) {
  40555. return null;
  40556. }
  40557. return this.size.width;
  40558. },
  40559. set: function (value) {
  40560. if (!this.size) {
  40561. this.size = new BABYLON.Size(value, 0);
  40562. return;
  40563. }
  40564. if (this.size.width === value) {
  40565. return;
  40566. }
  40567. this.size.width = value;
  40568. this.markAsDirty("size");
  40569. this._positioningDirty();
  40570. },
  40571. enumerable: true,
  40572. configurable: true
  40573. });
  40574. Object.defineProperty(Prim2DBase.prototype, "height", {
  40575. /**
  40576. * Direct access to the size.height value of the primitive
  40577. * Use this property when you only want to change one component of the size property
  40578. */
  40579. get: function () {
  40580. if (!this.size) {
  40581. return null;
  40582. }
  40583. return this.size.height;
  40584. },
  40585. set: function (value) {
  40586. if (!this.size) {
  40587. this.size = new BABYLON.Size(0, value);
  40588. return;
  40589. }
  40590. if (this.size.height === value) {
  40591. return;
  40592. }
  40593. this.size.height = value;
  40594. this.markAsDirty("size");
  40595. this._positioningDirty();
  40596. },
  40597. enumerable: true,
  40598. configurable: true
  40599. });
  40600. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  40601. get: function () {
  40602. return this._rotation;
  40603. },
  40604. set: function (value) {
  40605. this._rotation = value;
  40606. },
  40607. enumerable: true,
  40608. configurable: true
  40609. });
  40610. Object.defineProperty(Prim2DBase.prototype, "scale", {
  40611. get: function () {
  40612. return this._scale.x;
  40613. },
  40614. set: function (value) {
  40615. this._scale.x = this._scale.y = value;
  40616. },
  40617. enumerable: true,
  40618. configurable: true
  40619. });
  40620. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  40621. /**
  40622. * Return the size of the primitive as it's being rendered into the target.
  40623. * 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.
  40624. * BEWARE: don't use the setter, it's for internal purpose only
  40625. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  40626. */
  40627. get: function () {
  40628. if (this._actualSize) {
  40629. return this._actualSize;
  40630. }
  40631. return this._size;
  40632. },
  40633. set: function (value) {
  40634. if (this._actualSize.equals(value)) {
  40635. return;
  40636. }
  40637. this._actualSize = value;
  40638. },
  40639. enumerable: true,
  40640. configurable: true
  40641. });
  40642. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  40643. get: function () {
  40644. if (this._manualZOrder != null) {
  40645. return this._manualZOrder;
  40646. }
  40647. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40648. this._updateZOrder();
  40649. }
  40650. return (1 - this._zOrder);
  40651. },
  40652. enumerable: true,
  40653. configurable: true
  40654. });
  40655. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  40656. /**
  40657. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  40658. * The Primitive's size won't be less than specified.
  40659. * The default value depends of the Primitive type
  40660. */
  40661. get: function () {
  40662. return this._minSize;
  40663. },
  40664. set: function (value) {
  40665. if (this._minSize && value && this._minSize.equals(value)) {
  40666. return;
  40667. }
  40668. this._minSize = value;
  40669. this._parentLayoutDirty();
  40670. },
  40671. enumerable: true,
  40672. configurable: true
  40673. });
  40674. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  40675. /**
  40676. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  40677. * The Primitive's size won't be more than specified.
  40678. * The default value depends of the Primitive type
  40679. */
  40680. get: function () {
  40681. return this._maxSize;
  40682. },
  40683. set: function (value) {
  40684. if (this._maxSize && value && this._maxSize.equals(value)) {
  40685. return;
  40686. }
  40687. this._maxSize = value;
  40688. this._parentLayoutDirty();
  40689. },
  40690. enumerable: true,
  40691. configurable: true
  40692. });
  40693. Object.defineProperty(Prim2DBase.prototype, "origin", {
  40694. /**
  40695. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  40696. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  40697. * For instance:
  40698. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  40699. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  40700. * 0,1 means the center is top/left
  40701. * @returns The normalized center.
  40702. */
  40703. get: function () {
  40704. return this._origin;
  40705. },
  40706. set: function (value) {
  40707. this._origin = value;
  40708. },
  40709. enumerable: true,
  40710. configurable: true
  40711. });
  40712. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  40713. get: function () {
  40714. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  40715. },
  40716. set: function (value) {
  40717. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  40718. },
  40719. enumerable: true,
  40720. configurable: true
  40721. });
  40722. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  40723. get: function () {
  40724. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  40725. },
  40726. set: function (value) {
  40727. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  40728. },
  40729. enumerable: true,
  40730. configurable: true
  40731. });
  40732. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  40733. get: function () {
  40734. return this._manualZOrder;
  40735. },
  40736. set: function (value) {
  40737. if (this._manualZOrder === value) {
  40738. return;
  40739. }
  40740. this._manualZOrder = value;
  40741. this.onZOrderChanged();
  40742. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  40743. this._actualZOrderChangedObservable.notifyObservers(value);
  40744. }
  40745. },
  40746. enumerable: true,
  40747. configurable: true
  40748. });
  40749. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  40750. get: function () {
  40751. return this._manualZOrder != null;
  40752. },
  40753. enumerable: true,
  40754. configurable: true
  40755. });
  40756. Object.defineProperty(Prim2DBase.prototype, "margin", {
  40757. get: function () {
  40758. var _this = this;
  40759. if (!this._margin) {
  40760. this._margin = new PrimitiveThickness(function () {
  40761. if (!_this.parent) {
  40762. return null;
  40763. }
  40764. return _this.parent.margin;
  40765. }, function () { return _this._positioningDirty(); });
  40766. }
  40767. return this._margin;
  40768. },
  40769. enumerable: true,
  40770. configurable: true
  40771. });
  40772. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  40773. get: function () {
  40774. return (this._margin !== null) || (this._marginAlignment !== null);
  40775. },
  40776. enumerable: true,
  40777. configurable: true
  40778. });
  40779. Object.defineProperty(Prim2DBase.prototype, "padding", {
  40780. get: function () {
  40781. var _this = this;
  40782. if (!this._padding) {
  40783. this._padding = new PrimitiveThickness(function () {
  40784. if (!_this.parent) {
  40785. return null;
  40786. }
  40787. return _this.parent.padding;
  40788. }, function () { return _this._positioningDirty(); });
  40789. }
  40790. return this._padding;
  40791. },
  40792. enumerable: true,
  40793. configurable: true
  40794. });
  40795. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  40796. get: function () {
  40797. return this._padding !== null;
  40798. },
  40799. enumerable: true,
  40800. configurable: true
  40801. });
  40802. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  40803. get: function () {
  40804. var _this = this;
  40805. if (!this._marginAlignment) {
  40806. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  40807. }
  40808. return this._marginAlignment;
  40809. },
  40810. enumerable: true,
  40811. configurable: true
  40812. });
  40813. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  40814. get: function () {
  40815. return this._opacity;
  40816. },
  40817. set: function (value) {
  40818. if (value < 0) {
  40819. value = 0;
  40820. }
  40821. else if (value > 1) {
  40822. value = 1;
  40823. }
  40824. if (this._opacity === value) {
  40825. return;
  40826. }
  40827. this._opacity = value;
  40828. this._updateRenderMode();
  40829. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40830. this._spreadActualOpacityChanged();
  40831. },
  40832. enumerable: true,
  40833. configurable: true
  40834. });
  40835. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  40836. get: function () {
  40837. return this._scale.x;
  40838. },
  40839. set: function (value) {
  40840. this._scale.x = value;
  40841. },
  40842. enumerable: true,
  40843. configurable: true
  40844. });
  40845. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  40846. get: function () {
  40847. return this._scale.y;
  40848. },
  40849. set: function (value) {
  40850. this._scale.y = value;
  40851. },
  40852. enumerable: true,
  40853. configurable: true
  40854. });
  40855. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  40856. get: function () {
  40857. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  40858. var cur = this.parent;
  40859. var op = this.opacity;
  40860. while (cur) {
  40861. op *= cur.opacity;
  40862. cur = cur.parent;
  40863. }
  40864. this._actualOpacity = op;
  40865. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40866. }
  40867. return this._actualOpacity;
  40868. },
  40869. enumerable: true,
  40870. configurable: true
  40871. });
  40872. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  40873. /**
  40874. * Get/set the layout engine to use for this primitive.
  40875. * The default layout engine is the CanvasLayoutEngine.
  40876. */
  40877. get: function () {
  40878. if (!this._layoutEngine) {
  40879. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40880. }
  40881. return this._layoutEngine;
  40882. },
  40883. set: function (value) {
  40884. if (this._layoutEngine === value) {
  40885. return;
  40886. }
  40887. this._changeLayoutEngine(value);
  40888. },
  40889. enumerable: true,
  40890. configurable: true
  40891. });
  40892. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  40893. /**
  40894. * Get/set the layout are of this primitive.
  40895. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  40896. * The setter should only be called by a Layout Engine class.
  40897. */
  40898. get: function () {
  40899. return this._layoutArea;
  40900. },
  40901. set: function (val) {
  40902. if (this._layoutArea.equals(val)) {
  40903. return;
  40904. }
  40905. this._positioningDirty();
  40906. this._layoutArea = val;
  40907. },
  40908. enumerable: true,
  40909. configurable: true
  40910. });
  40911. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  40912. /**
  40913. * Get/set the layout area position (relative to the parent primitive).
  40914. * The setter should only be called by a Layout Engine class.
  40915. */
  40916. get: function () {
  40917. return this._layoutAreaPos;
  40918. },
  40919. set: function (val) {
  40920. if (this._layoutAreaPos.equals(val)) {
  40921. return;
  40922. }
  40923. this._positioningDirty();
  40924. this._layoutAreaPos = val;
  40925. },
  40926. enumerable: true,
  40927. configurable: true
  40928. });
  40929. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  40930. /**
  40931. * Define if the Primitive can be subject to intersection test or not (default is true)
  40932. */
  40933. get: function () {
  40934. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  40935. },
  40936. set: function (value) {
  40937. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  40938. },
  40939. enumerable: true,
  40940. configurable: true
  40941. });
  40942. Object.defineProperty(Prim2DBase.prototype, "isContainer", {
  40943. /**
  40944. * Define if the Primitive acts as a container or not
  40945. * A container will encapsulate its children for interaction event.
  40946. * If it's not a container events will be process down to children if the primitive is not pickable.
  40947. * Default value is true
  40948. */
  40949. get: function () {
  40950. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
  40951. },
  40952. set: function (value) {
  40953. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
  40954. },
  40955. enumerable: true,
  40956. configurable: true
  40957. });
  40958. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  40959. /**
  40960. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  40961. */
  40962. get: function () {
  40963. return this._hierarchyDepth;
  40964. },
  40965. enumerable: true,
  40966. configurable: true
  40967. });
  40968. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  40969. /**
  40970. * Retrieve the Group that is responsible to render this primitive
  40971. */
  40972. get: function () {
  40973. return this._renderGroup;
  40974. },
  40975. enumerable: true,
  40976. configurable: true
  40977. });
  40978. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  40979. /**
  40980. * Get the global transformation matrix of the primitive
  40981. */
  40982. get: function () {
  40983. this._updateLocalTransform();
  40984. return this._globalTransform;
  40985. },
  40986. enumerable: true,
  40987. configurable: true
  40988. });
  40989. /**
  40990. * return the global position of the primitive, relative to its canvas
  40991. */
  40992. Prim2DBase.prototype.getGlobalPosition = function () {
  40993. var v = new BABYLON.Vector2(0, 0);
  40994. this.getGlobalPositionByRef(v);
  40995. return v;
  40996. };
  40997. /**
  40998. * return the global position of the primitive, relative to its canvas
  40999. * @param v the valid Vector2 object where the global position will be stored
  41000. */
  41001. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  41002. v.x = this.globalTransform.m[12];
  41003. v.y = this.globalTransform.m[13];
  41004. };
  41005. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  41006. /**
  41007. * Get invert of the global transformation matrix of the primitive
  41008. */
  41009. get: function () {
  41010. this._updateLocalTransform();
  41011. return this._invGlobalTransform;
  41012. },
  41013. enumerable: true,
  41014. configurable: true
  41015. });
  41016. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  41017. /**
  41018. * Get the local transformation of the primitive
  41019. */
  41020. get: function () {
  41021. this._updateLocalTransform();
  41022. return this._localTransform;
  41023. },
  41024. enumerable: true,
  41025. configurable: true
  41026. });
  41027. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  41028. /**
  41029. * Get the boundingInfo associated to the primitive and its children.
  41030. * The value is supposed to be always up to date
  41031. */
  41032. get: function () {
  41033. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  41034. if (this.owner) {
  41035. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  41036. }
  41037. if (this.isSizedByContent) {
  41038. this._boundingInfo.clear();
  41039. }
  41040. else {
  41041. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  41042. }
  41043. var bi = this._boundingInfo;
  41044. var tps = new BABYLON.BoundingInfo2D();
  41045. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41046. var curChild = _a[_i];
  41047. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  41048. bi.unionToRef(tps, bi);
  41049. }
  41050. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  41051. 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);
  41052. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  41053. }
  41054. return this._boundingInfo;
  41055. },
  41056. enumerable: true,
  41057. configurable: true
  41058. });
  41059. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  41060. /**
  41061. * Determine if the size is automatically computed or fixed because manually specified.
  41062. * Use the actualSize property to get the final/real size of the primitive
  41063. * @returns true if the size is automatically computed, false if it were manually specified.
  41064. */
  41065. get: function () {
  41066. return this._size == null;
  41067. },
  41068. enumerable: true,
  41069. configurable: true
  41070. });
  41071. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  41072. /**
  41073. * Return true if this prim has an auto size which is set by the children's global bounding box
  41074. */
  41075. get: function () {
  41076. return (this._size == null) && (this._children.length > 0);
  41077. },
  41078. enumerable: true,
  41079. configurable: true
  41080. });
  41081. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  41082. /**
  41083. * Determine if the position is automatically computed or fixed because manually specified.
  41084. * Use the actualPosition property to get the final/real position of the primitive
  41085. * @returns true if the position is automatically computed, false if it were manually specified.
  41086. */
  41087. get: function () {
  41088. return this._position == null;
  41089. },
  41090. enumerable: true,
  41091. configurable: true
  41092. });
  41093. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  41094. /**
  41095. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  41096. */
  41097. get: function () {
  41098. return this._pointerEventObservable;
  41099. },
  41100. enumerable: true,
  41101. configurable: true
  41102. });
  41103. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  41104. get: function () {
  41105. if (!this._actualZOrderChangedObservable) {
  41106. this._actualZOrderChangedObservable = new BABYLON.Observable();
  41107. }
  41108. return this._actualZOrderChangedObservable;
  41109. },
  41110. enumerable: true,
  41111. configurable: true
  41112. });
  41113. Prim2DBase.prototype.findById = function (id) {
  41114. if (this._id === id) {
  41115. return this;
  41116. }
  41117. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41118. var child = _a[_i];
  41119. var r = child.findById(id);
  41120. if (r != null) {
  41121. return r;
  41122. }
  41123. }
  41124. };
  41125. Prim2DBase.prototype.onZOrderChanged = function () {
  41126. };
  41127. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  41128. return false;
  41129. };
  41130. /**
  41131. * Capture all the Events of the given PointerId for this primitive.
  41132. * Don't forget to call releasePointerEventsCapture when done.
  41133. * @param pointerId the Id of the pointer to capture the events from.
  41134. */
  41135. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  41136. return this.owner._setPointerCapture(pointerId, this);
  41137. };
  41138. /**
  41139. * Release a captured pointer made with setPointerEventCapture.
  41140. * @param pointerId the Id of the pointer to release the capture from.
  41141. */
  41142. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  41143. return this.owner._releasePointerCapture(pointerId, this);
  41144. };
  41145. /**
  41146. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  41147. * @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.
  41148. */
  41149. Prim2DBase.prototype.intersect = function (intersectInfo) {
  41150. if (!intersectInfo) {
  41151. return false;
  41152. }
  41153. // If this is null it means this method is call for the first level, initialize stuffs
  41154. var firstLevel = !intersectInfo._globalPickPosition;
  41155. if (firstLevel) {
  41156. // 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).
  41157. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  41158. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  41159. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  41160. intersectInfo.intersectedPrimitives = new Array();
  41161. intersectInfo.topMostIntersectedPrimitive = null;
  41162. }
  41163. if (!intersectInfo.intersectHidden && !this.isVisible) {
  41164. return false;
  41165. }
  41166. var id = this.id;
  41167. if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  41168. var ownerGroup = this.getExternalData("__cachedGroup__");
  41169. return ownerGroup.intersect(intersectInfo);
  41170. }
  41171. // If we're testing a cachedGroup, we must reject pointer outside its levelBoundingInfo because children primitives could be partially clipped outside so we must not accept them as intersected when it's the case (because they're not visually visible).
  41172. var isIntersectionTest = false;
  41173. if (this instanceof BABYLON.Group2D) {
  41174. var g = this;
  41175. isIntersectionTest = g.isCachedGroup;
  41176. }
  41177. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  41178. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  41179. intersectInfo._exit(firstLevel);
  41180. return false;
  41181. }
  41182. // Fast rejection test with boundingInfo
  41183. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  41184. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  41185. intersectInfo._exit(firstLevel);
  41186. return false;
  41187. }
  41188. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  41189. var levelIntersectRes = false;
  41190. if (this.isPickable) {
  41191. levelIntersectRes = this.levelIntersect(intersectInfo);
  41192. if (levelIntersectRes) {
  41193. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  41194. intersectInfo.intersectedPrimitives.push(pii);
  41195. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  41196. intersectInfo.topMostIntersectedPrimitive = pii;
  41197. }
  41198. // If we must stop at the first intersection, we're done, quit!
  41199. if (intersectInfo.findFirstOnly) {
  41200. intersectInfo._exit(firstLevel);
  41201. return true;
  41202. }
  41203. }
  41204. }
  41205. // Recurse to children if needed
  41206. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  41207. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41208. var curChild = _a[_i];
  41209. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  41210. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  41211. continue;
  41212. }
  41213. // Must compute the localPickLocation for the children level
  41214. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  41215. // If we got an intersection with the child and we only need to find the first one, quit!
  41216. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  41217. intersectInfo._exit(firstLevel);
  41218. return true;
  41219. }
  41220. }
  41221. }
  41222. intersectInfo._exit(firstLevel);
  41223. return intersectInfo.isIntersected;
  41224. };
  41225. /**
  41226. * Move a child object into a new position regarding its siblings to change its rendering order.
  41227. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  41228. * @param child the object to move
  41229. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  41230. */
  41231. Prim2DBase.prototype.moveChild = function (child, previous) {
  41232. if (child.parent !== this) {
  41233. return false;
  41234. }
  41235. var childIndex = this._children.indexOf(child);
  41236. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  41237. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41238. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41239. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  41240. }
  41241. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  41242. return true;
  41243. };
  41244. /**
  41245. * Move the given child so it's displayed on the top of all its siblings
  41246. * @param child the primitive to move to the top
  41247. */
  41248. Prim2DBase.prototype.moveChildToTop = function (child) {
  41249. return this.moveChild(child, this._children[this._children.length - 1]);
  41250. };
  41251. /**
  41252. * Move the given child so it's displayed on the bottom of all its siblings
  41253. * @param child the primitive to move to the top
  41254. */
  41255. Prim2DBase.prototype.moveChildToBottom = function (child) {
  41256. return this.moveChild(child, null);
  41257. };
  41258. /**
  41259. * Move this primitive to be at the top among all its sibling
  41260. */
  41261. Prim2DBase.prototype.moveToTop = function () {
  41262. if (this.parent == null) {
  41263. return false;
  41264. }
  41265. return this.parent.moveChildToTop(this);
  41266. };
  41267. /**
  41268. * Move this primitive to be at the bottom among all its sibling
  41269. */
  41270. Prim2DBase.prototype.moveToBottom = function () {
  41271. if (this.parent == null) {
  41272. return false;
  41273. }
  41274. return this.parent.moveChildToBottom(this);
  41275. };
  41276. Prim2DBase.prototype.addChild = function (child) {
  41277. child._parent = this;
  41278. this._boundingBoxDirty();
  41279. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41280. if (flat) {
  41281. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41282. child._setZOrder(this._zOrder, true);
  41283. child._zMax = this._zOrder;
  41284. }
  41285. else {
  41286. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41287. }
  41288. var length = this._children.push(child);
  41289. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  41290. };
  41291. /**
  41292. * Dispose the primitive, remove it from its parent.
  41293. */
  41294. Prim2DBase.prototype.dispose = function () {
  41295. if (!_super.prototype.dispose.call(this)) {
  41296. return false;
  41297. }
  41298. if (this._actionManager) {
  41299. this._actionManager.dispose();
  41300. this._actionManager = null;
  41301. }
  41302. // If there's a parent, remove this object from its parent list
  41303. if (this._parent) {
  41304. if (this instanceof BABYLON.Group2D) {
  41305. var g = this;
  41306. if (g.isRenderableGroup) {
  41307. var parentRenderable = this.parent.traverseUp(function (p) { return (p instanceof BABYLON.Group2D && p.isRenderableGroup); });
  41308. if (parentRenderable != null) {
  41309. var l = parentRenderable._renderableData._childrenRenderableGroups;
  41310. var i_1 = l.indexOf(g);
  41311. if (i_1 !== -1) {
  41312. l.splice(i_1, 1);
  41313. }
  41314. }
  41315. }
  41316. }
  41317. var i = this._parent._children.indexOf(this);
  41318. if (i !== undefined) {
  41319. this._parent._children.splice(i, 1);
  41320. }
  41321. this._parent = null;
  41322. }
  41323. // Recurse dispose to children
  41324. if (this._children) {
  41325. while (this._children.length > 0) {
  41326. this._children[this._children.length - 1].dispose();
  41327. }
  41328. }
  41329. return true;
  41330. };
  41331. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  41332. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  41333. this._renderGroup._addPrimToDirtyList(this);
  41334. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  41335. }
  41336. };
  41337. Prim2DBase.prototype._needPrepare = function () {
  41338. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty | BABYLON.SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  41339. };
  41340. Prim2DBase.prototype._prepareRender = function (context) {
  41341. this._prepareRenderPre(context);
  41342. this._prepareRenderPost(context);
  41343. };
  41344. Prim2DBase.prototype._prepareRenderPre = function (context) {
  41345. };
  41346. Prim2DBase.prototype._prepareRenderPost = function (context) {
  41347. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  41348. if (this instanceof BABYLON.Group2D) {
  41349. var self = this;
  41350. if (self.isRenderableGroup) {
  41351. return;
  41352. }
  41353. }
  41354. // Check if we need to recurse the prepare to children primitives
  41355. // - must have children
  41356. // - the global transform of this level have changed, or
  41357. // - the visible state of primitive has changed
  41358. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  41359. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  41360. this._children.forEach(function (c) {
  41361. // As usual stop the recursion if we meet a renderable group
  41362. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  41363. c._prepareRender(context);
  41364. }
  41365. });
  41366. }
  41367. // Finally reset the dirty flags as we've processed everything
  41368. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  41369. this._instanceDirtyFlags = 0;
  41370. };
  41371. Prim2DBase.prototype._canvasPreInit = function (settings) {
  41372. };
  41373. Prim2DBase.CheckParent = function (parent) {
  41374. //if (!Prim2DBase._isCanvasInit && !parent) {
  41375. // 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)");
  41376. //}
  41377. };
  41378. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  41379. for (var _i = 0; _i < list.length; _i++) {
  41380. var cur = list[_i];
  41381. cur.updateCachedStates(recurse);
  41382. }
  41383. };
  41384. Prim2DBase.prototype._parentLayoutDirty = function () {
  41385. if (!this._parent || this._parent.isDisposed) {
  41386. return;
  41387. }
  41388. this._parent._setLayoutDirty();
  41389. };
  41390. Prim2DBase.prototype._setLayoutDirty = function () {
  41391. this.onPrimBecomesDirty();
  41392. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  41393. };
  41394. Prim2DBase.prototype._checkPositionChange = function () {
  41395. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  41396. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  41397. return false;
  41398. }
  41399. return true;
  41400. };
  41401. Prim2DBase.prototype._positioningDirty = function () {
  41402. this.onPrimBecomesDirty();
  41403. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41404. };
  41405. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  41406. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41407. var child = _a[_i];
  41408. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41409. child._spreadActualOpacityChanged();
  41410. }
  41411. };
  41412. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  41413. this._layoutEngine = engine;
  41414. };
  41415. Prim2DBase.prototype._updateLocalTransform = function () {
  41416. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.scaleXProperty.flagId | Prim2DBase.scaleYProperty.flagId | Prim2DBase.originProperty.flagId;
  41417. if (this.checkPropertiesDirty(tflags)) {
  41418. if (this.owner) {
  41419. this.owner.addupdateLocalTransformCounter(1);
  41420. }
  41421. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  41422. var local;
  41423. var pos = this.position;
  41424. if (this._origin.x === 0 && this._origin.y === 0) {
  41425. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale.x, this._scale.y, 1), rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  41426. this._localTransform = local;
  41427. }
  41428. else {
  41429. // -Origin offset
  41430. var as = this.actualSize;
  41431. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  41432. // -Origin * rotation
  41433. rot.toRotationMatrix(Prim2DBase._t1);
  41434. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  41435. // -Origin * rotation * scale
  41436. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase._t0);
  41437. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  41438. // -Origin * rotation * scale * (Origin + Position)
  41439. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  41440. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  41441. }
  41442. this.clearPropertiesDirty(tflags);
  41443. return true;
  41444. }
  41445. return false;
  41446. };
  41447. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  41448. if (this.isDisposed) {
  41449. return;
  41450. }
  41451. this.owner.addCachedGroupRenderCounter(1);
  41452. // Check if the parent is synced
  41453. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  41454. this._parent.updateCachedStates(false);
  41455. }
  41456. // Update Z-Order if needed
  41457. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41458. this._updateZOrder();
  41459. }
  41460. // Update actualSize only if there' not positioning to recompute and the size changed
  41461. // Otherwise positioning will take care of it.
  41462. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41463. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  41464. var size = this.size;
  41465. if (size) {
  41466. if (this.size.width != null) {
  41467. this.actualSize.width = this.size.width;
  41468. }
  41469. if (this.size.height != null) {
  41470. this.actualSize.height = this.size.height;
  41471. }
  41472. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41473. }
  41474. }
  41475. // Check for layout update
  41476. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41477. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  41478. this.owner.addUpdateLayoutCounter(1);
  41479. this._layoutEngine.updateLayout(this);
  41480. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  41481. }
  41482. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41483. var autoContentChanged = false;
  41484. if (this.isSizeAuto) {
  41485. if (!this._lastAutoSizeArea) {
  41486. autoContentChanged = this.size !== null;
  41487. }
  41488. else {
  41489. autoContentChanged = (!this._lastAutoSizeArea.equals(this.size));
  41490. }
  41491. }
  41492. // Check for positioning update
  41493. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  41494. this._updatePositioning();
  41495. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41496. if (sizeDirty) {
  41497. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41498. }
  41499. positioningComputed = true;
  41500. }
  41501. if (positioningComputed && this._parent) {
  41502. this._parentContentArea.copyFrom(this._parent.contentArea);
  41503. }
  41504. // Check if we must update this prim
  41505. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  41506. this.owner.addUpdateGlobalTransformCounter(1);
  41507. var curVisibleState = this.isVisible;
  41508. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  41509. // Detect a change of visibility
  41510. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  41511. // Get/compute the localTransform
  41512. var localDirty = this._updateLocalTransform();
  41513. var parentPaddingChanged = false;
  41514. var parentPaddingOffset = Prim2DBase._v0;
  41515. if (this._parent) {
  41516. parentPaddingOffset = this._parent._paddingOffset;
  41517. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  41518. }
  41519. // Check if there are changes in the parent that will force us to update the global matrix
  41520. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  41521. // Check if we have to update the globalTransform
  41522. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged) {
  41523. var globalTransform = this._parent ? this._parent._globalTransform : null;
  41524. var localTransform;
  41525. Prim2DBase._transMtx.copyFrom(this._localTransform);
  41526. Prim2DBase._transMtx.m[12] += this._layoutAreaPos.x + this._marginOffset.x + parentPaddingOffset.x;
  41527. Prim2DBase._transMtx.m[13] += this._layoutAreaPos.y + this._marginOffset.y + parentPaddingOffset.y;
  41528. localTransform = Prim2DBase._transMtx;
  41529. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  41530. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  41531. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  41532. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  41533. }
  41534. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  41535. }
  41536. if (recurse) {
  41537. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41538. var child = _a[_i];
  41539. // Stop the recursion if we meet a renderable group
  41540. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  41541. }
  41542. }
  41543. };
  41544. Prim2DBase.prototype._updatePositioning = function () {
  41545. if (this.owner) {
  41546. this.owner.addUpdatePositioningCounter(1);
  41547. }
  41548. // From this point we assume that the primitive layoutArea is computed and up to date.
  41549. // We know have to :
  41550. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  41551. // 2. Determine the contentArea based on the padding property.
  41552. // 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
  41553. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  41554. if (this.actualSize.width == null) {
  41555. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  41556. }
  41557. if (this.actualSize.height == null) {
  41558. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  41559. }
  41560. }
  41561. // Apply margin
  41562. if (this._hasMargin) {
  41563. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  41564. this.actualSize = Prim2DBase._size.clone();
  41565. }
  41566. var isSizeAuto = this.isSizeAuto;
  41567. if (this._hasPadding) {
  41568. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  41569. if (isSizeAuto) {
  41570. var content = this.size.clone();
  41571. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  41572. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  41573. this._contentArea.copyFrom(content);
  41574. this.actualSize = Prim2DBase._size.clone();
  41575. // Changing the padding has resize the prim, which forces us to recompute margin again
  41576. if (this._hasMargin) {
  41577. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  41578. }
  41579. }
  41580. else {
  41581. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  41582. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  41583. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  41584. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  41585. this._paddingOffset.x += Prim2DBase._icPos.x;
  41586. this._paddingOffset.y += Prim2DBase._icPos.y;
  41587. this._contentArea.copyFrom(Prim2DBase._size);
  41588. }
  41589. }
  41590. else {
  41591. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  41592. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  41593. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  41594. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  41595. this._contentArea.copyFrom(Prim2DBase._icArea);
  41596. }
  41597. if (!this._position) {
  41598. var aPos = new BABYLON.Vector2(this._layoutAreaPos.x + this._marginOffset.x, this._layoutAreaPos.y + this._marginOffset.y);
  41599. this.actualPosition = aPos;
  41600. }
  41601. if (isSizeAuto) {
  41602. this._lastAutoSizeArea = this.size;
  41603. }
  41604. };
  41605. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  41606. /**
  41607. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  41608. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  41609. */
  41610. get: function () {
  41611. // Check for positioning update
  41612. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  41613. this._updatePositioning();
  41614. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41615. }
  41616. return this._contentArea;
  41617. },
  41618. enumerable: true,
  41619. configurable: true
  41620. });
  41621. Prim2DBase.prototype._patchHierarchy = function (owner) {
  41622. this._owner = owner;
  41623. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  41624. if (this._renderGroup != null) {
  41625. return;
  41626. }
  41627. if (this instanceof BABYLON.Group2D) {
  41628. var group = this;
  41629. group.detectGroupStates();
  41630. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  41631. group.owner._registerTrackedNode(this);
  41632. }
  41633. }
  41634. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  41635. if (this._parent) {
  41636. this._parentLayoutDirty();
  41637. }
  41638. // Make sure the prim is in the dirtyList if it should be
  41639. if (this._renderGroup && this.isDirty) {
  41640. var list = this._renderGroup._renderableData._primDirtyList;
  41641. var i = list.indexOf(this);
  41642. if (i === -1) {
  41643. list.push(this);
  41644. }
  41645. }
  41646. // Recurse
  41647. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41648. var child = _a[_i];
  41649. child._hierarchyDepth = this._hierarchyDepth + 1;
  41650. child._patchHierarchy(owner);
  41651. }
  41652. };
  41653. Prim2DBase.prototype._updateZOrder = function () {
  41654. var prevLinPos = this._primLinearPosition;
  41655. var startI = 0;
  41656. var startZ = this._zOrder;
  41657. // 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
  41658. var childrenCount = this._children.length;
  41659. if (this._firstZDirtyIndex > 0) {
  41660. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  41661. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  41662. prevLinPos = prevPrim._primLinearPosition;
  41663. startI = this._firstZDirtyIndex - 1;
  41664. startZ = prevPrim._zOrder;
  41665. }
  41666. }
  41667. var startPos = prevLinPos;
  41668. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  41669. Prim2DBase._totalCount = 0;
  41670. for (var i = startI; i < childrenCount; i++) {
  41671. var child = this._children[i];
  41672. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  41673. }
  41674. // Compute the new Z-Order for all the primitives
  41675. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  41676. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  41677. // 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.
  41678. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  41679. // 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...
  41680. if (Prim2DBase._zRebuildReentrency) {
  41681. var p = this._parent;
  41682. if (p == null) {
  41683. // 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...)
  41684. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  41685. Prim2DBase._zRebuildReentrency = false;
  41686. return;
  41687. }
  41688. p._firstZDirtyIndex = 0;
  41689. return p._updateZOrder();
  41690. }
  41691. Prim2DBase._zRebuildReentrency = true;
  41692. this._firstZDirtyIndex = 0;
  41693. this._updateZOrder();
  41694. Prim2DBase._zRebuildReentrency = false;
  41695. }
  41696. for (var i = startI; i < childrenCount; i++) {
  41697. var child = this._children[i];
  41698. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  41699. }
  41700. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  41701. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  41702. var p = _a[_i];
  41703. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  41704. }
  41705. Prim2DBase._zOrderChangedNotifList.splice(0);
  41706. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41707. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41708. };
  41709. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  41710. if (this.isManualZOrder) {
  41711. return prevLinPos;
  41712. }
  41713. this._primLinearPosition = ++prevLinPos;
  41714. Prim2DBase._totalCount++;
  41715. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  41716. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41717. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41718. var child = _a[_i];
  41719. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  41720. }
  41721. }
  41722. return prevLinPos;
  41723. };
  41724. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  41725. if (this.isManualZOrder) {
  41726. return null;
  41727. }
  41728. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  41729. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41730. this._setZOrder(newZ, false);
  41731. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41732. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41733. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41734. }
  41735. var curZ = newZ;
  41736. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  41737. if (isFlat) {
  41738. if (this._children.length > 0) {
  41739. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  41740. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41741. var child = _a[_i];
  41742. child._updatePrimitiveFlatZOrder(this._zOrder);
  41743. }
  41744. }
  41745. }
  41746. else {
  41747. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  41748. var child = _c[_b];
  41749. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  41750. if (r != null) {
  41751. curZ = r;
  41752. }
  41753. }
  41754. }
  41755. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  41756. return curZ;
  41757. };
  41758. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  41759. if (this.isManualZOrder) {
  41760. return;
  41761. }
  41762. this._setZOrder(newZ, false);
  41763. this._zMax = newZ;
  41764. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41765. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41766. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41767. }
  41768. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41769. var child = _a[_i];
  41770. child._updatePrimitiveFlatZOrder(newZ);
  41771. }
  41772. };
  41773. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  41774. if (newZ !== this._zOrder) {
  41775. this._zOrder = newZ;
  41776. this.onPrimBecomesDirty();
  41777. this.onZOrderChanged();
  41778. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  41779. if (directEmit) {
  41780. this._actualZOrderChangedObservable.notifyObservers(newZ);
  41781. }
  41782. else {
  41783. Prim2DBase._zOrderChangedNotifList.push(this);
  41784. }
  41785. }
  41786. }
  41787. };
  41788. Prim2DBase.prototype._updateRenderMode = function () {
  41789. };
  41790. /**
  41791. * This method is used to alter the contentArea of the Primitive before margin is applied.
  41792. * 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.
  41793. * @param primSize the current size of the primitive
  41794. * @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!
  41795. * @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!
  41796. */
  41797. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  41798. initialContentArea.copyFrom(primSize);
  41799. initialContentPosition.x = initialContentPosition.y = 0;
  41800. };
  41801. /**
  41802. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  41803. * Check the Rectangle2D implementation for a concrete application.
  41804. * @param primSize the current size of the primitive
  41805. * @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!
  41806. */
  41807. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  41808. newPrimSize.copyFrom(primSize);
  41809. };
  41810. Prim2DBase.PRIM2DBASE_PROPCOUNT = 16;
  41811. Prim2DBase._bigInt = Math.pow(2, 30);
  41812. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  41813. Prim2DBase.boundinbBoxReentrency = false;
  41814. Prim2DBase.nullSize = BABYLON.Size.Zero();
  41815. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  41816. Prim2DBase._isCanvasInit = false;
  41817. Prim2DBase._t0 = new BABYLON.Matrix();
  41818. Prim2DBase._t1 = new BABYLON.Matrix();
  41819. Prim2DBase._t2 = new BABYLON.Matrix();
  41820. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  41821. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  41822. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  41823. Prim2DBase._icArea = BABYLON.Size.Zero();
  41824. Prim2DBase._size = BABYLON.Size.Zero();
  41825. Prim2DBase._zOrderChangedNotifList = new Array();
  41826. Prim2DBase._zRebuildReentrency = false;
  41827. Prim2DBase._totalCount = 0;
  41828. __decorate([
  41829. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  41830. ], Prim2DBase.prototype, "actualPosition", null);
  41831. __decorate([
  41832. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  41833. ], Prim2DBase.prototype, "position", null);
  41834. __decorate([
  41835. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  41836. ], Prim2DBase.prototype, "size", null);
  41837. __decorate([
  41838. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  41839. ], Prim2DBase.prototype, "rotation", null);
  41840. __decorate([
  41841. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  41842. ], Prim2DBase.prototype, "scale", null);
  41843. __decorate([
  41844. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  41845. ], Prim2DBase.prototype, "origin", null);
  41846. __decorate([
  41847. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  41848. ], Prim2DBase.prototype, "levelVisible", null);
  41849. __decorate([
  41850. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  41851. ], Prim2DBase.prototype, "isVisible", null);
  41852. __decorate([
  41853. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  41854. ], Prim2DBase.prototype, "zOrder", null);
  41855. __decorate([
  41856. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  41857. ], Prim2DBase.prototype, "margin", null);
  41858. __decorate([
  41859. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  41860. ], Prim2DBase.prototype, "padding", null);
  41861. __decorate([
  41862. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  41863. ], Prim2DBase.prototype, "marginAlignment", null);
  41864. __decorate([
  41865. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  41866. ], Prim2DBase.prototype, "opacity", null);
  41867. __decorate([
  41868. BABYLON.instanceLevelProperty(14, function (pi) { return Prim2DBase.scaleXProperty = pi; }, false, true)
  41869. ], Prim2DBase.prototype, "scaleX", null);
  41870. __decorate([
  41871. BABYLON.instanceLevelProperty(15, function (pi) { return Prim2DBase.scaleYProperty = pi; }, false, true)
  41872. ], Prim2DBase.prototype, "scaleY", null);
  41873. Prim2DBase = __decorate([
  41874. BABYLON.className("Prim2DBase")
  41875. ], Prim2DBase);
  41876. return Prim2DBase;
  41877. })(BABYLON.SmartPropertyPrim);
  41878. BABYLON.Prim2DBase = Prim2DBase;
  41879. })(BABYLON || (BABYLON = {}));
  41880. var BABYLON;
  41881. (function (BABYLON) {
  41882. var GroupInstanceInfo = (function () {
  41883. function GroupInstanceInfo(owner, mrc, partCount) {
  41884. this._partCount = partCount;
  41885. this.owner = owner;
  41886. this.modelRenderCache = mrc;
  41887. this.modelRenderCache.addRef();
  41888. this.partIndexFromId = new BABYLON.StringDictionary();
  41889. this._usedShaderCategories = new Array(partCount);
  41890. this._strides = new Array(partCount);
  41891. this._opaqueData = null;
  41892. this._alphaTestData = null;
  41893. this._transparentData = null;
  41894. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  41895. }
  41896. GroupInstanceInfo.prototype.dispose = function () {
  41897. if (this._isDisposed) {
  41898. return false;
  41899. }
  41900. if (this.modelRenderCache) {
  41901. this.modelRenderCache.dispose();
  41902. this.modelRenderCache = null;
  41903. }
  41904. var engine = this.owner.owner.engine;
  41905. if (this._opaqueData) {
  41906. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  41907. this._opaqueData = null;
  41908. }
  41909. if (this._alphaTestData) {
  41910. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  41911. this._alphaTestData = null;
  41912. }
  41913. if (this._transparentData) {
  41914. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  41915. this._transparentData = null;
  41916. }
  41917. this.partIndexFromId = null;
  41918. this._isDisposed = true;
  41919. return true;
  41920. };
  41921. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  41922. get: function () {
  41923. return this._opaqueData != null;
  41924. },
  41925. enumerable: true,
  41926. configurable: true
  41927. });
  41928. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  41929. get: function () {
  41930. return this._alphaTestData != null;
  41931. },
  41932. enumerable: true,
  41933. configurable: true
  41934. });
  41935. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  41936. get: function () {
  41937. return this._transparentData != null;
  41938. },
  41939. enumerable: true,
  41940. configurable: true
  41941. });
  41942. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  41943. get: function () {
  41944. if (!this._opaqueData) {
  41945. this._opaqueData = new Array(this._partCount);
  41946. for (var i = 0; i < this._partCount; i++) {
  41947. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  41948. }
  41949. }
  41950. return this._opaqueData;
  41951. },
  41952. enumerable: true,
  41953. configurable: true
  41954. });
  41955. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  41956. get: function () {
  41957. if (!this._alphaTestData) {
  41958. this._alphaTestData = new Array(this._partCount);
  41959. for (var i = 0; i < this._partCount; i++) {
  41960. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  41961. }
  41962. }
  41963. return this._alphaTestData;
  41964. },
  41965. enumerable: true,
  41966. configurable: true
  41967. });
  41968. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  41969. get: function () {
  41970. if (!this._transparentData) {
  41971. this._transparentData = new Array(this._partCount);
  41972. for (var i = 0; i < this._partCount; i++) {
  41973. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  41974. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  41975. }
  41976. }
  41977. return this._transparentData;
  41978. },
  41979. enumerable: true,
  41980. configurable: true
  41981. });
  41982. GroupInstanceInfo.prototype.sortTransparentData = function () {
  41983. if (!this.transparentOrderDirty) {
  41984. return;
  41985. }
  41986. for (var i = 0; i < this._transparentData.length; i++) {
  41987. var td = this._transparentData[i];
  41988. td._partData.sort();
  41989. }
  41990. this.transparentOrderDirty = false;
  41991. };
  41992. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  41993. get: function () {
  41994. return this._usedShaderCategories;
  41995. },
  41996. enumerable: true,
  41997. configurable: true
  41998. });
  41999. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  42000. get: function () {
  42001. return this._strides;
  42002. },
  42003. enumerable: true,
  42004. configurable: true
  42005. });
  42006. return GroupInstanceInfo;
  42007. })();
  42008. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  42009. var TransparentSegment = (function () {
  42010. function TransparentSegment() {
  42011. this.groupInsanceInfo = null;
  42012. this.startZ = 0;
  42013. this.endZ = 0;
  42014. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  42015. this.endDataIndex = 0;
  42016. this.partBuffers = null;
  42017. }
  42018. TransparentSegment.prototype.dispose = function (engine) {
  42019. if (this.partBuffers) {
  42020. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  42021. this.partBuffers.splice(0);
  42022. this.partBuffers = null;
  42023. }
  42024. };
  42025. return TransparentSegment;
  42026. })();
  42027. BABYLON.TransparentSegment = TransparentSegment;
  42028. var GroupInfoPartData = (function () {
  42029. function GroupInfoPartData(stride) {
  42030. this._partData = null;
  42031. this._partBuffer = null;
  42032. this._partBufferSize = 0;
  42033. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  42034. this._isDisposed = false;
  42035. }
  42036. GroupInfoPartData.prototype.dispose = function (engine) {
  42037. if (this._isDisposed) {
  42038. return false;
  42039. }
  42040. if (this._partBuffer) {
  42041. engine._releaseBuffer(this._partBuffer);
  42042. this._partBuffer = null;
  42043. }
  42044. this._partData = null;
  42045. this._isDisposed = true;
  42046. };
  42047. return GroupInfoPartData;
  42048. })();
  42049. BABYLON.GroupInfoPartData = GroupInfoPartData;
  42050. var TransparentGroupInfoPartData = (function (_super) {
  42051. __extends(TransparentGroupInfoPartData, _super);
  42052. function TransparentGroupInfoPartData(stride, zoff) {
  42053. _super.call(this, stride);
  42054. this._partData.compareValueOffset = zoff;
  42055. this._partData.sortingAscending = false;
  42056. }
  42057. return TransparentGroupInfoPartData;
  42058. })(GroupInfoPartData);
  42059. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  42060. var ModelRenderCache = (function () {
  42061. function ModelRenderCache(engine, modelKey) {
  42062. this._engine = engine;
  42063. this._modelKey = modelKey;
  42064. this._nextKey = 1;
  42065. this._refCounter = 1;
  42066. this._partData = null;
  42067. }
  42068. ModelRenderCache.prototype.dispose = function () {
  42069. if (--this._refCounter !== 0) {
  42070. return false;
  42071. }
  42072. // Remove the Model Render Cache from the global dictionary
  42073. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  42074. if (edata) {
  42075. edata.DisposeModelRenderCache(this);
  42076. }
  42077. return true;
  42078. };
  42079. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  42080. get: function () {
  42081. return this._refCounter <= 0;
  42082. },
  42083. enumerable: true,
  42084. configurable: true
  42085. });
  42086. ModelRenderCache.prototype.addRef = function () {
  42087. return ++this._refCounter;
  42088. };
  42089. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  42090. get: function () {
  42091. return this._modelKey;
  42092. },
  42093. enumerable: true,
  42094. configurable: true
  42095. });
  42096. /**
  42097. * Render the model instances
  42098. * @param instanceInfo
  42099. * @param context
  42100. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  42101. */
  42102. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  42103. return true;
  42104. };
  42105. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  42106. for (var i = 0; i < this._partData.length; i++) {
  42107. if (this._partData[i]._partId === partId) {
  42108. return i;
  42109. }
  42110. }
  42111. return null;
  42112. };
  42113. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  42114. var i = this.getPartIndexFromId(partId);
  42115. if (i === null) {
  42116. return null;
  42117. }
  42118. var ci = this._partsClassInfo[i];
  42119. var categories = this._partData[i]._partUsedCategories;
  42120. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  42121. return res;
  42122. };
  42123. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  42124. var pd = this._partData[partIndex];
  42125. var offset = (pd._partDataStride / 4) * elementCount;
  42126. var pci = this._partsClassInfo[partIndex];
  42127. var self = this;
  42128. pci.fullContent.forEach(function (k, v) {
  42129. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  42130. switch (v.dataType) {
  42131. case 4 /* float */:
  42132. {
  42133. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42134. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  42135. break;
  42136. }
  42137. case 0 /* Vector2 */:
  42138. {
  42139. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42140. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  42141. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  42142. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  42143. break;
  42144. }
  42145. case 5 /* Color3 */:
  42146. case 1 /* Vector3 */:
  42147. {
  42148. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42149. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  42150. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  42151. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  42152. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  42153. break;
  42154. }
  42155. case 6 /* Color4 */:
  42156. case 2 /* Vector4 */:
  42157. {
  42158. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42159. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  42160. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  42161. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  42162. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  42163. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  42164. break;
  42165. }
  42166. default:
  42167. }
  42168. }
  42169. });
  42170. };
  42171. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  42172. // let i = this.getPartIndexFromId(partId);
  42173. // if (i === null) {
  42174. // return null;
  42175. // }
  42176. // let pci = this._partsClassInfo[i];
  42177. // pci.fullContent.forEach((k, v) => {
  42178. // if (uniforms.indexOf(v.attributeName) !== -1) {
  42179. // v.uniformLocation = effect.getUniform(v.attributeName);
  42180. // }
  42181. // });
  42182. //}
  42183. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  42184. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  42185. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  42186. return ModelRenderCache;
  42187. })();
  42188. BABYLON.ModelRenderCache = ModelRenderCache;
  42189. var ModelRenderCachePartData = (function () {
  42190. function ModelRenderCachePartData() {
  42191. }
  42192. return ModelRenderCachePartData;
  42193. })();
  42194. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  42195. })(BABYLON || (BABYLON = {}));
  42196. var BABYLON;
  42197. (function (BABYLON) {
  42198. var InstanceClassInfo = (function () {
  42199. function InstanceClassInfo(base) {
  42200. this._baseInfo = base;
  42201. this._nextOffset = new BABYLON.StringDictionary();
  42202. this._attributes = new Array();
  42203. }
  42204. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  42205. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  42206. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  42207. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  42208. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  42209. if (push) {
  42210. this._attributes.push(propInfo);
  42211. }
  42212. };
  42213. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  42214. var catInline = ";" + categories.join(";") + ";";
  42215. var res = new Array();
  42216. var curInfo = this;
  42217. while (curInfo) {
  42218. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  42219. var attrib = _a[_i];
  42220. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  42221. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  42222. var index = effect.getAttributeLocationByName(attrib.attributeName);
  42223. var iai = new BABYLON.InstancingAttributeInfo();
  42224. iai.index = index;
  42225. 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)
  42226. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  42227. iai.attributeName = attrib.attributeName;
  42228. res.push(iai);
  42229. }
  42230. }
  42231. curInfo = curInfo._baseInfo;
  42232. }
  42233. return res;
  42234. };
  42235. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  42236. var res = new Array();
  42237. var curInfo = this;
  42238. while (curInfo) {
  42239. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  42240. var attrib = _a[_i];
  42241. // 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
  42242. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  42243. res.push(attrib.attributeName);
  42244. }
  42245. }
  42246. curInfo = curInfo._baseInfo;
  42247. }
  42248. return res;
  42249. };
  42250. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  42251. var curOffset = 0;
  42252. var curBase = this._baseInfo;
  42253. while (curBase) {
  42254. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  42255. curBase = curBase._baseInfo;
  42256. }
  42257. return curOffset;
  42258. };
  42259. return InstanceClassInfo;
  42260. })();
  42261. BABYLON.InstanceClassInfo = InstanceClassInfo;
  42262. var InstancePropInfo = (function () {
  42263. function InstancePropInfo() {
  42264. this.instanceOffset = new BABYLON.StringDictionary();
  42265. }
  42266. InstancePropInfo.prototype.setSize = function (val) {
  42267. if (val instanceof BABYLON.Vector2) {
  42268. this.size = 8;
  42269. this.dataType = 0 /* Vector2 */;
  42270. return;
  42271. }
  42272. if (val instanceof BABYLON.Vector3) {
  42273. this.size = 12;
  42274. this.dataType = 1 /* Vector3 */;
  42275. return;
  42276. }
  42277. if (val instanceof BABYLON.Vector4) {
  42278. this.size = 16;
  42279. this.dataType = 2 /* Vector4 */;
  42280. return;
  42281. }
  42282. if (val instanceof BABYLON.Matrix) {
  42283. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  42284. }
  42285. if (typeof (val) === "number") {
  42286. this.size = 4;
  42287. this.dataType = 4 /* float */;
  42288. return;
  42289. }
  42290. if (val instanceof BABYLON.Color3) {
  42291. this.size = 12;
  42292. this.dataType = 5 /* Color3 */;
  42293. return;
  42294. }
  42295. if (val instanceof BABYLON.Color4) {
  42296. this.size = 16;
  42297. this.dataType = 6 /* Color4 */;
  42298. return;
  42299. }
  42300. if (val instanceof BABYLON.Size) {
  42301. this.size = 8;
  42302. this.dataType = 7 /* Size */;
  42303. return;
  42304. }
  42305. return;
  42306. };
  42307. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  42308. switch (this.dataType) {
  42309. case 0 /* Vector2 */:
  42310. {
  42311. var v = val;
  42312. array[offset + 0] = v.x;
  42313. array[offset + 1] = v.y;
  42314. break;
  42315. }
  42316. case 1 /* Vector3 */:
  42317. {
  42318. var v = val;
  42319. array[offset + 0] = v.x;
  42320. array[offset + 1] = v.y;
  42321. array[offset + 2] = v.z;
  42322. break;
  42323. }
  42324. case 2 /* Vector4 */:
  42325. {
  42326. var v = val;
  42327. array[offset + 0] = v.x;
  42328. array[offset + 1] = v.y;
  42329. array[offset + 2] = v.z;
  42330. array[offset + 3] = v.w;
  42331. break;
  42332. }
  42333. case 5 /* Color3 */:
  42334. {
  42335. var v = val;
  42336. array[offset + 0] = v.r;
  42337. array[offset + 1] = v.g;
  42338. array[offset + 2] = v.b;
  42339. break;
  42340. }
  42341. case 6 /* Color4 */:
  42342. {
  42343. var v = val;
  42344. array[offset + 0] = v.r;
  42345. array[offset + 1] = v.g;
  42346. array[offset + 2] = v.b;
  42347. array[offset + 3] = v.a;
  42348. break;
  42349. }
  42350. case 4 /* float */:
  42351. {
  42352. var v = val;
  42353. array[offset] = v;
  42354. break;
  42355. }
  42356. case 3 /* Matrix */:
  42357. {
  42358. var v = val;
  42359. for (var i = 0; i < 16; i++) {
  42360. array[offset + i] = v.m[i];
  42361. }
  42362. break;
  42363. }
  42364. case 7 /* Size */:
  42365. {
  42366. var s = val;
  42367. array[offset + 0] = s.width;
  42368. array[offset + 1] = s.height;
  42369. break;
  42370. }
  42371. }
  42372. };
  42373. return InstancePropInfo;
  42374. })();
  42375. BABYLON.InstancePropInfo = InstancePropInfo;
  42376. function instanceData(category, shaderAttributeName) {
  42377. return function (target, propName, descriptor) {
  42378. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  42379. var node = dic.getLevelOf(target);
  42380. var instanceDataName = propName;
  42381. shaderAttributeName = shaderAttributeName || instanceDataName;
  42382. var info = node.levelContent.get(instanceDataName);
  42383. if (info) {
  42384. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  42385. }
  42386. info = new InstancePropInfo();
  42387. info.attributeName = shaderAttributeName;
  42388. info.category = category || null;
  42389. if (info.category) {
  42390. info.delimitedCategory = ";" + info.category + ";";
  42391. }
  42392. node.levelContent.add(instanceDataName, info);
  42393. descriptor.get = function () {
  42394. return null;
  42395. };
  42396. descriptor.set = function (val) {
  42397. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  42398. // Quit if it's the case, otherwise we could overwrite data somewhere...
  42399. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  42400. return;
  42401. }
  42402. if (!info.size) {
  42403. info.setSize(val);
  42404. node.classContent.mapProperty(info, true);
  42405. }
  42406. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  42407. node.classContent.mapProperty(info, false);
  42408. }
  42409. var obj = this;
  42410. if (obj.dataBuffer && obj.dataElements) {
  42411. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  42412. info.writeData(obj.dataBuffer.buffer, offset, val);
  42413. }
  42414. };
  42415. };
  42416. }
  42417. BABYLON.instanceData = instanceData;
  42418. var InstanceDataBase = (function () {
  42419. function InstanceDataBase(partId, dataElementCount) {
  42420. this.id = partId;
  42421. this.curElement = 0;
  42422. this._dataElementCount = dataElementCount;
  42423. this.renderMode = 0;
  42424. this.arrayLengthChanged = false;
  42425. }
  42426. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  42427. get: function () {
  42428. return null;
  42429. },
  42430. enumerable: true,
  42431. configurable: true
  42432. });
  42433. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  42434. get: function () {
  42435. return null;
  42436. },
  42437. enumerable: true,
  42438. configurable: true
  42439. });
  42440. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  42441. get: function () {
  42442. return null;
  42443. },
  42444. enumerable: true,
  42445. configurable: true
  42446. });
  42447. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  42448. get: function () {
  42449. return null;
  42450. },
  42451. enumerable: true,
  42452. configurable: true
  42453. });
  42454. InstanceDataBase.prototype.getClassTreeInfo = function () {
  42455. if (!this.typeInfo) {
  42456. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  42457. }
  42458. return this.typeInfo;
  42459. };
  42460. InstanceDataBase.prototype.allocElements = function () {
  42461. if (!this.dataBuffer || this.dataElements) {
  42462. return;
  42463. }
  42464. var res = new Array(this.dataElementCount);
  42465. for (var i = 0; i < this.dataElementCount; i++) {
  42466. res[i] = this.dataBuffer.allocElement();
  42467. }
  42468. this.dataElements = res;
  42469. };
  42470. InstanceDataBase.prototype.freeElements = function () {
  42471. if (!this.dataElements) {
  42472. return;
  42473. }
  42474. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  42475. var ei = _a[_i];
  42476. this.dataBuffer.freeElement(ei);
  42477. }
  42478. this.dataElements = null;
  42479. };
  42480. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  42481. get: function () {
  42482. return this._dataElementCount;
  42483. },
  42484. set: function (value) {
  42485. if (value === this._dataElementCount) {
  42486. return;
  42487. }
  42488. this.arrayLengthChanged = true;
  42489. this.freeElements();
  42490. this._dataElementCount = value;
  42491. this.allocElements();
  42492. },
  42493. enumerable: true,
  42494. configurable: true
  42495. });
  42496. __decorate([
  42497. instanceData()
  42498. ], InstanceDataBase.prototype, "zBias", null);
  42499. __decorate([
  42500. instanceData()
  42501. ], InstanceDataBase.prototype, "transformX", null);
  42502. __decorate([
  42503. instanceData()
  42504. ], InstanceDataBase.prototype, "transformY", null);
  42505. __decorate([
  42506. instanceData()
  42507. ], InstanceDataBase.prototype, "opacity", null);
  42508. return InstanceDataBase;
  42509. })();
  42510. BABYLON.InstanceDataBase = InstanceDataBase;
  42511. var RenderablePrim2D = (function (_super) {
  42512. __extends(RenderablePrim2D, _super);
  42513. function RenderablePrim2D(settings) {
  42514. _super.call(this, settings);
  42515. this._transparentPrimitiveInfo = null;
  42516. }
  42517. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  42518. get: function () {
  42519. return this._useTextureAlpha() || this._isPrimAlphaTest();
  42520. },
  42521. enumerable: true,
  42522. configurable: true
  42523. });
  42524. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  42525. get: function () {
  42526. return (this._opacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  42527. },
  42528. enumerable: true,
  42529. configurable: true
  42530. });
  42531. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  42532. get: function () {
  42533. return this._renderMode;
  42534. },
  42535. enumerable: true,
  42536. configurable: true
  42537. });
  42538. /**
  42539. * Dispose the primitive and its resources, remove it from its parent
  42540. */
  42541. RenderablePrim2D.prototype.dispose = function () {
  42542. if (!_super.prototype.dispose.call(this)) {
  42543. return false;
  42544. }
  42545. if (this.renderGroup) {
  42546. this.renderGroup._setCacheGroupDirty();
  42547. }
  42548. if (this._transparentPrimitiveInfo) {
  42549. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  42550. this._transparentPrimitiveInfo = null;
  42551. }
  42552. if (this._instanceDataParts) {
  42553. this._cleanupInstanceDataParts();
  42554. }
  42555. if (this._modelRenderCache) {
  42556. this._modelRenderCache.dispose();
  42557. this._modelRenderCache = null;
  42558. }
  42559. if (this._instanceDataParts) {
  42560. this._instanceDataParts.forEach(function (p) {
  42561. p.freeElements();
  42562. });
  42563. this._instanceDataParts = null;
  42564. }
  42565. return true;
  42566. };
  42567. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  42568. var gii = null;
  42569. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42570. var part = _a[_i];
  42571. part.freeElements();
  42572. gii = part.groupInstanceInfo;
  42573. }
  42574. if (gii) {
  42575. var usedCount = 0;
  42576. if (gii.hasOpaqueData) {
  42577. var od = gii.opaqueData[0];
  42578. usedCount += od._partData.usedElementCount;
  42579. }
  42580. if (gii.hasAlphaTestData) {
  42581. var atd = gii.alphaTestData[0];
  42582. usedCount += atd._partData.usedElementCount;
  42583. }
  42584. if (gii.hasTransparentData) {
  42585. var td = gii.transparentData[0];
  42586. usedCount += td._partData.usedElementCount;
  42587. }
  42588. if (usedCount === 0 && gii.modelRenderCache != null) {
  42589. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  42590. gii.dispose();
  42591. }
  42592. if (this._modelRenderCache) {
  42593. this._modelRenderCache.dispose();
  42594. this._modelRenderCache = null;
  42595. }
  42596. }
  42597. this._instanceDataParts = null;
  42598. };
  42599. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  42600. _super.prototype._prepareRenderPre.call(this, context);
  42601. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  42602. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  42603. this._cleanupInstanceDataParts();
  42604. }
  42605. // Need to create the model?
  42606. var setupModelRenderCache = false;
  42607. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  42608. setupModelRenderCache = this._createModelRenderCache();
  42609. }
  42610. var gii = null;
  42611. var newInstance = false;
  42612. // Need to create the instance data parts?
  42613. if (!this._instanceDataParts) {
  42614. // Yes, flag it for later, more processing will have to be done
  42615. newInstance = true;
  42616. gii = this._createModelDataParts();
  42617. }
  42618. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  42619. if (setupModelRenderCache) {
  42620. this.setupModelRenderCache(this._modelRenderCache);
  42621. }
  42622. // 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.
  42623. // 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.
  42624. if (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  42625. this._updateInstanceDataParts(gii);
  42626. }
  42627. };
  42628. RenderablePrim2D.prototype._createModelRenderCache = function () {
  42629. var _this = this;
  42630. var setupModelRenderCache = false;
  42631. if (this._modelRenderCache) {
  42632. this._modelRenderCache.dispose();
  42633. }
  42634. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  42635. var mrc = _this.createModelRenderCache(key);
  42636. setupModelRenderCache = true;
  42637. return mrc;
  42638. });
  42639. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  42640. // if this is still false it means the MRC already exists, so we add a reference to it
  42641. if (!setupModelRenderCache) {
  42642. this._modelRenderCache.addRef();
  42643. }
  42644. return setupModelRenderCache;
  42645. };
  42646. RenderablePrim2D.prototype._createModelDataParts = function () {
  42647. var _this = this;
  42648. // Create the instance data parts of the primitive and store them
  42649. var parts = this.createInstanceDataParts();
  42650. this._instanceDataParts = parts;
  42651. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  42652. if (!this._modelRenderCache._partData) {
  42653. this._setupModelRenderCache(parts);
  42654. }
  42655. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  42656. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  42657. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  42658. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  42659. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  42660. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  42661. var part = _this._instanceDataParts[j];
  42662. res.partIndexFromId.add(part.id.toString(), j);
  42663. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  42664. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  42665. }
  42666. return res;
  42667. });
  42668. // Get the GroupInfoDataPart corresponding to the render category of the part
  42669. var rm = 0;
  42670. var gipd = null;
  42671. if (this.isTransparent) {
  42672. gipd = gii.transparentData;
  42673. rm = BABYLON.Render2DContext.RenderModeTransparent;
  42674. }
  42675. else if (this.isAlphaTest) {
  42676. gipd = gii.alphaTestData;
  42677. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  42678. }
  42679. else {
  42680. gipd = gii.opaqueData;
  42681. rm = BABYLON.Render2DContext.RenderModeOpaque;
  42682. }
  42683. // For each instance data part of the primitive, allocate the instanced element it needs for render
  42684. for (var i = 0; i < parts.length; i++) {
  42685. var part = parts[i];
  42686. part.dataBuffer = gipd[i]._partData;
  42687. part.allocElements();
  42688. part.renderMode = rm;
  42689. part.groupInstanceInfo = gii;
  42690. }
  42691. return gii;
  42692. };
  42693. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  42694. var ctiArray = new Array();
  42695. this._modelRenderCache._partData = new Array();
  42696. for (var _i = 0; _i < parts.length; _i++) {
  42697. var dataPart = parts[_i];
  42698. var pd = new BABYLON.ModelRenderCachePartData();
  42699. this._modelRenderCache._partData.push(pd);
  42700. var cat = this.getUsedShaderCategories(dataPart);
  42701. var cti = dataPart.getClassTreeInfo();
  42702. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  42703. var curVisible = this.isVisible;
  42704. this.isVisible = true;
  42705. // 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.
  42706. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  42707. var joinCat = ";" + cat.join(";") + ";";
  42708. pd._partJoinedUsedCategories = joinCat;
  42709. InstanceClassInfo._CurCategories = joinCat;
  42710. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  42711. if (!this.refreshInstanceDataPart(dataPart)) {
  42712. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  42713. }
  42714. this.afterRefreshForLayoutConstruction(dataPart, obj);
  42715. this.isVisible = curVisible;
  42716. var size = 0;
  42717. cti.fullContent.forEach(function (k, v) {
  42718. if (!v.category || cat.indexOf(v.category) !== -1) {
  42719. if (v.attributeName === "zBias") {
  42720. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  42721. }
  42722. if (!v.size) {
  42723. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  42724. }
  42725. else {
  42726. size += v.size;
  42727. }
  42728. }
  42729. });
  42730. pd._partDataStride = size;
  42731. pd._partUsedCategories = cat;
  42732. pd._partId = dataPart.id;
  42733. ctiArray.push(cti);
  42734. }
  42735. this._modelRenderCache._partsClassInfo = ctiArray;
  42736. };
  42737. RenderablePrim2D.prototype.onZOrderChanged = function () {
  42738. if (this.isTransparent && this._transparentPrimitiveInfo) {
  42739. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  42740. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  42741. // Flag the transparentData dirty has will have to sort it again
  42742. gii.transparentOrderDirty = true;
  42743. }
  42744. };
  42745. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  42746. return false;
  42747. };
  42748. RenderablePrim2D.prototype._useTextureAlpha = function () {
  42749. return false;
  42750. };
  42751. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  42752. return false;
  42753. };
  42754. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  42755. return false;
  42756. };
  42757. RenderablePrim2D.prototype._isPrimTransparent = function () {
  42758. return false;
  42759. };
  42760. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  42761. // Fetch the GroupInstanceInfo if we don't already have it
  42762. var rd = this.renderGroup._renderableData;
  42763. if (!gii) {
  42764. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  42765. }
  42766. var isTransparent = this.isTransparent;
  42767. var isAlphaTest = this.isAlphaTest;
  42768. var wereTransparent = false;
  42769. // Check a render mode change
  42770. var rmChanged = false;
  42771. if (this._instanceDataParts.length > 0) {
  42772. var firstPart = this._instanceDataParts[0];
  42773. var partRM = firstPart.renderMode;
  42774. var curRM = this.renderMode;
  42775. if (partRM !== curRM) {
  42776. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  42777. rmChanged = true;
  42778. var gipd;
  42779. switch (curRM) {
  42780. case BABYLON.Render2DContext.RenderModeTransparent:
  42781. gipd = gii.transparentData;
  42782. break;
  42783. case BABYLON.Render2DContext.RenderModeAlphaTest:
  42784. gipd = gii.alphaTestData;
  42785. break;
  42786. default:
  42787. gipd = gii.opaqueData;
  42788. }
  42789. for (var i = 0; i < this._instanceDataParts.length; i++) {
  42790. var part = this._instanceDataParts[i];
  42791. part.freeElements();
  42792. part.dataBuffer = gipd[i]._partData;
  42793. part.renderMode = curRM;
  42794. }
  42795. }
  42796. }
  42797. // Handle changes related to ZOffset
  42798. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  42799. if (isTransparent || wereTransparent) {
  42800. // Handle visibility change, which is also triggered when the primitive just got created
  42801. if (visChanged || rmChanged) {
  42802. if (this.isVisible && !wereTransparent) {
  42803. if (!this._transparentPrimitiveInfo) {
  42804. // Add the primitive to the list of transparent ones in the group that render is
  42805. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  42806. }
  42807. }
  42808. else {
  42809. if (this._transparentPrimitiveInfo) {
  42810. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  42811. this._transparentPrimitiveInfo = null;
  42812. }
  42813. }
  42814. gii.transparentOrderDirty = true;
  42815. }
  42816. }
  42817. var rebuildTrans = false;
  42818. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  42819. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42820. var part = _a[_i];
  42821. var justAllocated = false;
  42822. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  42823. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  42824. part.allocElements();
  42825. justAllocated = true;
  42826. }
  42827. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  42828. // Will return false if the instance should not be rendered (not visible or other any reasons)
  42829. part.arrayLengthChanged = false;
  42830. if (!this.refreshInstanceDataPart(part)) {
  42831. // Free the data element
  42832. if (part.dataElements) {
  42833. part.freeElements();
  42834. }
  42835. // The refresh couldn't succeed, push the primitive to be dirty again for the next render
  42836. if (this.isVisible) {
  42837. rd._primNewDirtyList.push(this);
  42838. }
  42839. }
  42840. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  42841. }
  42842. this._instanceDirtyFlags = 0;
  42843. // Make the appropriate data dirty
  42844. if (isTransparent) {
  42845. gii.transparentDirty = true;
  42846. if (rebuildTrans) {
  42847. rd._transparentListChanged = true;
  42848. }
  42849. }
  42850. else if (isAlphaTest) {
  42851. gii.alphaTestDirty = true;
  42852. }
  42853. else {
  42854. gii.opaqueDirty = true;
  42855. }
  42856. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  42857. };
  42858. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  42859. var minOff = BABYLON.Prim2DBase._bigInt;
  42860. var maxOff = 0;
  42861. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42862. var part = _a[_i];
  42863. if (part && part.dataElements) {
  42864. part.dataBuffer.pack();
  42865. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  42866. var el = _c[_b];
  42867. minOff = Math.min(minOff, el.offset);
  42868. maxOff = Math.max(maxOff, el.offset);
  42869. }
  42870. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  42871. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  42872. }
  42873. }
  42874. };
  42875. // This internal method is mainly used for transparency processing
  42876. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  42877. var length = this._instanceDataParts.length;
  42878. for (var i = 0; i < length; i++) {
  42879. var part = this._instanceDataParts[i];
  42880. if (part) {
  42881. var stride = part.dataBuffer.stride;
  42882. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  42883. // check if it's the last in the DFA
  42884. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  42885. return null;
  42886. }
  42887. // Return the Z of the next primitive that lies in the DFA
  42888. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  42889. }
  42890. }
  42891. return null;
  42892. };
  42893. // This internal method is mainly used for transparency processing
  42894. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  42895. var length = this._instanceDataParts.length;
  42896. for (var i = 0; i < length; i++) {
  42897. var part = this._instanceDataParts[i];
  42898. if (part) {
  42899. var stride = part.dataBuffer.stride;
  42900. var firstElementOffset = part.dataElements[0].offset;
  42901. // check if it's the first in the DFA
  42902. if (firstElementOffset === 0) {
  42903. return null;
  42904. }
  42905. // Return the Z of the previous primitive that lies in the DFA
  42906. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  42907. }
  42908. }
  42909. return null;
  42910. };
  42911. /**
  42912. * Transform a given point using the Primitive's origin setting.
  42913. * This method requires the Primitive's actualSize to be accurate
  42914. * @param p the point to transform
  42915. * @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.
  42916. * @param res an allocated Vector2 that will receive the transformed content
  42917. */
  42918. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  42919. var actualSize = this.actualSize;
  42920. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  42921. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  42922. };
  42923. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  42924. this.transformPointWithOriginByRef(p, originOffset, res);
  42925. return res;
  42926. };
  42927. /**
  42928. * Get the info for a given effect based on the dataPart metadata
  42929. * @param dataPartId partId in part list to get the info
  42930. * @param vertexBufferAttributes vertex buffer attributes to manually add
  42931. * @param uniforms uniforms to manually add
  42932. * @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
  42933. */
  42934. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  42935. if (uniforms === void 0) { uniforms = null; }
  42936. if (useInstanced === void 0) { useInstanced = null; }
  42937. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  42938. if (!dataPart) {
  42939. return null;
  42940. }
  42941. var instancedArray = this.owner.supportInstancedArray;
  42942. if (useInstanced != null) {
  42943. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  42944. if (useInstanced && instancedArray === false) {
  42945. return null;
  42946. }
  42947. // Use the caller's setting
  42948. instancedArray = useInstanced;
  42949. }
  42950. var cti = dataPart.getClassTreeInfo();
  42951. var categories = this.getUsedShaderCategories(dataPart);
  42952. var att = cti.classContent.getShaderAttributes(categories);
  42953. var defines = "";
  42954. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  42955. if (instancedArray) {
  42956. defines += "#define Instanced\n";
  42957. }
  42958. return {
  42959. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  42960. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  42961. defines: defines
  42962. };
  42963. };
  42964. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  42965. get: function () {
  42966. return this._modelRenderCache;
  42967. },
  42968. enumerable: true,
  42969. configurable: true
  42970. });
  42971. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  42972. return null;
  42973. };
  42974. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42975. };
  42976. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  42977. return null;
  42978. };
  42979. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  42980. return [];
  42981. };
  42982. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  42983. };
  42984. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  42985. };
  42986. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  42987. if (!this.isVisible) {
  42988. return false;
  42989. }
  42990. part.isVisible = this.isVisible;
  42991. // 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)
  42992. if (part.dataElementCount === 1) {
  42993. part.curElement = 0;
  42994. this.updateInstanceDataPart(part);
  42995. }
  42996. return true;
  42997. };
  42998. /**
  42999. * Update the instanceDataBase level properties of a part
  43000. * @param part the part to update
  43001. * @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).
  43002. */
  43003. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  43004. if (positionOffset === void 0) { positionOffset = null; }
  43005. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  43006. var size = this.renderGroup.viewportSize;
  43007. var zBias = this.actualZOffset;
  43008. var offX = 0;
  43009. var offY = 0;
  43010. // If there's an offset, apply the global transformation matrix on it to get a global offset
  43011. if (positionOffset) {
  43012. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  43013. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  43014. }
  43015. // 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
  43016. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  43017. // So for X:
  43018. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  43019. // - 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].
  43020. var w = size.width;
  43021. var h = size.height;
  43022. var invZBias = 1 / zBias;
  43023. 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);
  43024. 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);
  43025. part.transformX = tx;
  43026. part.transformY = ty;
  43027. part.opacity = this.actualOpacity;
  43028. // 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)
  43029. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  43030. };
  43031. RenderablePrim2D.prototype._updateRenderMode = function () {
  43032. if (this.isTransparent) {
  43033. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  43034. }
  43035. else if (this.isAlphaTest) {
  43036. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  43037. }
  43038. else {
  43039. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  43040. }
  43041. };
  43042. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  43043. __decorate([
  43044. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  43045. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  43046. __decorate([
  43047. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  43048. ], RenderablePrim2D.prototype, "isTransparent", null);
  43049. RenderablePrim2D = __decorate([
  43050. BABYLON.className("RenderablePrim2D")
  43051. ], RenderablePrim2D);
  43052. return RenderablePrim2D;
  43053. })(BABYLON.Prim2DBase);
  43054. BABYLON.RenderablePrim2D = RenderablePrim2D;
  43055. })(BABYLON || (BABYLON = {}));
  43056. var BABYLON;
  43057. (function (BABYLON) {
  43058. var Shape2D = (function (_super) {
  43059. __extends(Shape2D, _super);
  43060. function Shape2D(settings) {
  43061. _super.call(this, settings);
  43062. if (!settings) {
  43063. settings = {};
  43064. }
  43065. var borderBrush = null;
  43066. if (settings.border) {
  43067. if (typeof (settings.border) === "string") {
  43068. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  43069. }
  43070. else {
  43071. borderBrush = settings.border;
  43072. }
  43073. }
  43074. var fillBrush = null;
  43075. if (settings.fill) {
  43076. if (typeof (settings.fill) === "string") {
  43077. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  43078. }
  43079. else {
  43080. fillBrush = settings.fill;
  43081. }
  43082. }
  43083. this._isTransparent = false;
  43084. this._oldTransparent = false;
  43085. this.border = borderBrush;
  43086. this.fill = fillBrush;
  43087. this._updateTransparencyStatus();
  43088. this.borderThickness = settings.borderThickness;
  43089. }
  43090. Object.defineProperty(Shape2D.prototype, "border", {
  43091. get: function () {
  43092. return this._border;
  43093. },
  43094. set: function (value) {
  43095. this._border = value;
  43096. this._updateTransparencyStatus();
  43097. },
  43098. enumerable: true,
  43099. configurable: true
  43100. });
  43101. Object.defineProperty(Shape2D.prototype, "fill", {
  43102. /**
  43103. * Get/set the brush to render the Fill part of the Primitive
  43104. */
  43105. get: function () {
  43106. return this._fill;
  43107. },
  43108. set: function (value) {
  43109. this._fill = value;
  43110. this._updateTransparencyStatus();
  43111. },
  43112. enumerable: true,
  43113. configurable: true
  43114. });
  43115. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  43116. get: function () {
  43117. return this._borderThickness;
  43118. },
  43119. set: function (value) {
  43120. this._borderThickness = value;
  43121. },
  43122. enumerable: true,
  43123. configurable: true
  43124. });
  43125. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  43126. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  43127. // Fill Part
  43128. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  43129. var fill = this.fill;
  43130. if (fill instanceof BABYLON.SolidColorBrush2D) {
  43131. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  43132. }
  43133. if (fill instanceof BABYLON.GradientColorBrush2D) {
  43134. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  43135. }
  43136. }
  43137. // Border Part
  43138. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  43139. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  43140. var border = this.border;
  43141. if (border instanceof BABYLON.SolidColorBrush2D) {
  43142. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  43143. }
  43144. if (border instanceof BABYLON.GradientColorBrush2D) {
  43145. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  43146. }
  43147. }
  43148. return cat;
  43149. };
  43150. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  43151. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43152. return false;
  43153. }
  43154. // Fill Part
  43155. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  43156. var d = part;
  43157. if (this.fill) {
  43158. var fill = this.fill;
  43159. if (fill instanceof BABYLON.SolidColorBrush2D) {
  43160. d.fillSolidColor = fill.color;
  43161. }
  43162. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  43163. d.fillGradientColor1 = fill.color1;
  43164. d.fillGradientColor2 = fill.color2;
  43165. 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));
  43166. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  43167. d.fillGradientTY = ty;
  43168. }
  43169. }
  43170. }
  43171. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  43172. var d = part;
  43173. if (this.border) {
  43174. d.borderThickness = this.borderThickness;
  43175. var border = this.border;
  43176. if (border instanceof BABYLON.SolidColorBrush2D) {
  43177. d.borderSolidColor = border.color;
  43178. }
  43179. else if (border instanceof BABYLON.GradientColorBrush2D) {
  43180. d.borderGradientColor1 = border.color1;
  43181. d.borderGradientColor2 = border.color2;
  43182. 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));
  43183. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  43184. d.borderGradientTY = ty;
  43185. }
  43186. }
  43187. }
  43188. return true;
  43189. };
  43190. Shape2D.prototype._updateTransparencyStatus = function () {
  43191. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  43192. if (this._isTransparent !== this._oldTransparent) {
  43193. this._oldTransparent = this._isTransparent;
  43194. this._updateRenderMode();
  43195. }
  43196. };
  43197. Shape2D.prototype._mustUpdateInstance = function () {
  43198. var res = this._oldTransparent !== this._isTransparent;
  43199. if (res) {
  43200. this._updateRenderMode();
  43201. this._oldTransparent = this._isTransparent;
  43202. }
  43203. return res;
  43204. };
  43205. Shape2D.prototype._isPrimTransparent = function () {
  43206. return this._isTransparent;
  43207. };
  43208. Shape2D.SHAPE2D_BORDERPARTID = 1;
  43209. Shape2D.SHAPE2D_FILLPARTID = 2;
  43210. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  43211. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  43212. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  43213. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  43214. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  43215. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  43216. __decorate([
  43217. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  43218. ], Shape2D.prototype, "border", null);
  43219. __decorate([
  43220. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  43221. ], Shape2D.prototype, "fill", null);
  43222. __decorate([
  43223. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  43224. ], Shape2D.prototype, "borderThickness", null);
  43225. Shape2D = __decorate([
  43226. BABYLON.className("Shape2D")
  43227. ], Shape2D);
  43228. return Shape2D;
  43229. })(BABYLON.RenderablePrim2D);
  43230. BABYLON.Shape2D = Shape2D;
  43231. var Shape2DInstanceData = (function (_super) {
  43232. __extends(Shape2DInstanceData, _super);
  43233. function Shape2DInstanceData() {
  43234. _super.apply(this, arguments);
  43235. }
  43236. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  43237. // FILL ATTRIBUTES
  43238. get: function () {
  43239. return null;
  43240. },
  43241. enumerable: true,
  43242. configurable: true
  43243. });
  43244. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  43245. get: function () {
  43246. return null;
  43247. },
  43248. enumerable: true,
  43249. configurable: true
  43250. });
  43251. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  43252. get: function () {
  43253. return null;
  43254. },
  43255. enumerable: true,
  43256. configurable: true
  43257. });
  43258. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  43259. get: function () {
  43260. return null;
  43261. },
  43262. enumerable: true,
  43263. configurable: true
  43264. });
  43265. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  43266. // BORDER ATTRIBUTES
  43267. get: function () {
  43268. return null;
  43269. },
  43270. enumerable: true,
  43271. configurable: true
  43272. });
  43273. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  43274. get: function () {
  43275. return null;
  43276. },
  43277. enumerable: true,
  43278. configurable: true
  43279. });
  43280. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  43281. get: function () {
  43282. return null;
  43283. },
  43284. enumerable: true,
  43285. configurable: true
  43286. });
  43287. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  43288. get: function () {
  43289. return null;
  43290. },
  43291. enumerable: true,
  43292. configurable: true
  43293. });
  43294. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  43295. get: function () {
  43296. return null;
  43297. },
  43298. enumerable: true,
  43299. configurable: true
  43300. });
  43301. __decorate([
  43302. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  43303. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  43304. __decorate([
  43305. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43306. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  43307. __decorate([
  43308. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43309. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  43310. __decorate([
  43311. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43312. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  43313. __decorate([
  43314. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  43315. ], Shape2DInstanceData.prototype, "borderThickness", null);
  43316. __decorate([
  43317. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  43318. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  43319. __decorate([
  43320. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43321. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  43322. __decorate([
  43323. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43324. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  43325. __decorate([
  43326. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43327. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  43328. return Shape2DInstanceData;
  43329. })(BABYLON.InstanceDataBase);
  43330. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  43331. })(BABYLON || (BABYLON = {}));
  43332. var BABYLON;
  43333. (function (BABYLON) {
  43334. var Group2D = (function (_super) {
  43335. __extends(Group2D, _super);
  43336. /**
  43337. * Create an Logical or Renderable Group.
  43338. * @param settings a combination of settings, possible ones are
  43339. * - 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)
  43340. * - children: an array of direct children
  43341. * - id a text identifier, for information purpose
  43342. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43343. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43344. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  43345. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43346. * - zOrder: override the zOrder with the specified value
  43347. * - origin: define the normalized origin point location, default [0.5;0.5]
  43348. * - 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.
  43349. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  43350. * - 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).
  43351. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  43352. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  43353. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  43354. * - 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!
  43355. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43356. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43357. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43358. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43359. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43360. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43361. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43362. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43363. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43364. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43365. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43366. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43367. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43368. */
  43369. function Group2D(settings) {
  43370. if (settings == null) {
  43371. settings = {};
  43372. }
  43373. if (settings.origin == null) {
  43374. settings.origin = new BABYLON.Vector2(0, 0);
  43375. }
  43376. _super.call(this, settings);
  43377. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  43378. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  43379. if (this._trackedNode && this.owner) {
  43380. this.owner._registerTrackedNode(this);
  43381. }
  43382. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  43383. this.size = size;
  43384. this._viewportPosition = BABYLON.Vector2.Zero();
  43385. }
  43386. Group2D._createCachedCanvasGroup = function (owner) {
  43387. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true, isPickable: false });
  43388. return g;
  43389. };
  43390. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  43391. this._bindCacheTarget();
  43392. if (vertexData) {
  43393. var uv = vertexData.uvs;
  43394. var nodeuv = this._renderableData._cacheNodeUVs;
  43395. for (var i = 0; i < 4; i++) {
  43396. uv[i * 2 + 0] = nodeuv[i].x;
  43397. uv[i * 2 + 1] = nodeuv[i].y;
  43398. }
  43399. }
  43400. if (material) {
  43401. material.diffuseTexture = this._renderableData._cacheTexture;
  43402. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  43403. }
  43404. this._renderableData._cacheTexture.hasAlpha = true;
  43405. this._unbindCacheTarget();
  43406. };
  43407. Object.defineProperty(Group2D.prototype, "cachedRect", {
  43408. /**
  43409. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  43410. * 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.
  43411. */
  43412. get: function () {
  43413. if (!this._renderableData) {
  43414. return null;
  43415. }
  43416. return this._renderableData._cacheNode;
  43417. },
  43418. enumerable: true,
  43419. configurable: true
  43420. });
  43421. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  43422. /**
  43423. * The UVs into the MapTexture that map the cached group
  43424. */
  43425. get: function () {
  43426. if (!this._renderableData) {
  43427. return null;
  43428. }
  43429. return this._renderableData._cacheNodeUVs;
  43430. },
  43431. enumerable: true,
  43432. configurable: true
  43433. });
  43434. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  43435. get: function () {
  43436. if (!this._renderableData) {
  43437. return null;
  43438. }
  43439. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  43440. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  43441. }
  43442. return this._renderableData._cacheNodeUVsChangedObservable;
  43443. },
  43444. enumerable: true,
  43445. configurable: true
  43446. });
  43447. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  43448. /**
  43449. * Access the texture that maintains a cached version of the Group2D.
  43450. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  43451. */
  43452. get: function () {
  43453. if (!this._renderableData) {
  43454. return null;
  43455. }
  43456. return this._renderableData._cacheTexture;
  43457. },
  43458. enumerable: true,
  43459. configurable: true
  43460. });
  43461. /**
  43462. * Call this method to remove this Group and its children from the Canvas
  43463. */
  43464. Group2D.prototype.dispose = function () {
  43465. if (!_super.prototype.dispose.call(this)) {
  43466. return false;
  43467. }
  43468. if (this._trackedNode != null) {
  43469. this.owner._unregisterTrackedNode(this);
  43470. this._trackedNode = null;
  43471. }
  43472. if (this._renderableData) {
  43473. this._renderableData.dispose(this.owner.engine);
  43474. this._renderableData = null;
  43475. }
  43476. return true;
  43477. };
  43478. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  43479. /**
  43480. * @returns Returns true if the Group render content, false if it's a logical group only
  43481. */
  43482. get: function () {
  43483. return this._isRenderableGroup;
  43484. },
  43485. enumerable: true,
  43486. configurable: true
  43487. });
  43488. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  43489. /**
  43490. * @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
  43491. */
  43492. get: function () {
  43493. return this._isCachedGroup;
  43494. },
  43495. enumerable: true,
  43496. configurable: true
  43497. });
  43498. Object.defineProperty(Group2D.prototype, "size", {
  43499. get: function () {
  43500. return this._size;
  43501. },
  43502. /**
  43503. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  43504. * 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.
  43505. */
  43506. set: function (val) {
  43507. this._size = val;
  43508. },
  43509. enumerable: true,
  43510. configurable: true
  43511. });
  43512. Object.defineProperty(Group2D.prototype, "viewportSize", {
  43513. get: function () {
  43514. return this._viewportSize;
  43515. },
  43516. enumerable: true,
  43517. configurable: true
  43518. });
  43519. Object.defineProperty(Group2D.prototype, "actualSize", {
  43520. get: function () {
  43521. // The computed size will be floor on both width and height
  43522. var actualSize;
  43523. // Return the size if set by the user
  43524. if (this._size) {
  43525. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  43526. }
  43527. else {
  43528. var m = this.boundingInfo.max();
  43529. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  43530. }
  43531. // 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)
  43532. if (!actualSize.equals(this._actualSize)) {
  43533. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  43534. this._actualSize = actualSize;
  43535. this.handleGroupChanged(Group2D.actualSizeProperty);
  43536. }
  43537. return actualSize;
  43538. },
  43539. enumerable: true,
  43540. configurable: true
  43541. });
  43542. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  43543. /**
  43544. * 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.
  43545. * 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.
  43546. */
  43547. get: function () {
  43548. return this._cacheBehavior;
  43549. },
  43550. enumerable: true,
  43551. configurable: true
  43552. });
  43553. Group2D.prototype._addPrimToDirtyList = function (prim) {
  43554. this._renderableData._primDirtyList.push(prim);
  43555. };
  43556. Group2D.prototype._renderCachedCanvas = function () {
  43557. this.owner._addGroupRenderCount(1);
  43558. this.updateCachedStates(true);
  43559. var context = new BABYLON.PrepareRender2DContext();
  43560. this._prepareGroupRender(context);
  43561. this._groupRender();
  43562. };
  43563. Object.defineProperty(Group2D.prototype, "trackedNode", {
  43564. /**
  43565. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  43566. */
  43567. get: function () {
  43568. return this._trackedNode;
  43569. },
  43570. set: function (val) {
  43571. if (val != null) {
  43572. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  43573. this.owner._registerTrackedNode(this);
  43574. }
  43575. this._trackedNode = val;
  43576. }
  43577. else {
  43578. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  43579. this.owner._unregisterTrackedNode(this);
  43580. }
  43581. this._trackedNode = null;
  43582. }
  43583. },
  43584. enumerable: true,
  43585. configurable: true
  43586. });
  43587. Group2D.prototype.levelIntersect = function (intersectInfo) {
  43588. // 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
  43589. return true;
  43590. };
  43591. Group2D.prototype.updateLevelBoundingInfo = function () {
  43592. var size;
  43593. // If the size is set by the user, the boundingInfo is computed from this value
  43594. if (this.size) {
  43595. size = this.size;
  43596. }
  43597. else {
  43598. size = new BABYLON.Size(0, 0);
  43599. }
  43600. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  43601. };
  43602. // Method called only on renderable groups to prepare the rendering
  43603. Group2D.prototype._prepareGroupRender = function (context) {
  43604. var sortedDirtyList = null;
  43605. // Update the Global Transformation and visibility status of the changed primitives
  43606. var rd = this._renderableData;
  43607. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  43608. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  43609. this.updateCachedStatesOf(sortedDirtyList, true);
  43610. }
  43611. // Setup the size of the rendering viewport
  43612. // 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
  43613. if (!this._isCachedGroup) {
  43614. // Compute the WebGL viewport's location/size
  43615. var t = this._globalTransform.getTranslation();
  43616. var s = this.actualSize.clone();
  43617. var rs = this.owner._renderingSize;
  43618. s.height = Math.min(s.height, rs.height - t.y);
  43619. s.width = Math.min(s.width, rs.width - t.x);
  43620. var x = t.x;
  43621. var y = t.y;
  43622. // 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
  43623. this._viewportPosition.x = x;
  43624. this._viewportPosition.y = y;
  43625. var vw = s.width;
  43626. var vh = s.height;
  43627. if (!this._viewportSize) {
  43628. this._viewportSize = new BABYLON.Size(vw, vh);
  43629. }
  43630. else {
  43631. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  43632. context.forceRefreshPrimitive = true;
  43633. }
  43634. this._viewportSize.width = vw;
  43635. this._viewportSize.height = vh;
  43636. }
  43637. }
  43638. else {
  43639. var newSize = this.actualSize.clone();
  43640. if (!newSize.equals(this._viewportSize)) {
  43641. context.forceRefreshPrimitive = true;
  43642. }
  43643. this._viewportSize = newSize;
  43644. }
  43645. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  43646. // If the group is cached, set the dirty flag to true because of the incoming changes
  43647. this._cacheGroupDirty = this._isCachedGroup;
  43648. rd._primNewDirtyList.splice(0);
  43649. // If it's a force refresh, prepare all the children
  43650. if (context.forceRefreshPrimitive) {
  43651. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  43652. var p = _a[_i];
  43653. p._prepareRender(context);
  43654. }
  43655. }
  43656. else {
  43657. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  43658. // the hierarchyDepth in order to prepare primitives from top to bottom
  43659. if (!sortedDirtyList) {
  43660. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  43661. }
  43662. sortedDirtyList.forEach(function (p) {
  43663. // 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.
  43664. // 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.
  43665. if (!p.isDisposed && p._needPrepare()) {
  43666. p._prepareRender(context);
  43667. }
  43668. });
  43669. }
  43670. // Everything is updated, clear the dirty list
  43671. rd._primDirtyList.forEach(function (p) {
  43672. if (rd._primNewDirtyList.indexOf(p) === -1) {
  43673. p._resetPropertiesDirty();
  43674. }
  43675. else {
  43676. p._setFlags(BABYLON.SmartPropertyPrim.flagNeedRefresh);
  43677. }
  43678. });
  43679. rd._primDirtyList.splice(0);
  43680. rd._primDirtyList = rd._primDirtyList.concat(rd._primNewDirtyList);
  43681. }
  43682. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  43683. rd._childrenRenderableGroups.forEach(function (g) {
  43684. g._prepareGroupRender(context);
  43685. });
  43686. };
  43687. Group2D.prototype._groupRender = function () {
  43688. var _this = this;
  43689. var engine = this.owner.engine;
  43690. var failedCount = 0;
  43691. // First recurse to children render group to render them (in their cache or on screen)
  43692. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  43693. var childGroup = _a[_i];
  43694. childGroup._groupRender();
  43695. }
  43696. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  43697. if (!this.isCachedGroup || this._cacheGroupDirty) {
  43698. this.owner._addGroupRenderCount(1);
  43699. if (this.isCachedGroup) {
  43700. this._bindCacheTarget();
  43701. }
  43702. else {
  43703. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  43704. }
  43705. var curAlphaTest = engine.getAlphaTesting() === true;
  43706. var curDepthWrite = engine.getDepthWrite() === true;
  43707. // ===================================================================
  43708. // First pass, update the InstancedArray and render Opaque primitives
  43709. // Disable Alpha Testing, Enable Depth Write
  43710. engine.setAlphaTesting(false);
  43711. engine.setDepthWrite(true);
  43712. // For each different model of primitive to render
  43713. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  43714. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  43715. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  43716. var renderCount = _this._prepareContext(engine, context, v);
  43717. // If null is returned, there's no opaque data to render
  43718. if (renderCount === null) {
  43719. return;
  43720. }
  43721. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  43722. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  43723. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  43724. var renderFailed = !v.modelRenderCache.render(v, context);
  43725. // Update dirty flag/related
  43726. v.opaqueDirty = renderFailed;
  43727. failedCount += renderFailed ? 1 : 0;
  43728. }
  43729. });
  43730. // =======================================================================
  43731. // Second pass, update the InstancedArray and render AlphaTest primitives
  43732. // Enable Alpha Testing, Enable Depth Write
  43733. engine.setAlphaTesting(true);
  43734. engine.setDepthWrite(true);
  43735. // For each different model of primitive to render
  43736. context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  43737. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  43738. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  43739. var renderCount = _this._prepareContext(engine, context, v);
  43740. // If null is returned, there's no opaque data to render
  43741. if (renderCount === null) {
  43742. return;
  43743. }
  43744. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  43745. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  43746. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  43747. var renderFailed = !v.modelRenderCache.render(v, context);
  43748. // Update dirty flag/related
  43749. v.opaqueDirty = renderFailed;
  43750. failedCount += renderFailed ? 1 : 0;
  43751. }
  43752. });
  43753. // =======================================================================
  43754. // Third pass, transparent primitive rendering
  43755. // Enable Alpha Testing, Disable Depth Write
  43756. engine.setAlphaTesting(true);
  43757. engine.setDepthWrite(false);
  43758. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  43759. if (this._renderableData._transparentListChanged) {
  43760. this._updateTransparentData();
  43761. }
  43762. // From this point on we have up to date data to render, so let's go
  43763. failedCount += this._renderTransparentData();
  43764. // =======================================================================
  43765. // Unbind target/restore viewport setting, clear dirty flag, and quit
  43766. // The group's content is no longer dirty
  43767. this._cacheGroupDirty = failedCount !== 0;
  43768. if (this.isCachedGroup) {
  43769. this._unbindCacheTarget();
  43770. }
  43771. else {
  43772. if (curVP) {
  43773. engine.setViewport(curVP);
  43774. }
  43775. }
  43776. // Restore saved states
  43777. engine.setAlphaTesting(curAlphaTest);
  43778. engine.setDepthWrite(curDepthWrite);
  43779. }
  43780. };
  43781. Group2D.prototype._setCacheGroupDirty = function () {
  43782. this._cacheGroupDirty = true;
  43783. };
  43784. Group2D.prototype._updateTransparentData = function () {
  43785. this.owner._addUpdateTransparentDataCount(1);
  43786. var rd = this._renderableData;
  43787. // Sort all the primitive from their depth, max (bottom) to min (top)
  43788. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  43789. var checkAndAddPrimInSegment = function (seg, tpiI) {
  43790. var tpi = rd._transparentPrimitives[tpiI];
  43791. // Fast rejection: if gii are different
  43792. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  43793. return false;
  43794. }
  43795. //let tpiZ = tpi._primitive.actualZOffset;
  43796. // We've made it so far, the tpi can be part of the segment, add it
  43797. tpi._transparentSegment = seg;
  43798. tpi._primitive._updateTransparentSegmentIndices(seg);
  43799. return true;
  43800. };
  43801. // Free the existing TransparentSegments
  43802. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  43803. var ts = _a[_i];
  43804. ts.dispose(this.owner.engine);
  43805. }
  43806. rd._transparentSegments.splice(0);
  43807. var prevSeg = null;
  43808. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  43809. var tpi = rd._transparentPrimitives[tpiI];
  43810. // Check if the Data in which the primitive is stored is not sorted properly
  43811. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  43812. tpi._groupInstanceInfo.sortTransparentData();
  43813. }
  43814. // Reset the segment, we have to create/rebuild it
  43815. tpi._transparentSegment = null;
  43816. // If there's a previous valid segment, check if this prim can be part of it
  43817. if (prevSeg) {
  43818. checkAndAddPrimInSegment(prevSeg, tpiI);
  43819. }
  43820. // If we couldn't insert in the adjacent segments, he have to create one
  43821. if (!tpi._transparentSegment) {
  43822. var ts = new BABYLON.TransparentSegment();
  43823. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  43824. var prim = tpi._primitive;
  43825. ts.startZ = prim.actualZOffset;
  43826. prim._updateTransparentSegmentIndices(ts);
  43827. ts.endZ = ts.startZ;
  43828. tpi._transparentSegment = ts;
  43829. rd._transparentSegments.push(ts);
  43830. }
  43831. // Update prevSeg
  43832. prevSeg = tpi._transparentSegment;
  43833. }
  43834. //rd._firstChangedPrim = null;
  43835. rd._transparentListChanged = false;
  43836. };
  43837. Group2D.prototype._renderTransparentData = function () {
  43838. var failedCount = 0;
  43839. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  43840. var rd = this._renderableData;
  43841. var useInstanced = this.owner.supportInstancedArray;
  43842. var length = rd._transparentSegments.length;
  43843. for (var i = 0; i < length; i++) {
  43844. context.instancedBuffers = null;
  43845. var ts = rd._transparentSegments[i];
  43846. var gii = ts.groupInsanceInfo;
  43847. var mrc = gii.modelRenderCache;
  43848. var engine = this.owner.engine;
  43849. var count = ts.endDataIndex - ts.startDataIndex;
  43850. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  43851. // We don't want to create an Instanced Buffer for less that 5 prims
  43852. if (useInstanced && count >= 5) {
  43853. if (!ts.partBuffers) {
  43854. var buffers = new Array();
  43855. for (var j = 0; j < gii.transparentData.length; j++) {
  43856. var gitd = gii.transparentData[j];
  43857. var dfa = gitd._partData;
  43858. var data = dfa.pack();
  43859. var stride = dfa.stride;
  43860. var neededSize = count * stride * 4;
  43861. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  43862. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  43863. engine.updateArrayBuffer(segData);
  43864. buffers.push(buffer);
  43865. }
  43866. ts.partBuffers = buffers;
  43867. }
  43868. else if (gii.transparentDirty) {
  43869. for (var j = 0; j < gii.transparentData.length; j++) {
  43870. var gitd = gii.transparentData[j];
  43871. var dfa = gitd._partData;
  43872. var data = dfa.pack();
  43873. var stride = dfa.stride;
  43874. var buffer = ts.partBuffers[j];
  43875. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  43876. engine.bindArrayBuffer(buffer);
  43877. engine.updateArrayBuffer(segData);
  43878. }
  43879. }
  43880. context.useInstancing = true;
  43881. context.instancesCount = count;
  43882. context.instancedBuffers = ts.partBuffers;
  43883. context.groupInfoPartData = gii.transparentData;
  43884. var renderFailed = !mrc.render(gii, context);
  43885. failedCount += renderFailed ? 1 : 0;
  43886. }
  43887. else {
  43888. context.useInstancing = false;
  43889. context.partDataStartIndex = ts.startDataIndex;
  43890. context.partDataEndIndex = ts.endDataIndex;
  43891. context.groupInfoPartData = gii.transparentData;
  43892. var renderFailed = !mrc.render(gii, context);
  43893. failedCount += renderFailed ? 1 : 0;
  43894. }
  43895. }
  43896. return failedCount;
  43897. };
  43898. Group2D.prototype._prepareContext = function (engine, context, gii) {
  43899. var gipd = null;
  43900. var setDirty;
  43901. var getDirty;
  43902. // Render Mode specifics
  43903. switch (context.renderMode) {
  43904. case BABYLON.Render2DContext.RenderModeOpaque:
  43905. {
  43906. if (!gii.hasOpaqueData) {
  43907. return null;
  43908. }
  43909. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  43910. getDirty = function () { return gii.opaqueDirty; };
  43911. context.groupInfoPartData = gii.opaqueData;
  43912. gipd = gii.opaqueData;
  43913. break;
  43914. }
  43915. case BABYLON.Render2DContext.RenderModeAlphaTest:
  43916. {
  43917. if (!gii.hasAlphaTestData) {
  43918. return null;
  43919. }
  43920. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  43921. getDirty = function () { return gii.alphaTestDirty; };
  43922. context.groupInfoPartData = gii.alphaTestData;
  43923. gipd = gii.alphaTestData;
  43924. break;
  43925. }
  43926. default:
  43927. throw new Error("_prepareContext is only for opaque or alphaTest");
  43928. }
  43929. var renderCount = 0;
  43930. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  43931. // Skip it if instanced arrays are not supported
  43932. if (this.owner.supportInstancedArray) {
  43933. // Flag for instancing
  43934. context.useInstancing = true;
  43935. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  43936. for (var i = 0; i < gipd.length; i++) {
  43937. var pid = gipd[i];
  43938. // If the instances of the model was changed, pack the data
  43939. var array = pid._partData;
  43940. var instanceData_1 = array.pack();
  43941. renderCount += array.usedElementCount;
  43942. // Compute the size the instance buffer should have
  43943. var neededSize = array.usedElementCount * array.stride * 4;
  43944. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  43945. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  43946. if (pid._partBuffer) {
  43947. engine.deleteInstancesBuffer(pid._partBuffer);
  43948. }
  43949. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  43950. pid._partBufferSize = neededSize;
  43951. setDirty(false);
  43952. // Update the WebGL buffer to match the new content of the instances data
  43953. engine.updateArrayBuffer(instanceData_1);
  43954. }
  43955. else if (getDirty()) {
  43956. // Update the WebGL buffer to match the new content of the instances data
  43957. engine.bindArrayBuffer(pid._partBuffer);
  43958. engine.updateArrayBuffer(instanceData_1);
  43959. }
  43960. }
  43961. setDirty(false);
  43962. }
  43963. else {
  43964. context.partDataStartIndex = 0;
  43965. // Find the first valid object to get the count
  43966. if (context.groupInfoPartData.length > 0) {
  43967. var i = 0;
  43968. while (!context.groupInfoPartData[i]) {
  43969. i++;
  43970. }
  43971. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  43972. }
  43973. }
  43974. return renderCount;
  43975. };
  43976. Group2D.prototype._setRenderingScale = function (scale) {
  43977. if (this._renderableData._renderingScale === scale) {
  43978. return;
  43979. }
  43980. this._renderableData._renderingScale = scale;
  43981. };
  43982. Group2D.prototype._bindCacheTarget = function () {
  43983. var curWidth;
  43984. var curHeight;
  43985. var rd = this._renderableData;
  43986. var rs = rd._renderingScale;
  43987. Group2D._s.width = Math.ceil(this.actualSize.width * rs);
  43988. Group2D._s.height = Math.ceil(this.actualSize.height * rs);
  43989. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  43990. if (rd._cacheNode) {
  43991. var size = rd._cacheNode.contentSize;
  43992. // Check if we have to deallocate because the size is too small
  43993. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  43994. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  43995. // For World space: no over-provisioning
  43996. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  43997. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  43998. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  43999. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  44000. rd._cacheTexture.freeRect(rd._cacheNode);
  44001. rd._cacheNode = null;
  44002. }
  44003. }
  44004. if (!rd._cacheNode) {
  44005. // Check if we have to allocate a rendering zone in the global cache texture
  44006. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  44007. rd._cacheNode = res.node;
  44008. rd._cacheTexture = res.texture;
  44009. rd._cacheRenderSprite = res.sprite;
  44010. sizeChanged = true;
  44011. }
  44012. if (sizeChanged) {
  44013. rd._cacheSize.copyFrom(Group2D._s);
  44014. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  44015. this.scale = this._renderableData._renderingScale;
  44016. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  44017. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  44018. }
  44019. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  44020. }
  44021. var n = rd._cacheNode;
  44022. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  44023. };
  44024. Group2D.prototype._unbindCacheTarget = function () {
  44025. if (this._renderableData._cacheTexture) {
  44026. this._renderableData._cacheTexture.unbindTexture();
  44027. }
  44028. };
  44029. Group2D.prototype.handleGroupChanged = function (prop) {
  44030. // This method is only for cachedGroup
  44031. var rd = this._renderableData;
  44032. if (!rd) {
  44033. return;
  44034. }
  44035. var cachedSprite = rd._cacheRenderSprite;
  44036. if (!this.isCachedGroup || !cachedSprite) {
  44037. return;
  44038. }
  44039. // For now we only support these property changes
  44040. // TODO: add more! :)
  44041. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  44042. cachedSprite.actualPosition = this.actualPosition.clone();
  44043. if (cachedSprite.position != null) {
  44044. cachedSprite.position = cachedSprite.actualPosition.clone();
  44045. }
  44046. }
  44047. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  44048. cachedSprite.rotation = this.rotation;
  44049. }
  44050. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  44051. cachedSprite.scale = this.scale;
  44052. }
  44053. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  44054. cachedSprite.origin = this.origin.clone();
  44055. }
  44056. else if (prop.id === Group2D.actualSizeProperty.id) {
  44057. cachedSprite.size = this.actualSize.clone();
  44058. }
  44059. };
  44060. Group2D.prototype.detectGroupStates = function () {
  44061. var isCanvas = this instanceof BABYLON.Canvas2D;
  44062. var canvasStrat = this.owner.cachingStrategy;
  44063. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  44064. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  44065. this._isRenderableGroup = isCanvas;
  44066. this._isCachedGroup = false;
  44067. }
  44068. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  44069. if (isCanvas) {
  44070. this._isRenderableGroup = true;
  44071. this._isCachedGroup = true;
  44072. }
  44073. else {
  44074. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  44075. this._isCachedGroup = false;
  44076. }
  44077. }
  44078. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  44079. if (isCanvas) {
  44080. this._isRenderableGroup = true;
  44081. this._isCachedGroup = false;
  44082. }
  44083. else {
  44084. if (this.hierarchyDepth === 1) {
  44085. this._isRenderableGroup = true;
  44086. this._isCachedGroup = true;
  44087. }
  44088. else {
  44089. this._isRenderableGroup = false;
  44090. this._isCachedGroup = false;
  44091. }
  44092. }
  44093. }
  44094. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  44095. var gcb = this.cacheBehavior;
  44096. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  44097. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  44098. this._isCachedGroup = false;
  44099. }
  44100. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  44101. this._isRenderableGroup = true;
  44102. this._isCachedGroup = true;
  44103. }
  44104. }
  44105. if (this._isRenderableGroup) {
  44106. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  44107. if (!this._renderableData) {
  44108. this._renderableData = new RenderableGroupData();
  44109. }
  44110. }
  44111. // If the group is tagged as renderable we add it to the renderable tree
  44112. if (this._isCachedGroup) {
  44113. var cur = this.parent;
  44114. while (cur) {
  44115. if (cur instanceof Group2D && cur._isRenderableGroup) {
  44116. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  44117. cur._renderableData._childrenRenderableGroups.push(this);
  44118. }
  44119. break;
  44120. }
  44121. cur = cur.parent;
  44122. }
  44123. }
  44124. };
  44125. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  44126. /**
  44127. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  44128. */
  44129. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  44130. /**
  44131. * When used, this group's content won't be cached, no matter which strategy used.
  44132. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  44133. */
  44134. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  44135. /**
  44136. * When used, the group's content will be cached in the nearest cached parent group/canvas
  44137. */
  44138. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  44139. Group2D._s = BABYLON.Size.Zero();
  44140. __decorate([
  44141. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  44142. ], Group2D.prototype, "size", null);
  44143. __decorate([
  44144. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  44145. ], Group2D.prototype, "actualSize", null);
  44146. Group2D = __decorate([
  44147. BABYLON.className("Group2D")
  44148. ], Group2D);
  44149. return Group2D;
  44150. })(BABYLON.Prim2DBase);
  44151. BABYLON.Group2D = Group2D;
  44152. var RenderableGroupData = (function () {
  44153. function RenderableGroupData() {
  44154. this._primDirtyList = new Array();
  44155. this._primNewDirtyList = new Array();
  44156. this._childrenRenderableGroups = new Array();
  44157. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  44158. this._transparentPrimitives = new Array();
  44159. this._transparentSegments = new Array();
  44160. this._transparentListChanged = false;
  44161. this._cacheNode = null;
  44162. this._cacheTexture = null;
  44163. this._cacheRenderSprite = null;
  44164. this._renderingScale = 1;
  44165. this._cacheNodeUVs = null;
  44166. this._cacheNodeUVsChangedObservable = null;
  44167. this._cacheSize = BABYLON.Size.Zero();
  44168. this._useMipMap = false;
  44169. this._anisotropicLevel = 1;
  44170. }
  44171. RenderableGroupData.prototype.dispose = function (engine) {
  44172. if (this._cacheRenderSprite) {
  44173. this._cacheRenderSprite.dispose();
  44174. this._cacheRenderSprite = null;
  44175. }
  44176. if (this._cacheTexture && this._cacheNode) {
  44177. this._cacheTexture.freeRect(this._cacheNode);
  44178. this._cacheTexture = null;
  44179. this._cacheNode = null;
  44180. }
  44181. if (this._primDirtyList) {
  44182. this._primDirtyList.splice(0);
  44183. this._primDirtyList = null;
  44184. }
  44185. if (this._renderGroupInstancesInfo) {
  44186. this._renderGroupInstancesInfo.forEach(function (k, v) {
  44187. v.dispose();
  44188. });
  44189. this._renderGroupInstancesInfo = null;
  44190. }
  44191. if (this._cacheNodeUVsChangedObservable) {
  44192. this._cacheNodeUVsChangedObservable.clear();
  44193. this._cacheNodeUVsChangedObservable = null;
  44194. }
  44195. if (this._transparentSegments) {
  44196. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  44197. var ts = _a[_i];
  44198. ts.dispose(engine);
  44199. }
  44200. this._transparentSegments.splice(0);
  44201. this._transparentSegments = null;
  44202. }
  44203. };
  44204. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  44205. var tpi = new TransparentPrimitiveInfo();
  44206. tpi._primitive = prim;
  44207. tpi._groupInstanceInfo = gii;
  44208. tpi._transparentSegment = null;
  44209. this._transparentPrimitives.push(tpi);
  44210. this._transparentListChanged = true;
  44211. return tpi;
  44212. };
  44213. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  44214. var index = this._transparentPrimitives.indexOf(tpi);
  44215. if (index !== -1) {
  44216. this._transparentPrimitives.splice(index, 1);
  44217. this._transparentListChanged = true;
  44218. }
  44219. };
  44220. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  44221. this._transparentListChanged = true;
  44222. //this.updateSmallestZChangedPrim(tpi);
  44223. };
  44224. return RenderableGroupData;
  44225. })();
  44226. BABYLON.RenderableGroupData = RenderableGroupData;
  44227. var TransparentPrimitiveInfo = (function () {
  44228. function TransparentPrimitiveInfo() {
  44229. }
  44230. return TransparentPrimitiveInfo;
  44231. })();
  44232. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  44233. })(BABYLON || (BABYLON = {}));
  44234. var BABYLON;
  44235. (function (BABYLON) {
  44236. var Rectangle2DRenderCache = (function (_super) {
  44237. __extends(Rectangle2DRenderCache, _super);
  44238. function Rectangle2DRenderCache(engine, modelKey) {
  44239. _super.call(this, engine, modelKey);
  44240. this.effectsReady = false;
  44241. this.fillVB = null;
  44242. this.fillIB = null;
  44243. this.fillIndicesCount = 0;
  44244. this.instancingFillAttributes = null;
  44245. this.effectFill = null;
  44246. this.effectFillInstanced = null;
  44247. this.borderVB = null;
  44248. this.borderIB = null;
  44249. this.borderIndicesCount = 0;
  44250. this.instancingBorderAttributes = null;
  44251. this.effectBorder = null;
  44252. this.effectBorderInstanced = null;
  44253. }
  44254. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  44255. // Do nothing if the shader is still loading/preparing
  44256. if (!this.effectsReady) {
  44257. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44258. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44259. return false;
  44260. }
  44261. this.effectsReady = true;
  44262. }
  44263. var canvas = instanceInfo.owner.owner;
  44264. var engine = canvas.engine;
  44265. var depthFunction = 0;
  44266. if (this.effectFill && this.effectBorder) {
  44267. depthFunction = engine.getDepthFunction();
  44268. engine.setDepthFunctionToLessOrEqual();
  44269. }
  44270. var curAlphaMode = engine.getAlphaMode();
  44271. if (this.effectFill) {
  44272. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44273. var pid = context.groupInfoPartData[partIndex];
  44274. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44275. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44276. }
  44277. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44278. engine.enableEffect(effect);
  44279. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  44280. if (context.useInstancing) {
  44281. if (!this.instancingFillAttributes) {
  44282. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44283. }
  44284. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44285. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44286. canvas._addDrawCallCount(1, context.renderMode);
  44287. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44288. engine.draw(true, 0, this.fillIndicesCount, count);
  44289. engine.unbindInstanceAttributes();
  44290. }
  44291. else {
  44292. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44293. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44294. this.setupUniforms(effect, partIndex, pid._partData, i);
  44295. engine.draw(true, 0, this.fillIndicesCount);
  44296. }
  44297. }
  44298. }
  44299. if (this.effectBorder) {
  44300. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44301. var pid = context.groupInfoPartData[partIndex];
  44302. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44303. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44304. }
  44305. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44306. engine.enableEffect(effect);
  44307. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  44308. if (context.useInstancing) {
  44309. if (!this.instancingBorderAttributes) {
  44310. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44311. }
  44312. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44313. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44314. canvas._addDrawCallCount(1, context.renderMode);
  44315. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44316. engine.draw(true, 0, this.borderIndicesCount, count);
  44317. engine.unbindInstanceAttributes();
  44318. }
  44319. else {
  44320. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44321. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44322. this.setupUniforms(effect, partIndex, pid._partData, i);
  44323. engine.draw(true, 0, this.borderIndicesCount);
  44324. }
  44325. }
  44326. }
  44327. engine.setAlphaMode(curAlphaMode, true);
  44328. if (this.effectFill && this.effectBorder) {
  44329. engine.setDepthFunction(depthFunction);
  44330. }
  44331. return true;
  44332. };
  44333. Rectangle2DRenderCache.prototype.dispose = function () {
  44334. if (!_super.prototype.dispose.call(this)) {
  44335. return false;
  44336. }
  44337. if (this.fillVB) {
  44338. this._engine._releaseBuffer(this.fillVB);
  44339. this.fillVB = null;
  44340. }
  44341. if (this.fillIB) {
  44342. this._engine._releaseBuffer(this.fillIB);
  44343. this.fillIB = null;
  44344. }
  44345. this.effectFill = null;
  44346. this.effectFillInstanced = null;
  44347. this.effectBorder = null;
  44348. this.effectBorderInstanced = null;
  44349. if (this.borderVB) {
  44350. this._engine._releaseBuffer(this.borderVB);
  44351. this.borderVB = null;
  44352. }
  44353. if (this.borderIB) {
  44354. this._engine._releaseBuffer(this.borderIB);
  44355. this.borderIB = null;
  44356. }
  44357. return true;
  44358. };
  44359. return Rectangle2DRenderCache;
  44360. })(BABYLON.ModelRenderCache);
  44361. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  44362. var Rectangle2DInstanceData = (function (_super) {
  44363. __extends(Rectangle2DInstanceData, _super);
  44364. function Rectangle2DInstanceData(partId) {
  44365. _super.call(this, partId, 1);
  44366. }
  44367. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  44368. get: function () {
  44369. return null;
  44370. },
  44371. enumerable: true,
  44372. configurable: true
  44373. });
  44374. __decorate([
  44375. BABYLON.instanceData()
  44376. ], Rectangle2DInstanceData.prototype, "properties", null);
  44377. return Rectangle2DInstanceData;
  44378. })(BABYLON.Shape2DInstanceData);
  44379. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  44380. var Rectangle2D = (function (_super) {
  44381. __extends(Rectangle2D, _super);
  44382. /**
  44383. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  44384. * @param settings a combination of settings, possible ones are
  44385. * - 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)
  44386. * - children: an array of direct children
  44387. * - id a text identifier, for information purpose
  44388. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  44389. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44390. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44391. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44392. * - zOrder: override the zOrder with the specified value
  44393. * - origin: define the normalized origin point location, default [0.5;0.5]
  44394. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  44395. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  44396. * - 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)
  44397. * - 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)
  44398. * - borderThickness: the thickness of the drawn border, default is 1.
  44399. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  44400. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  44401. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  44402. * - 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!
  44403. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44404. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44405. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44406. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44407. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44408. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44409. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44410. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44411. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44412. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44413. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44414. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44415. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44416. */
  44417. function Rectangle2D(settings) {
  44418. // Avoid checking every time if the object exists
  44419. if (settings == null) {
  44420. settings = {};
  44421. }
  44422. _super.call(this, settings);
  44423. if (settings.size != null) {
  44424. this.size = settings.size;
  44425. }
  44426. else if (settings.width || settings.height) {
  44427. var size = new BABYLON.Size(settings.width, settings.height);
  44428. this.size = size;
  44429. }
  44430. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  44431. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  44432. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  44433. //this.size = size;
  44434. this.roundRadius = roundRadius;
  44435. this.borderThickness = borderThickness;
  44436. }
  44437. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  44438. get: function () {
  44439. if (this._actualSize) {
  44440. return this._actualSize;
  44441. }
  44442. return this.size;
  44443. },
  44444. set: function (value) {
  44445. this._actualSize = value;
  44446. },
  44447. enumerable: true,
  44448. configurable: true
  44449. });
  44450. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  44451. get: function () {
  44452. return this._notRounded;
  44453. },
  44454. set: function (value) {
  44455. this._notRounded = value;
  44456. },
  44457. enumerable: true,
  44458. configurable: true
  44459. });
  44460. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  44461. get: function () {
  44462. return this._roundRadius;
  44463. },
  44464. set: function (value) {
  44465. this._roundRadius = value;
  44466. this.notRounded = value === 0;
  44467. this._positioningDirty();
  44468. },
  44469. enumerable: true,
  44470. configurable: true
  44471. });
  44472. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  44473. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  44474. if (this.notRounded) {
  44475. return true;
  44476. }
  44477. // 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.
  44478. // 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)
  44479. // 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.
  44480. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  44481. var size = this.size;
  44482. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  44483. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  44484. var rr = this.roundRadius;
  44485. var rrs = rr * rr;
  44486. // Check if the point is in the bottom/left quarter area
  44487. Rectangle2D._i1.x = rr;
  44488. Rectangle2D._i1.y = rr;
  44489. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  44490. // Compute the intersection point in the quarter local space
  44491. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44492. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44493. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44494. return Rectangle2D._i2.lengthSquared() <= rrs;
  44495. }
  44496. // Check if the point is in the top/left quarter area
  44497. Rectangle2D._i1.x = rr;
  44498. Rectangle2D._i1.y = size.height - rr;
  44499. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  44500. // Compute the intersection point in the quarter local space
  44501. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44502. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44503. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44504. return Rectangle2D._i2.lengthSquared() <= rrs;
  44505. }
  44506. // Check if the point is in the top/right quarter area
  44507. Rectangle2D._i1.x = size.width - rr;
  44508. Rectangle2D._i1.y = size.height - rr;
  44509. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  44510. // Compute the intersection point in the quarter local space
  44511. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44512. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44513. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44514. return Rectangle2D._i2.lengthSquared() <= rrs;
  44515. }
  44516. // Check if the point is in the bottom/right quarter area
  44517. Rectangle2D._i1.x = size.width - rr;
  44518. Rectangle2D._i1.y = rr;
  44519. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  44520. // Compute the intersection point in the quarter local space
  44521. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44522. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44523. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44524. return Rectangle2D._i2.lengthSquared() <= rrs;
  44525. }
  44526. // At any other locations the point is guarantied to be inside
  44527. return true;
  44528. };
  44529. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  44530. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44531. };
  44532. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  44533. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  44534. return renderCache;
  44535. };
  44536. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44537. var renderCache = modelRenderCache;
  44538. var engine = this.owner.engine;
  44539. // Need to create WebGL resources for fill part?
  44540. if (this.fill) {
  44541. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  44542. var vb = new Float32Array(vbSize);
  44543. for (var i = 0; i < vbSize; i++) {
  44544. vb[i] = i;
  44545. }
  44546. renderCache.fillVB = engine.createVertexBuffer(vb);
  44547. var triCount = vbSize - 1;
  44548. var ib = new Float32Array(triCount * 3);
  44549. for (var i = 0; i < triCount; i++) {
  44550. ib[i * 3 + 0] = 0;
  44551. ib[i * 3 + 2] = i + 1;
  44552. ib[i * 3 + 1] = i + 2;
  44553. }
  44554. ib[triCount * 3 - 2] = 1;
  44555. renderCache.fillIB = engine.createIndexBuffer(ib);
  44556. renderCache.fillIndicesCount = triCount * 3;
  44557. // 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
  44558. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  44559. if (ei) {
  44560. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44561. }
  44562. // Get the non instanced version
  44563. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  44564. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44565. }
  44566. // Need to create WebGL resource for border part?
  44567. if (this.border) {
  44568. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  44569. var vb = new Float32Array(vbSize);
  44570. for (var i = 0; i < vbSize; i++) {
  44571. vb[i] = i;
  44572. }
  44573. renderCache.borderVB = engine.createVertexBuffer(vb);
  44574. var triCount = vbSize;
  44575. var rs = triCount / 2;
  44576. var ib = new Float32Array(triCount * 3);
  44577. for (var i = 0; i < rs; i++) {
  44578. var r0 = i;
  44579. var r1 = (i + 1) % rs;
  44580. ib[i * 6 + 0] = rs + r1;
  44581. ib[i * 6 + 1] = rs + r0;
  44582. ib[i * 6 + 2] = r0;
  44583. ib[i * 6 + 3] = r1;
  44584. ib[i * 6 + 4] = rs + r1;
  44585. ib[i * 6 + 5] = r0;
  44586. }
  44587. renderCache.borderIB = engine.createIndexBuffer(ib);
  44588. renderCache.borderIndicesCount = triCount * 3;
  44589. // 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
  44590. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  44591. if (ei) {
  44592. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44593. }
  44594. // Get the non instanced version
  44595. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  44596. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44597. }
  44598. return renderCache;
  44599. };
  44600. // 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
  44601. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  44602. // Fall back to default implementation if there's no round Radius
  44603. if (this._notRounded) {
  44604. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  44605. }
  44606. else {
  44607. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  44608. initialContentPosition.x = initialContentPosition.y = rr;
  44609. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  44610. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  44611. }
  44612. };
  44613. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  44614. // Fall back to default implementation if there's no round Radius
  44615. if (this._notRounded) {
  44616. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  44617. }
  44618. else {
  44619. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  44620. newPrimSize.copyFrom(primSize);
  44621. newPrimSize.width += rr * 2;
  44622. newPrimSize.height += rr * 2;
  44623. }
  44624. };
  44625. Rectangle2D.prototype.createInstanceDataParts = function () {
  44626. var res = new Array();
  44627. if (this.border) {
  44628. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  44629. }
  44630. if (this.fill) {
  44631. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  44632. }
  44633. return res;
  44634. };
  44635. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  44636. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44637. return false;
  44638. }
  44639. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  44640. var d = part;
  44641. var size = this.actualSize;
  44642. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  44643. }
  44644. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  44645. var d = part;
  44646. var size = this.actualSize;
  44647. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  44648. }
  44649. return true;
  44650. };
  44651. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  44652. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  44653. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  44654. Rectangle2D.roundSubdivisions = 16;
  44655. __decorate([
  44656. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  44657. ], Rectangle2D.prototype, "actualSize", null);
  44658. __decorate([
  44659. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  44660. ], Rectangle2D.prototype, "notRounded", null);
  44661. __decorate([
  44662. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  44663. ], Rectangle2D.prototype, "roundRadius", null);
  44664. Rectangle2D = __decorate([
  44665. BABYLON.className("Rectangle2D")
  44666. ], Rectangle2D);
  44667. return Rectangle2D;
  44668. })(BABYLON.Shape2D);
  44669. BABYLON.Rectangle2D = Rectangle2D;
  44670. })(BABYLON || (BABYLON = {}));
  44671. var BABYLON;
  44672. (function (BABYLON) {
  44673. var Ellipse2DRenderCache = (function (_super) {
  44674. __extends(Ellipse2DRenderCache, _super);
  44675. function Ellipse2DRenderCache(engine, modelKey) {
  44676. _super.call(this, engine, modelKey);
  44677. this.effectsReady = false;
  44678. this.fillVB = null;
  44679. this.fillIB = null;
  44680. this.fillIndicesCount = 0;
  44681. this.instancingFillAttributes = null;
  44682. this.effectFillInstanced = null;
  44683. this.effectFill = null;
  44684. this.borderVB = null;
  44685. this.borderIB = null;
  44686. this.borderIndicesCount = 0;
  44687. this.instancingBorderAttributes = null;
  44688. this.effectBorderInstanced = null;
  44689. this.effectBorder = null;
  44690. }
  44691. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  44692. // Do nothing if the shader is still loading/preparing
  44693. if (!this.effectsReady) {
  44694. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44695. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44696. return false;
  44697. }
  44698. this.effectsReady = true;
  44699. }
  44700. var canvas = instanceInfo.owner.owner;
  44701. var engine = canvas.engine;
  44702. var depthFunction = 0;
  44703. if (this.effectFill && this.effectBorder) {
  44704. depthFunction = engine.getDepthFunction();
  44705. engine.setDepthFunctionToLessOrEqual();
  44706. }
  44707. var curAlphaMode = engine.getAlphaMode();
  44708. if (this.effectFill) {
  44709. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44710. var pid = context.groupInfoPartData[partIndex];
  44711. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44712. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44713. }
  44714. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44715. engine.enableEffect(effect);
  44716. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  44717. if (context.useInstancing) {
  44718. if (!this.instancingFillAttributes) {
  44719. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44720. }
  44721. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44722. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44723. canvas._addDrawCallCount(1, context.renderMode);
  44724. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44725. engine.draw(true, 0, this.fillIndicesCount, count);
  44726. engine.unbindInstanceAttributes();
  44727. }
  44728. else {
  44729. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44730. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44731. this.setupUniforms(effect, partIndex, pid._partData, i);
  44732. engine.draw(true, 0, this.fillIndicesCount);
  44733. }
  44734. }
  44735. }
  44736. if (this.effectBorder) {
  44737. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44738. var pid = context.groupInfoPartData[partIndex];
  44739. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44740. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44741. }
  44742. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44743. engine.enableEffect(effect);
  44744. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  44745. if (context.useInstancing) {
  44746. if (!this.instancingBorderAttributes) {
  44747. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44748. }
  44749. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44750. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44751. canvas._addDrawCallCount(1, context.renderMode);
  44752. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44753. engine.draw(true, 0, this.borderIndicesCount, count);
  44754. engine.unbindInstanceAttributes();
  44755. }
  44756. else {
  44757. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44758. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44759. this.setupUniforms(effect, partIndex, pid._partData, i);
  44760. engine.draw(true, 0, this.borderIndicesCount);
  44761. }
  44762. }
  44763. }
  44764. engine.setAlphaMode(curAlphaMode, true);
  44765. if (this.effectFill && this.effectBorder) {
  44766. engine.setDepthFunction(depthFunction);
  44767. }
  44768. return true;
  44769. };
  44770. Ellipse2DRenderCache.prototype.dispose = function () {
  44771. if (!_super.prototype.dispose.call(this)) {
  44772. return false;
  44773. }
  44774. if (this.fillVB) {
  44775. this._engine._releaseBuffer(this.fillVB);
  44776. this.fillVB = null;
  44777. }
  44778. if (this.fillIB) {
  44779. this._engine._releaseBuffer(this.fillIB);
  44780. this.fillIB = null;
  44781. }
  44782. this.effectFill = null;
  44783. this.effectFillInstanced = null;
  44784. this.effectBorder = null;
  44785. this.effectBorderInstanced = null;
  44786. if (this.borderVB) {
  44787. this._engine._releaseBuffer(this.borderVB);
  44788. this.borderVB = null;
  44789. }
  44790. if (this.borderIB) {
  44791. this._engine._releaseBuffer(this.borderIB);
  44792. this.borderIB = null;
  44793. }
  44794. return true;
  44795. };
  44796. return Ellipse2DRenderCache;
  44797. })(BABYLON.ModelRenderCache);
  44798. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  44799. var Ellipse2DInstanceData = (function (_super) {
  44800. __extends(Ellipse2DInstanceData, _super);
  44801. function Ellipse2DInstanceData(partId) {
  44802. _super.call(this, partId, 1);
  44803. }
  44804. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  44805. get: function () {
  44806. return null;
  44807. },
  44808. enumerable: true,
  44809. configurable: true
  44810. });
  44811. __decorate([
  44812. BABYLON.instanceData()
  44813. ], Ellipse2DInstanceData.prototype, "properties", null);
  44814. return Ellipse2DInstanceData;
  44815. })(BABYLON.Shape2DInstanceData);
  44816. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  44817. var Ellipse2D = (function (_super) {
  44818. __extends(Ellipse2D, _super);
  44819. /**
  44820. * Create an Ellipse 2D Shape primitive
  44821. * @param settings a combination of settings, possible ones are
  44822. * - 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)
  44823. * - children: an array of direct children
  44824. * - id: a text identifier, for information purpose
  44825. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44826. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44827. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44828. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44829. * - zOrder: override the zOrder with the specified value
  44830. * - origin: define the normalized origin point location, default [0.5;0.5]
  44831. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  44832. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  44833. * - 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)
  44834. * - 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)
  44835. * - borderThickness: the thickness of the drawn border, default is 1.
  44836. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  44837. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  44838. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  44839. * - 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!
  44840. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44841. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44842. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44843. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44844. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44845. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44846. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44847. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44848. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44849. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44850. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44851. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44852. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44853. */
  44854. function Ellipse2D(settings) {
  44855. // Avoid checking every time if the object exists
  44856. if (settings == null) {
  44857. settings = {};
  44858. }
  44859. _super.call(this, settings);
  44860. if (settings.size != null) {
  44861. this.size = settings.size;
  44862. }
  44863. else if (settings.width || settings.height) {
  44864. var size = new BABYLON.Size(settings.width, settings.height);
  44865. this.size = size;
  44866. }
  44867. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  44868. this.subdivisions = sub;
  44869. }
  44870. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  44871. get: function () {
  44872. if (this._actualSize) {
  44873. return this._actualSize;
  44874. }
  44875. return this.size;
  44876. },
  44877. set: function (value) {
  44878. this._actualSize = value;
  44879. },
  44880. enumerable: true,
  44881. configurable: true
  44882. });
  44883. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  44884. get: function () {
  44885. return this._subdivisions;
  44886. },
  44887. set: function (value) {
  44888. this._subdivisions = value;
  44889. },
  44890. enumerable: true,
  44891. configurable: true
  44892. });
  44893. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  44894. var w = this.size.width / 2;
  44895. var h = this.size.height / 2;
  44896. var x = intersectInfo._localPickPosition.x - w;
  44897. var y = intersectInfo._localPickPosition.y - h;
  44898. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  44899. };
  44900. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  44901. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44902. };
  44903. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  44904. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  44905. return renderCache;
  44906. };
  44907. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44908. var renderCache = modelRenderCache;
  44909. var engine = this.owner.engine;
  44910. // Need to create WebGL resources for fill part?
  44911. if (this.fill) {
  44912. var vbSize = this.subdivisions + 1;
  44913. var vb = new Float32Array(vbSize);
  44914. for (var i = 0; i < vbSize; i++) {
  44915. vb[i] = i;
  44916. }
  44917. renderCache.fillVB = engine.createVertexBuffer(vb);
  44918. var triCount = vbSize - 1;
  44919. var ib = new Float32Array(triCount * 3);
  44920. for (var i = 0; i < triCount; i++) {
  44921. ib[i * 3 + 0] = 0;
  44922. ib[i * 3 + 2] = i + 1;
  44923. ib[i * 3 + 1] = i + 2;
  44924. }
  44925. ib[triCount * 3 - 2] = 1;
  44926. renderCache.fillIB = engine.createIndexBuffer(ib);
  44927. renderCache.fillIndicesCount = triCount * 3;
  44928. // 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
  44929. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  44930. if (ei) {
  44931. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44932. }
  44933. // Get the non instanced version
  44934. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  44935. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44936. }
  44937. // Need to create WebGL resource for border part?
  44938. if (this.border) {
  44939. var vbSize = this.subdivisions * 2;
  44940. var vb = new Float32Array(vbSize);
  44941. for (var i = 0; i < vbSize; i++) {
  44942. vb[i] = i;
  44943. }
  44944. renderCache.borderVB = engine.createVertexBuffer(vb);
  44945. var triCount = vbSize;
  44946. var rs = triCount / 2;
  44947. var ib = new Float32Array(triCount * 3);
  44948. for (var i = 0; i < rs; i++) {
  44949. var r0 = i;
  44950. var r1 = (i + 1) % rs;
  44951. ib[i * 6 + 0] = rs + r1;
  44952. ib[i * 6 + 1] = rs + r0;
  44953. ib[i * 6 + 2] = r0;
  44954. ib[i * 6 + 3] = r1;
  44955. ib[i * 6 + 4] = rs + r1;
  44956. ib[i * 6 + 5] = r0;
  44957. }
  44958. renderCache.borderIB = engine.createIndexBuffer(ib);
  44959. renderCache.borderIndicesCount = (triCount * 3);
  44960. // 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
  44961. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  44962. if (ei) {
  44963. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44964. }
  44965. // Get the non instanced version
  44966. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  44967. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44968. }
  44969. return renderCache;
  44970. };
  44971. Ellipse2D.prototype.createInstanceDataParts = function () {
  44972. var res = new Array();
  44973. if (this.border) {
  44974. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  44975. }
  44976. if (this.fill) {
  44977. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  44978. }
  44979. return res;
  44980. };
  44981. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  44982. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44983. return false;
  44984. }
  44985. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  44986. var d = part;
  44987. var size = this.actualSize;
  44988. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  44989. }
  44990. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  44991. var d = part;
  44992. var size = this.actualSize;
  44993. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  44994. }
  44995. return true;
  44996. };
  44997. __decorate([
  44998. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  44999. ], Ellipse2D.prototype, "actualSize", null);
  45000. __decorate([
  45001. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  45002. ], Ellipse2D.prototype, "subdivisions", null);
  45003. Ellipse2D = __decorate([
  45004. BABYLON.className("Ellipse2D")
  45005. ], Ellipse2D);
  45006. return Ellipse2D;
  45007. })(BABYLON.Shape2D);
  45008. BABYLON.Ellipse2D = Ellipse2D;
  45009. })(BABYLON || (BABYLON = {}));
  45010. var BABYLON;
  45011. (function (BABYLON) {
  45012. var Sprite2DRenderCache = (function (_super) {
  45013. __extends(Sprite2DRenderCache, _super);
  45014. function Sprite2DRenderCache() {
  45015. _super.apply(this, arguments);
  45016. this.effectsReady = false;
  45017. this.vb = null;
  45018. this.ib = null;
  45019. this.instancingAttributes = null;
  45020. this.texture = null;
  45021. this.effect = null;
  45022. this.effectInstanced = null;
  45023. }
  45024. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  45025. // Do nothing if the shader is still loading/preparing
  45026. if (!this.effectsReady) {
  45027. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  45028. return false;
  45029. }
  45030. this.effectsReady = true;
  45031. }
  45032. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  45033. var canvas = instanceInfo.owner.owner;
  45034. var engine = canvas.engine;
  45035. var cur = engine.getAlphaMode();
  45036. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  45037. engine.enableEffect(effect);
  45038. effect.setTexture("diffuseSampler", this.texture);
  45039. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  45040. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45041. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45042. }
  45043. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  45044. var pid = context.groupInfoPartData[0];
  45045. if (context.useInstancing) {
  45046. if (!this.instancingAttributes) {
  45047. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  45048. }
  45049. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  45050. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45051. canvas._addDrawCallCount(1, context.renderMode);
  45052. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  45053. engine.draw(true, 0, 6, count);
  45054. engine.unbindInstanceAttributes();
  45055. }
  45056. else {
  45057. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45058. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45059. this.setupUniforms(effect, 0, pid._partData, i);
  45060. engine.draw(true, 0, 6);
  45061. }
  45062. }
  45063. engine.setAlphaMode(cur, true);
  45064. return true;
  45065. };
  45066. Sprite2DRenderCache.prototype.dispose = function () {
  45067. if (!_super.prototype.dispose.call(this)) {
  45068. return false;
  45069. }
  45070. if (this.vb) {
  45071. this._engine._releaseBuffer(this.vb);
  45072. this.vb = null;
  45073. }
  45074. if (this.ib) {
  45075. this._engine._releaseBuffer(this.ib);
  45076. this.ib = null;
  45077. }
  45078. //if (this.texture) {
  45079. // this.texture.dispose();
  45080. // this.texture = null;
  45081. //}
  45082. this.effect = null;
  45083. this.effectInstanced = null;
  45084. return true;
  45085. };
  45086. return Sprite2DRenderCache;
  45087. })(BABYLON.ModelRenderCache);
  45088. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  45089. var Sprite2DInstanceData = (function (_super) {
  45090. __extends(Sprite2DInstanceData, _super);
  45091. function Sprite2DInstanceData(partId) {
  45092. _super.call(this, partId, 1);
  45093. }
  45094. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  45095. get: function () {
  45096. return null;
  45097. },
  45098. enumerable: true,
  45099. configurable: true
  45100. });
  45101. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  45102. get: function () {
  45103. return null;
  45104. },
  45105. enumerable: true,
  45106. configurable: true
  45107. });
  45108. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  45109. get: function () {
  45110. return null;
  45111. },
  45112. enumerable: true,
  45113. configurable: true
  45114. });
  45115. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  45116. get: function () {
  45117. return null;
  45118. },
  45119. enumerable: true,
  45120. configurable: true
  45121. });
  45122. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  45123. // 3 floats being:
  45124. // - x: frame number to display
  45125. // - y: invertY setting
  45126. // - z: alignToPixel setting
  45127. get: function () {
  45128. return null;
  45129. },
  45130. enumerable: true,
  45131. configurable: true
  45132. });
  45133. __decorate([
  45134. BABYLON.instanceData()
  45135. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  45136. __decorate([
  45137. BABYLON.instanceData()
  45138. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  45139. __decorate([
  45140. BABYLON.instanceData()
  45141. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  45142. __decorate([
  45143. BABYLON.instanceData()
  45144. ], Sprite2DInstanceData.prototype, "textureSize", null);
  45145. __decorate([
  45146. BABYLON.instanceData()
  45147. ], Sprite2DInstanceData.prototype, "properties", null);
  45148. return Sprite2DInstanceData;
  45149. })(BABYLON.InstanceDataBase);
  45150. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  45151. var Sprite2D = (function (_super) {
  45152. __extends(Sprite2D, _super);
  45153. /**
  45154. * Create an 2D Sprite primitive
  45155. * @param texture the texture that stores the sprite to render
  45156. * @param settings a combination of settings, possible ones are
  45157. * - 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)
  45158. * - children: an array of direct children
  45159. * - id a text identifier, for information purpose
  45160. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45161. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45162. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45163. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45164. * - zOrder: override the zOrder with the specified value
  45165. * - origin: define the normalized origin point location, default [0.5;0.5]
  45166. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  45167. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  45168. * - 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.
  45169. * - invertY: if true the texture Y will be inverted, default is false.
  45170. * - 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.
  45171. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  45172. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  45173. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  45174. * - 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!
  45175. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45176. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45177. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45178. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45179. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45180. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45181. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45182. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45183. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45184. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45185. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45186. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45187. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45188. */
  45189. function Sprite2D(texture, settings) {
  45190. var _this = this;
  45191. if (!settings) {
  45192. settings = {};
  45193. }
  45194. _super.call(this, settings);
  45195. this.texture = texture;
  45196. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45197. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45198. this.size = settings.spriteSize;
  45199. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  45200. this.spriteScaleFactor = settings.spriteScaleFactor || new BABYLON.Vector2(1, 1);
  45201. this.spriteFrame = 0;
  45202. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  45203. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  45204. this.useAlphaFromTexture = true;
  45205. if (settings.spriteSize == null || !texture.isReady()) {
  45206. if (texture.isReady()) {
  45207. this.size = texture.getBaseSize();
  45208. }
  45209. else {
  45210. texture.onLoadObservable.add(function () {
  45211. if (settings.spriteSize == null) {
  45212. _this.size = texture.getBaseSize();
  45213. }
  45214. _this._positioningDirty();
  45215. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D.textureProperty.flagId; // To make sure the sprite is issued again for render
  45216. });
  45217. }
  45218. }
  45219. }
  45220. Object.defineProperty(Sprite2D.prototype, "texture", {
  45221. get: function () {
  45222. return this._texture;
  45223. },
  45224. set: function (value) {
  45225. this._texture = value;
  45226. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  45227. },
  45228. enumerable: true,
  45229. configurable: true
  45230. });
  45231. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  45232. get: function () {
  45233. return this._useAlphaFromTexture;
  45234. },
  45235. set: function (value) {
  45236. if (this._useAlphaFromTexture === value) {
  45237. return;
  45238. }
  45239. this._useAlphaFromTexture = value;
  45240. this._updateRenderMode();
  45241. },
  45242. enumerable: true,
  45243. configurable: true
  45244. });
  45245. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  45246. get: function () {
  45247. if (this._actualSize) {
  45248. return this._actualSize;
  45249. }
  45250. return this.size;
  45251. },
  45252. set: function (value) {
  45253. this._actualSize = value;
  45254. },
  45255. enumerable: true,
  45256. configurable: true
  45257. });
  45258. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  45259. get: function () {
  45260. return this._location;
  45261. },
  45262. set: function (value) {
  45263. this._location = value;
  45264. },
  45265. enumerable: true,
  45266. configurable: true
  45267. });
  45268. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  45269. get: function () {
  45270. return this._spriteFrame;
  45271. },
  45272. set: function (value) {
  45273. this._spriteFrame = value;
  45274. },
  45275. enumerable: true,
  45276. configurable: true
  45277. });
  45278. Object.defineProperty(Sprite2D.prototype, "invertY", {
  45279. get: function () {
  45280. return this._invertY;
  45281. },
  45282. set: function (value) {
  45283. this._invertY = value;
  45284. },
  45285. enumerable: true,
  45286. configurable: true
  45287. });
  45288. Object.defineProperty(Sprite2D.prototype, "spriteScaleFactor", {
  45289. get: function () {
  45290. return this._spriteScaleFactor;
  45291. },
  45292. set: function (value) {
  45293. this._spriteScaleFactor = value;
  45294. },
  45295. enumerable: true,
  45296. configurable: true
  45297. });
  45298. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  45299. /**
  45300. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  45301. */
  45302. get: function () {
  45303. return this._alignToPixel;
  45304. },
  45305. set: function (value) {
  45306. this._alignToPixel = value;
  45307. },
  45308. enumerable: true,
  45309. configurable: true
  45310. });
  45311. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  45312. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  45313. };
  45314. /**
  45315. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  45316. */
  45317. Sprite2D.prototype.getAnimatables = function () {
  45318. var res = new Array();
  45319. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  45320. res.push(this.texture);
  45321. }
  45322. return res;
  45323. };
  45324. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  45325. // 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
  45326. return true;
  45327. };
  45328. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  45329. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  45330. return sprite;
  45331. };
  45332. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  45333. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  45334. return renderCache;
  45335. };
  45336. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45337. var renderCache = modelRenderCache;
  45338. var engine = this.owner.engine;
  45339. var vb = new Float32Array(4);
  45340. for (var i = 0; i < 4; i++) {
  45341. vb[i] = i;
  45342. }
  45343. renderCache.vb = engine.createVertexBuffer(vb);
  45344. var ib = new Float32Array(6);
  45345. ib[0] = 0;
  45346. ib[1] = 2;
  45347. ib[2] = 1;
  45348. ib[3] = 0;
  45349. ib[4] = 3;
  45350. ib[5] = 2;
  45351. renderCache.ib = engine.createIndexBuffer(ib);
  45352. renderCache.texture = this.texture;
  45353. // 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
  45354. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  45355. if (ei) {
  45356. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45357. }
  45358. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  45359. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45360. return renderCache;
  45361. };
  45362. Sprite2D.prototype.createInstanceDataParts = function () {
  45363. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  45364. };
  45365. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  45366. Sprite2D.layoutConstructMode = true;
  45367. };
  45368. // if obj contains something, we restore the _text property
  45369. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  45370. Sprite2D.layoutConstructMode = false;
  45371. };
  45372. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  45373. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45374. return false;
  45375. }
  45376. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  45377. return false;
  45378. }
  45379. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  45380. var d = this._instanceDataParts[0];
  45381. if (Sprite2D.layoutConstructMode) {
  45382. d.topLeftUV = BABYLON.Vector2.Zero();
  45383. d.sizeUV = BABYLON.Vector2.Zero();
  45384. d.properties = BABYLON.Vector3.Zero();
  45385. d.textureSize = BABYLON.Vector2.Zero();
  45386. d.scaleFactor = BABYLON.Vector2.Zero();
  45387. }
  45388. else {
  45389. var ts = this.texture.getBaseSize();
  45390. var sl = this.spriteLocation;
  45391. var ss = this.actualSize;
  45392. var ssf = this.spriteScaleFactor;
  45393. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  45394. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  45395. d.sizeUV = suv;
  45396. d.scaleFactor = ssf;
  45397. Sprite2D._prop.x = this.spriteFrame;
  45398. Sprite2D._prop.y = this.invertY ? 1 : 0;
  45399. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  45400. d.properties = Sprite2D._prop;
  45401. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  45402. }
  45403. }
  45404. return true;
  45405. };
  45406. Sprite2D.prototype._mustUpdateInstance = function () {
  45407. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  45408. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  45409. if (res) {
  45410. this._updateRenderMode();
  45411. }
  45412. return res;
  45413. };
  45414. Sprite2D.prototype._useTextureAlpha = function () {
  45415. return this.texture != null && this.texture.hasAlpha;
  45416. };
  45417. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  45418. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  45419. };
  45420. Sprite2D.SPRITE2D_MAINPARTID = 1;
  45421. Sprite2D._prop = BABYLON.Vector3.Zero();
  45422. Sprite2D.layoutConstructMode = false;
  45423. __decorate([
  45424. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  45425. ], Sprite2D.prototype, "texture", null);
  45426. __decorate([
  45427. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.useAlphaFromTextureProperty = pi; })
  45428. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  45429. __decorate([
  45430. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  45431. ], Sprite2D.prototype, "actualSize", null);
  45432. __decorate([
  45433. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  45434. ], Sprite2D.prototype, "spriteLocation", null);
  45435. __decorate([
  45436. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  45437. ], Sprite2D.prototype, "spriteFrame", null);
  45438. __decorate([
  45439. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D.invertYProperty = pi; })
  45440. ], Sprite2D.prototype, "invertY", null);
  45441. __decorate([
  45442. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D.spriteScaleFactorProperty = pi; })
  45443. ], Sprite2D.prototype, "spriteScaleFactor", null);
  45444. Sprite2D = __decorate([
  45445. BABYLON.className("Sprite2D")
  45446. ], Sprite2D);
  45447. return Sprite2D;
  45448. })(BABYLON.RenderablePrim2D);
  45449. BABYLON.Sprite2D = Sprite2D;
  45450. })(BABYLON || (BABYLON = {}));
  45451. var BABYLON;
  45452. (function (BABYLON) {
  45453. var Text2DRenderCache = (function (_super) {
  45454. __extends(Text2DRenderCache, _super);
  45455. function Text2DRenderCache() {
  45456. _super.apply(this, arguments);
  45457. this.effectsReady = false;
  45458. this.vb = null;
  45459. this.ib = null;
  45460. this.instancingAttributes = null;
  45461. this.fontTexture = null;
  45462. this.effect = null;
  45463. this.effectInstanced = null;
  45464. }
  45465. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  45466. // Do nothing if the shader is still loading/preparing
  45467. if (!this.effectsReady) {
  45468. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  45469. return false;
  45470. }
  45471. this.effectsReady = true;
  45472. }
  45473. var canvas = instanceInfo.owner.owner;
  45474. var engine = canvas.engine;
  45475. this.fontTexture.update();
  45476. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  45477. engine.enableEffect(effect);
  45478. effect.setTexture("diffuseSampler", this.fontTexture);
  45479. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  45480. var curAlphaMode = engine.getAlphaMode();
  45481. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45482. var pid = context.groupInfoPartData[0];
  45483. if (context.useInstancing) {
  45484. if (!this.instancingAttributes) {
  45485. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  45486. }
  45487. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  45488. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45489. canvas._addDrawCallCount(1, context.renderMode);
  45490. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  45491. engine.draw(true, 0, 6, count);
  45492. engine.unbindInstanceAttributes();
  45493. }
  45494. else {
  45495. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45496. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45497. this.setupUniforms(effect, 0, pid._partData, i);
  45498. engine.draw(true, 0, 6);
  45499. }
  45500. }
  45501. engine.setAlphaMode(curAlphaMode, true);
  45502. return true;
  45503. };
  45504. Text2DRenderCache.prototype.dispose = function () {
  45505. if (!_super.prototype.dispose.call(this)) {
  45506. return false;
  45507. }
  45508. if (this.vb) {
  45509. this._engine._releaseBuffer(this.vb);
  45510. this.vb = null;
  45511. }
  45512. if (this.ib) {
  45513. this._engine._releaseBuffer(this.ib);
  45514. this.ib = null;
  45515. }
  45516. if (this.fontTexture) {
  45517. this.fontTexture.decCachedFontTextureCounter();
  45518. this.fontTexture = null;
  45519. }
  45520. this.effect = null;
  45521. this.effectInstanced = null;
  45522. return true;
  45523. };
  45524. return Text2DRenderCache;
  45525. })(BABYLON.ModelRenderCache);
  45526. BABYLON.Text2DRenderCache = Text2DRenderCache;
  45527. var Text2DInstanceData = (function (_super) {
  45528. __extends(Text2DInstanceData, _super);
  45529. function Text2DInstanceData(partId, dataElementCount) {
  45530. _super.call(this, partId, dataElementCount);
  45531. }
  45532. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  45533. get: function () {
  45534. return null;
  45535. },
  45536. enumerable: true,
  45537. configurable: true
  45538. });
  45539. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  45540. get: function () {
  45541. return null;
  45542. },
  45543. enumerable: true,
  45544. configurable: true
  45545. });
  45546. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  45547. get: function () {
  45548. return null;
  45549. },
  45550. enumerable: true,
  45551. configurable: true
  45552. });
  45553. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  45554. get: function () {
  45555. return null;
  45556. },
  45557. enumerable: true,
  45558. configurable: true
  45559. });
  45560. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  45561. get: function () {
  45562. return null;
  45563. },
  45564. enumerable: true,
  45565. configurable: true
  45566. });
  45567. __decorate([
  45568. BABYLON.instanceData()
  45569. ], Text2DInstanceData.prototype, "topLeftUV", null);
  45570. __decorate([
  45571. BABYLON.instanceData()
  45572. ], Text2DInstanceData.prototype, "sizeUV", null);
  45573. __decorate([
  45574. BABYLON.instanceData()
  45575. ], Text2DInstanceData.prototype, "textureSize", null);
  45576. __decorate([
  45577. BABYLON.instanceData()
  45578. ], Text2DInstanceData.prototype, "color", null);
  45579. __decorate([
  45580. BABYLON.instanceData()
  45581. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  45582. return Text2DInstanceData;
  45583. })(BABYLON.InstanceDataBase);
  45584. BABYLON.Text2DInstanceData = Text2DInstanceData;
  45585. var Text2D = (function (_super) {
  45586. __extends(Text2D, _super);
  45587. /**
  45588. * Create a Text primitive
  45589. * @param text the text to display
  45590. * @param settings a combination of settings, possible ones are
  45591. * - 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)
  45592. * - children: an array of direct children
  45593. * - id a text identifier, for information purpose
  45594. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45595. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45596. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45597. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45598. * - zOrder: override the zOrder with the specified value
  45599. * - origin: define the normalized origin point location, default [0.5;0.5]
  45600. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  45601. * - 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.
  45602. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  45603. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  45604. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  45605. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  45606. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  45607. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  45608. * - 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!
  45609. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45610. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45611. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45612. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45613. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45614. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45615. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45616. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45617. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45618. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45619. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45620. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45621. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45622. */
  45623. function Text2D(text, settings) {
  45624. if (!settings) {
  45625. settings = {};
  45626. }
  45627. _super.call(this, settings);
  45628. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  45629. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  45630. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  45631. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  45632. this._textSize = null;
  45633. this.text = text;
  45634. this.size = (settings.size == null) ? null : settings.size;
  45635. this._updateRenderMode();
  45636. }
  45637. Object.defineProperty(Text2D.prototype, "fontName", {
  45638. get: function () {
  45639. return this._fontName;
  45640. },
  45641. set: function (value) {
  45642. if (this._fontName) {
  45643. throw new Error("Font Name change is not supported right now.");
  45644. }
  45645. this._fontName = value;
  45646. },
  45647. enumerable: true,
  45648. configurable: true
  45649. });
  45650. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  45651. get: function () {
  45652. return this._defaultFontColor;
  45653. },
  45654. set: function (value) {
  45655. this._defaultFontColor = value;
  45656. },
  45657. enumerable: true,
  45658. configurable: true
  45659. });
  45660. Object.defineProperty(Text2D.prototype, "text", {
  45661. get: function () {
  45662. return this._text;
  45663. },
  45664. set: function (value) {
  45665. this._text = value;
  45666. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  45667. this._size = null;
  45668. this._updateCharCount();
  45669. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  45670. var s = this.textSize;
  45671. },
  45672. enumerable: true,
  45673. configurable: true
  45674. });
  45675. Object.defineProperty(Text2D.prototype, "size", {
  45676. get: function () {
  45677. if (this._size != null) {
  45678. return this._size;
  45679. }
  45680. return this.textSize;
  45681. },
  45682. set: function (value) {
  45683. this._size = value;
  45684. },
  45685. enumerable: true,
  45686. configurable: true
  45687. });
  45688. Object.defineProperty(Text2D.prototype, "actualSize", {
  45689. /**
  45690. * Get the actual size of the Text2D primitive
  45691. */
  45692. get: function () {
  45693. if (this._actualSize) {
  45694. return this._actualSize;
  45695. }
  45696. return this.size;
  45697. },
  45698. enumerable: true,
  45699. configurable: true
  45700. });
  45701. Object.defineProperty(Text2D.prototype, "textSize", {
  45702. /**
  45703. * Get the area that bounds the text associated to the primitive
  45704. */
  45705. get: function () {
  45706. if (!this._textSize) {
  45707. if (this.owner) {
  45708. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  45709. if (!newSize.equals(this._textSize)) {
  45710. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  45711. this._positioningDirty();
  45712. }
  45713. this._textSize = newSize;
  45714. }
  45715. else {
  45716. return Text2D.nullSize;
  45717. }
  45718. }
  45719. return this._textSize;
  45720. },
  45721. enumerable: true,
  45722. configurable: true
  45723. });
  45724. Object.defineProperty(Text2D.prototype, "fontTexture", {
  45725. get: function () {
  45726. if (this._fontTexture) {
  45727. return this._fontTexture;
  45728. }
  45729. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  45730. return null;
  45731. }
  45732. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  45733. return this._fontTexture;
  45734. },
  45735. enumerable: true,
  45736. configurable: true
  45737. });
  45738. /**
  45739. * Dispose the primitive, remove it from its parent
  45740. */
  45741. Text2D.prototype.dispose = function () {
  45742. if (!_super.prototype.dispose.call(this)) {
  45743. return false;
  45744. }
  45745. if (this._fontTexture) {
  45746. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  45747. this._fontTexture = null;
  45748. }
  45749. return true;
  45750. };
  45751. Text2D.prototype.updateLevelBoundingInfo = function () {
  45752. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  45753. };
  45754. Text2D.prototype.levelIntersect = function (intersectInfo) {
  45755. // 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...
  45756. return true;
  45757. };
  45758. Text2D.prototype.createModelRenderCache = function (modelKey) {
  45759. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  45760. return renderCache;
  45761. };
  45762. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45763. var renderCache = modelRenderCache;
  45764. var engine = this.owner.engine;
  45765. renderCache.fontTexture = this.fontTexture;
  45766. renderCache.fontTexture.incCachedFontTextureCounter();
  45767. var vb = new Float32Array(4);
  45768. for (var i = 0; i < 4; i++) {
  45769. vb[i] = i;
  45770. }
  45771. renderCache.vb = engine.createVertexBuffer(vb);
  45772. var ib = new Float32Array(6);
  45773. ib[0] = 0;
  45774. ib[1] = 2;
  45775. ib[2] = 1;
  45776. ib[3] = 0;
  45777. ib[4] = 3;
  45778. ib[5] = 2;
  45779. renderCache.ib = engine.createIndexBuffer(ib);
  45780. // 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
  45781. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, true);
  45782. if (ei) {
  45783. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45784. }
  45785. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, false);
  45786. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45787. return renderCache;
  45788. };
  45789. Text2D.prototype.createInstanceDataParts = function () {
  45790. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  45791. };
  45792. // Looks like a hack!? Yes! Because that's what it is!
  45793. // 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
  45794. // 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)
  45795. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  45796. if (!this._charCount) {
  45797. var curText = this._text;
  45798. this.text = "A";
  45799. return curText;
  45800. }
  45801. };
  45802. // if obj contains something, we restore the _text property
  45803. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  45804. if (obj !== undefined) {
  45805. this.text = obj;
  45806. }
  45807. };
  45808. Text2D.prototype.refreshInstanceDataPart = function (part) {
  45809. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45810. return false;
  45811. }
  45812. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  45813. var d = part;
  45814. var texture = this.fontTexture;
  45815. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  45816. var ts = texture.getSize();
  45817. var offset = BABYLON.Vector2.Zero();
  45818. var lh = this.fontTexture.lineHeight;
  45819. 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
  45820. var charxpos = 0;
  45821. d.dataElementCount = this._charCount;
  45822. d.curElement = 0;
  45823. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  45824. var char = _a[_i];
  45825. // Line feed
  45826. if (char === "\n") {
  45827. offset.x = 0;
  45828. offset.y -= texture.lineHeight;
  45829. }
  45830. // Tabulation ?
  45831. if (char === "\t") {
  45832. var nextPos = charxpos + this._tabulationSize;
  45833. nextPos = nextPos - (nextPos % this._tabulationSize);
  45834. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  45835. charxpos = nextPos;
  45836. continue;
  45837. }
  45838. if (char < " ") {
  45839. continue;
  45840. }
  45841. this.updateInstanceDataPart(d, offset);
  45842. var ci = texture.getChar(char);
  45843. offset.x += ci.charWidth;
  45844. d.topLeftUV = ci.topLeftUV;
  45845. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  45846. d.sizeUV = suv;
  45847. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  45848. d.color = this.defaultFontColor;
  45849. d.superSampleFactor = superSampleFactor;
  45850. ++d.curElement;
  45851. }
  45852. }
  45853. return true;
  45854. };
  45855. Text2D.prototype._updateCharCount = function () {
  45856. var count = 0;
  45857. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  45858. var char = _a[_i];
  45859. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  45860. continue;
  45861. }
  45862. ++count;
  45863. }
  45864. this._charCount = count;
  45865. };
  45866. Text2D.prototype._useTextureAlpha = function () {
  45867. return this.fontTexture != null && this.fontTexture.hasAlpha;
  45868. };
  45869. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  45870. return true;
  45871. };
  45872. Text2D.TEXT2D_MAINPARTID = 1;
  45873. __decorate([
  45874. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  45875. ], Text2D.prototype, "fontName", null);
  45876. __decorate([
  45877. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  45878. ], Text2D.prototype, "defaultFontColor", null);
  45879. __decorate([
  45880. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  45881. ], Text2D.prototype, "text", null);
  45882. __decorate([
  45883. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  45884. ], Text2D.prototype, "size", null);
  45885. Text2D = __decorate([
  45886. BABYLON.className("Text2D")
  45887. ], Text2D);
  45888. return Text2D;
  45889. })(BABYLON.RenderablePrim2D);
  45890. BABYLON.Text2D = Text2D;
  45891. })(BABYLON || (BABYLON = {}));
  45892. var BABYLON;
  45893. (function (BABYLON) {
  45894. var Lines2DRenderCache = (function (_super) {
  45895. __extends(Lines2DRenderCache, _super);
  45896. function Lines2DRenderCache(engine, modelKey) {
  45897. _super.call(this, engine, modelKey);
  45898. this.effectsReady = false;
  45899. this.fillVB = null;
  45900. this.fillIB = null;
  45901. this.fillIndicesCount = 0;
  45902. this.instancingFillAttributes = null;
  45903. this.effectFill = null;
  45904. this.effectFillInstanced = null;
  45905. this.borderVB = null;
  45906. this.borderIB = null;
  45907. this.borderIndicesCount = 0;
  45908. this.instancingBorderAttributes = null;
  45909. this.effectBorder = null;
  45910. this.effectBorderInstanced = null;
  45911. }
  45912. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  45913. // Do nothing if the shader is still loading/preparing
  45914. if (!this.effectsReady) {
  45915. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  45916. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  45917. return false;
  45918. }
  45919. this.effectsReady = true;
  45920. }
  45921. var canvas = instanceInfo.owner.owner;
  45922. var engine = canvas.engine;
  45923. var depthFunction = 0;
  45924. if (this.effectFill && this.effectBorder) {
  45925. depthFunction = engine.getDepthFunction();
  45926. engine.setDepthFunctionToLessOrEqual();
  45927. }
  45928. var curAlphaMode = engine.getAlphaMode();
  45929. if (this.effectFill) {
  45930. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  45931. var pid = context.groupInfoPartData[partIndex];
  45932. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45933. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45934. }
  45935. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  45936. engine.enableEffect(effect);
  45937. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  45938. if (context.useInstancing) {
  45939. if (!this.instancingFillAttributes) {
  45940. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  45941. }
  45942. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45943. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45944. canvas._addDrawCallCount(1, context.renderMode);
  45945. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  45946. engine.draw(true, 0, this.fillIndicesCount, count);
  45947. engine.unbindInstanceAttributes();
  45948. }
  45949. else {
  45950. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45951. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45952. this.setupUniforms(effect, partIndex, pid._partData, i);
  45953. engine.draw(true, 0, this.fillIndicesCount);
  45954. }
  45955. }
  45956. }
  45957. if (this.effectBorder) {
  45958. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  45959. var pid = context.groupInfoPartData[partIndex];
  45960. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45961. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45962. }
  45963. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  45964. engine.enableEffect(effect);
  45965. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  45966. if (context.useInstancing) {
  45967. if (!this.instancingBorderAttributes) {
  45968. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  45969. }
  45970. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45971. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45972. canvas._addDrawCallCount(1, context.renderMode);
  45973. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  45974. engine.draw(true, 0, this.borderIndicesCount, count);
  45975. engine.unbindInstanceAttributes();
  45976. }
  45977. else {
  45978. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45979. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45980. this.setupUniforms(effect, partIndex, pid._partData, i);
  45981. engine.draw(true, 0, this.borderIndicesCount);
  45982. }
  45983. }
  45984. }
  45985. engine.setAlphaMode(curAlphaMode, true);
  45986. if (this.effectFill && this.effectBorder) {
  45987. engine.setDepthFunction(depthFunction);
  45988. }
  45989. return true;
  45990. };
  45991. Lines2DRenderCache.prototype.dispose = function () {
  45992. if (!_super.prototype.dispose.call(this)) {
  45993. return false;
  45994. }
  45995. if (this.fillVB) {
  45996. this._engine._releaseBuffer(this.fillVB);
  45997. this.fillVB = null;
  45998. }
  45999. if (this.fillIB) {
  46000. this._engine._releaseBuffer(this.fillIB);
  46001. this.fillIB = null;
  46002. }
  46003. this.effectFill = null;
  46004. this.effectFillInstanced = null;
  46005. this.effectBorder = null;
  46006. this.effectBorderInstanced = null;
  46007. if (this.borderVB) {
  46008. this._engine._releaseBuffer(this.borderVB);
  46009. this.borderVB = null;
  46010. }
  46011. if (this.borderIB) {
  46012. this._engine._releaseBuffer(this.borderIB);
  46013. this.borderIB = null;
  46014. }
  46015. return true;
  46016. };
  46017. return Lines2DRenderCache;
  46018. })(BABYLON.ModelRenderCache);
  46019. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  46020. var Lines2DInstanceData = (function (_super) {
  46021. __extends(Lines2DInstanceData, _super);
  46022. function Lines2DInstanceData(partId) {
  46023. _super.call(this, partId, 1);
  46024. }
  46025. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  46026. get: function () {
  46027. return null;
  46028. },
  46029. enumerable: true,
  46030. configurable: true
  46031. });
  46032. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  46033. get: function () {
  46034. return null;
  46035. },
  46036. enumerable: true,
  46037. configurable: true
  46038. });
  46039. __decorate([
  46040. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  46041. ], Lines2DInstanceData.prototype, "boundingMin", null);
  46042. __decorate([
  46043. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  46044. ], Lines2DInstanceData.prototype, "boundingMax", null);
  46045. return Lines2DInstanceData;
  46046. })(BABYLON.Shape2DInstanceData);
  46047. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  46048. var Lines2D = (function (_super) {
  46049. __extends(Lines2D, _super);
  46050. /**
  46051. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  46052. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  46053. * @param settings a combination of settings, possible ones are
  46054. * - 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)
  46055. * - children: an array of direct children
  46056. * - id a text identifier, for information purpose
  46057. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  46058. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  46059. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  46060. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  46061. * - zOrder: override the zOrder with the specified value
  46062. * - origin: define the normalized origin point location, default [0.5;0.5]
  46063. * - 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.
  46064. * - 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.
  46065. * - 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.
  46066. * - 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.
  46067. * - 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)
  46068. * - 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)
  46069. * - borderThickness: the thickness of the drawn border, default is 1.
  46070. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  46071. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  46072. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  46073. * - 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!
  46074. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46075. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46076. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46077. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46078. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  46079. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  46080. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  46081. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  46082. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46083. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46084. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46085. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46086. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46087. */
  46088. function Lines2D(points, settings) {
  46089. if (!settings) {
  46090. settings = {};
  46091. }
  46092. _super.call(this, settings);
  46093. this._fillVB = null;
  46094. this._fillIB = null;
  46095. this._borderVB = null;
  46096. this._borderIB = null;
  46097. this._size = BABYLON.Size.Zero();
  46098. this._boundingMin = null;
  46099. this._boundingMax = null;
  46100. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  46101. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  46102. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  46103. var closed = (settings.closed == null) ? false : settings.closed;
  46104. this.points = points;
  46105. this.fillThickness = fillThickness;
  46106. this.startCap = startCap;
  46107. this.endCap = endCap;
  46108. this.closed = closed;
  46109. }
  46110. Object.defineProperty(Lines2D, "NoCap", {
  46111. /**
  46112. * No Cap to apply on the extremity
  46113. */
  46114. get: function () { return Lines2D._noCap; },
  46115. enumerable: true,
  46116. configurable: true
  46117. });
  46118. Object.defineProperty(Lines2D, "RoundCap", {
  46119. /**
  46120. * A round cap, will use the line thickness as diameter
  46121. */
  46122. get: function () { return Lines2D._roundCap; },
  46123. enumerable: true,
  46124. configurable: true
  46125. });
  46126. Object.defineProperty(Lines2D, "TriangleCap", {
  46127. /**
  46128. * Creates a triangle at the extremity.
  46129. */
  46130. get: function () { return Lines2D._triangleCap; },
  46131. enumerable: true,
  46132. configurable: true
  46133. });
  46134. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  46135. /**
  46136. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  46137. */
  46138. get: function () { return Lines2D._squareAnchorCap; },
  46139. enumerable: true,
  46140. configurable: true
  46141. });
  46142. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  46143. /**
  46144. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  46145. */
  46146. get: function () { return Lines2D._roundAnchorCap; },
  46147. enumerable: true,
  46148. configurable: true
  46149. });
  46150. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  46151. /**
  46152. * Creates a diamond anchor at the extremity.
  46153. */
  46154. get: function () { return Lines2D._diamondAnchorCap; },
  46155. enumerable: true,
  46156. configurable: true
  46157. });
  46158. Object.defineProperty(Lines2D, "ArrowCap", {
  46159. /**
  46160. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  46161. */
  46162. get: function () { return Lines2D._arrowCap; },
  46163. enumerable: true,
  46164. configurable: true
  46165. });
  46166. Object.defineProperty(Lines2D.prototype, "points", {
  46167. get: function () {
  46168. return this._points;
  46169. },
  46170. set: function (value) {
  46171. this._points = value;
  46172. this._contour = null;
  46173. this._boundingBoxDirty();
  46174. },
  46175. enumerable: true,
  46176. configurable: true
  46177. });
  46178. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  46179. get: function () {
  46180. return this._fillThickness;
  46181. },
  46182. set: function (value) {
  46183. this._fillThickness = value;
  46184. },
  46185. enumerable: true,
  46186. configurable: true
  46187. });
  46188. Object.defineProperty(Lines2D.prototype, "closed", {
  46189. get: function () {
  46190. return this._closed;
  46191. },
  46192. set: function (value) {
  46193. this._closed = value;
  46194. },
  46195. enumerable: true,
  46196. configurable: true
  46197. });
  46198. Object.defineProperty(Lines2D.prototype, "startCap", {
  46199. get: function () {
  46200. return this._startCap;
  46201. },
  46202. set: function (value) {
  46203. this._startCap = value;
  46204. },
  46205. enumerable: true,
  46206. configurable: true
  46207. });
  46208. Object.defineProperty(Lines2D.prototype, "endCap", {
  46209. get: function () {
  46210. return this._endCap;
  46211. },
  46212. set: function (value) {
  46213. this._endCap = value;
  46214. },
  46215. enumerable: true,
  46216. configurable: true
  46217. });
  46218. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  46219. var _this = this;
  46220. if (this._contour == null) {
  46221. this._computeLines2D();
  46222. }
  46223. var pl = this.points.length;
  46224. var l = this.closed ? pl + 1 : pl;
  46225. var p = intersectInfo._localPickPosition;
  46226. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  46227. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  46228. for (var i = 1; i < l; i++) {
  46229. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  46230. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  46231. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  46232. return true;
  46233. }
  46234. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  46235. return true;
  46236. }
  46237. Lines2D._prevA.x = Lines2D._curA.x;
  46238. Lines2D._prevA.y = Lines2D._curA.y;
  46239. Lines2D._prevB.x = Lines2D._curB.x;
  46240. Lines2D._prevB.y = Lines2D._curB.y;
  46241. }
  46242. var capIntersect = function (tri, points) {
  46243. var l = tri.length;
  46244. for (var i = 0; i < l; i += 3) {
  46245. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  46246. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  46247. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  46248. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  46249. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  46250. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  46251. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  46252. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  46253. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  46254. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  46255. return true;
  46256. }
  46257. }
  46258. return false;
  46259. };
  46260. if (this._startCapTriIndices) {
  46261. if (this._startCapTriIndices && capIntersect(this._startCapTriIndices, this._startCapContour)) {
  46262. return true;
  46263. }
  46264. if (this._endCapTriIndices && capIntersect(this._endCapTriIndices, this._endCapContour)) {
  46265. return true;
  46266. }
  46267. }
  46268. return false;
  46269. };
  46270. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  46271. get: function () {
  46272. if (!this._boundingMin) {
  46273. this._computeLines2D();
  46274. }
  46275. return this._boundingMin;
  46276. },
  46277. enumerable: true,
  46278. configurable: true
  46279. });
  46280. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  46281. get: function () {
  46282. if (!this._boundingMax) {
  46283. this._computeLines2D();
  46284. }
  46285. return this._boundingMax;
  46286. },
  46287. enumerable: true,
  46288. configurable: true
  46289. });
  46290. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  46291. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  46292. // Remove the BORDER category, we don't use it in the VertexShader
  46293. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  46294. if (i !== -1) {
  46295. res.splice(i, 1);
  46296. }
  46297. return res;
  46298. };
  46299. Lines2D.prototype.updateLevelBoundingInfo = function () {
  46300. if (!this._boundingMin) {
  46301. this._computeLines2D();
  46302. }
  46303. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  46304. };
  46305. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  46306. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  46307. return renderCache;
  46308. };
  46309. ///////////////////////////////////////////////////////////////////////////////////
  46310. // Methods for Lines building
  46311. Lines2D.prototype._perp = function (v, res) {
  46312. res.x = v.y;
  46313. res.y = -v.x;
  46314. };
  46315. ;
  46316. Lines2D.prototype._direction = function (a, b, res) {
  46317. a.subtractToRef(b, res);
  46318. res.normalize();
  46319. };
  46320. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  46321. a.addToRef(b, tangent);
  46322. tangent.normalize();
  46323. miter.x = -tangent.y;
  46324. miter.y = tangent.x;
  46325. Lines2D._miterTps.x = -a.y;
  46326. Lines2D._miterTps.y = a.x;
  46327. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  46328. };
  46329. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  46330. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  46331. if (d === 0)
  46332. return false;
  46333. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  46334. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  46335. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  46336. return false;
  46337. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  46338. return false;
  46339. return true;
  46340. };
  46341. Lines2D.prototype._updateMinMax = function (array, offset) {
  46342. if (offset >= array.length) {
  46343. return;
  46344. }
  46345. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  46346. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  46347. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  46348. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  46349. };
  46350. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  46351. var borderMode = borderThickness != null && !isNaN(borderThickness);
  46352. var off = index * (borderMode ? 8 : 4);
  46353. // 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)
  46354. if (off >= array.length) {
  46355. return;
  46356. }
  46357. // Store start/end normal, we need it for the cap construction
  46358. if (index === 0) {
  46359. this._perp(n, Lines2D._startDir);
  46360. }
  46361. else if (index === max - 1) {
  46362. this._perp(n, Lines2D._endDir);
  46363. Lines2D._endDir.x *= -1;
  46364. Lines2D._endDir.y *= -1;
  46365. }
  46366. var swap = false;
  46367. array[off + 0] = p.x + n.x * halfThickness;
  46368. array[off + 1] = p.y + n.y * halfThickness;
  46369. array[off + 2] = p.x + n.x * -halfThickness;
  46370. array[off + 3] = p.y + n.y * -halfThickness;
  46371. this._updateMinMax(array, off);
  46372. this._updateMinMax(array, off + 2);
  46373. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  46374. // 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
  46375. if (detectFlip !== undefined) {
  46376. // Flip if intersect
  46377. var flipOff = detectFlip * (borderMode ? 8 : 4);
  46378. 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])) {
  46379. swap = true;
  46380. var tps = array[off + 0];
  46381. array[off + 0] = array[off + 2];
  46382. array[off + 2] = tps;
  46383. tps = array[off + 1];
  46384. array[off + 1] = array[off + 3];
  46385. array[off + 3] = tps;
  46386. }
  46387. }
  46388. if (borderMode) {
  46389. var t = halfThickness + borderThickness;
  46390. array[off + 4] = p.x + n.x * (swap ? -t : t);
  46391. array[off + 5] = p.y + n.y * (swap ? -t : t);
  46392. array[off + 6] = p.x + n.x * (swap ? t : -t);
  46393. array[off + 7] = p.y + n.y * (swap ? t : -t);
  46394. this._updateMinMax(array, off + 4);
  46395. this._updateMinMax(array, off + 6);
  46396. }
  46397. if (contour) {
  46398. off += borderMode ? 4 : 0;
  46399. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  46400. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  46401. }
  46402. };
  46403. Lines2D.prototype._getCapSize = function (type, border) {
  46404. if (border === void 0) { border = false; }
  46405. var sd = Lines2D._roundCapSubDiv;
  46406. // If no array given, we call this to get the size
  46407. var vbsize = 0, ibsize = 0;
  46408. switch (type) {
  46409. case Lines2D.NoCap:
  46410. {
  46411. // If the line is not close and we're computing border, we add the size to generate the edge border
  46412. if (!this.closed && border) {
  46413. vbsize = 4;
  46414. ibsize = 6;
  46415. }
  46416. else {
  46417. vbsize = ibsize = 0;
  46418. }
  46419. break;
  46420. }
  46421. case Lines2D.RoundCap:
  46422. {
  46423. if (border) {
  46424. vbsize = sd;
  46425. ibsize = (sd - 2) * 3;
  46426. }
  46427. else {
  46428. vbsize = (sd / 2) + 1;
  46429. ibsize = (sd / 2) * 3;
  46430. }
  46431. break;
  46432. }
  46433. case Lines2D.ArrowCap:
  46434. {
  46435. if (border) {
  46436. vbsize = 12;
  46437. ibsize = 24;
  46438. }
  46439. else {
  46440. vbsize = 3;
  46441. ibsize = 3;
  46442. }
  46443. break;
  46444. }
  46445. case Lines2D.TriangleCap:
  46446. {
  46447. if (border) {
  46448. vbsize = 6;
  46449. ibsize = 12;
  46450. }
  46451. else {
  46452. vbsize = 3;
  46453. ibsize = 3;
  46454. }
  46455. break;
  46456. }
  46457. case Lines2D.DiamondAnchorCap:
  46458. {
  46459. if (border) {
  46460. vbsize = 10;
  46461. ibsize = 24;
  46462. }
  46463. else {
  46464. vbsize = 5;
  46465. ibsize = 9;
  46466. }
  46467. break;
  46468. }
  46469. case Lines2D.SquareAnchorCap:
  46470. {
  46471. if (border) {
  46472. vbsize = 12;
  46473. ibsize = 30;
  46474. }
  46475. else {
  46476. vbsize = 4;
  46477. ibsize = 6;
  46478. }
  46479. break;
  46480. }
  46481. case Lines2D.RoundAnchorCap:
  46482. {
  46483. if (border) {
  46484. vbsize = sd * 2;
  46485. ibsize = (sd - 1) * 6;
  46486. }
  46487. else {
  46488. vbsize = sd + 1;
  46489. ibsize = (sd + 1) * 3;
  46490. }
  46491. break;
  46492. }
  46493. }
  46494. return { vbsize: vbsize * 2, ibsize: ibsize };
  46495. };
  46496. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  46497. var c = Math.cos(rotation);
  46498. var s = Math.sin(rotation);
  46499. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  46500. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  46501. var offset = baseOffset + (index * 2);
  46502. vb[offset + 0] = Lines2D._tpsV.x;
  46503. vb[offset + 1] = Lines2D._tpsV.y;
  46504. if (contour) {
  46505. contour.push(Lines2D._tpsV.x);
  46506. contour.push(Lines2D._tpsV.y);
  46507. }
  46508. this._updateMinMax(vb, offset);
  46509. return (baseOffset + index * 2) / 2;
  46510. };
  46511. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  46512. ib[baseOffset + index] = vertexIndex;
  46513. };
  46514. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  46515. // 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
  46516. var sd = Lines2D._roundCapSubDiv;
  46517. var dir = new BABYLON.Vector2(1, 0);
  46518. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  46519. var ht = thickness / 2;
  46520. var t = thickness;
  46521. var borderMode = borderThickness != null;
  46522. var bt = borderThickness;
  46523. switch (type) {
  46524. case Lines2D.NoCap:
  46525. if (borderMode && !this.closed) {
  46526. var vi = 0;
  46527. var ii = 0;
  46528. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  46529. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  46530. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  46531. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  46532. this._storeIndex(ib, ibi, ii++, v1);
  46533. this._storeIndex(ib, ibi, ii++, v2);
  46534. this._storeIndex(ib, ibi, ii++, v3);
  46535. this._storeIndex(ib, ibi, ii++, v1);
  46536. this._storeIndex(ib, ibi, ii++, v3);
  46537. this._storeIndex(ib, ibi, ii++, v4);
  46538. }
  46539. break;
  46540. case Lines2D.ArrowCap:
  46541. ht *= 2;
  46542. case Lines2D.TriangleCap:
  46543. {
  46544. if (borderMode) {
  46545. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  46546. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  46547. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  46548. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  46549. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  46550. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  46551. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  46552. var ii = 0;
  46553. this._storeIndex(ib, ibi, ii++, v1);
  46554. this._storeIndex(ib, ibi, ii++, v4);
  46555. this._storeIndex(ib, ibi, ii++, v5);
  46556. this._storeIndex(ib, ibi, ii++, v1);
  46557. this._storeIndex(ib, ibi, ii++, v5);
  46558. this._storeIndex(ib, ibi, ii++, v2);
  46559. this._storeIndex(ib, ibi, ii++, v6);
  46560. this._storeIndex(ib, ibi, ii++, v3);
  46561. this._storeIndex(ib, ibi, ii++, v2);
  46562. this._storeIndex(ib, ibi, ii++, v6);
  46563. this._storeIndex(ib, ibi, ii++, v2);
  46564. this._storeIndex(ib, ibi, ii++, v5);
  46565. if (type === Lines2D.ArrowCap) {
  46566. var rht = thickness / 2;
  46567. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  46568. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  46569. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  46570. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  46571. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  46572. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  46573. this._storeIndex(ib, ibi, ii++, v7);
  46574. this._storeIndex(ib, ibi, ii++, v8);
  46575. this._storeIndex(ib, ibi, ii++, v9);
  46576. this._storeIndex(ib, ibi, ii++, v7);
  46577. this._storeIndex(ib, ibi, ii++, v9);
  46578. this._storeIndex(ib, ibi, ii++, v4);
  46579. this._storeIndex(ib, ibi, ii++, v10);
  46580. this._storeIndex(ib, ibi, ii++, v12);
  46581. this._storeIndex(ib, ibi, ii++, v11);
  46582. this._storeIndex(ib, ibi, ii++, v10);
  46583. this._storeIndex(ib, ibi, ii++, v6);
  46584. this._storeIndex(ib, ibi, ii++, v12);
  46585. }
  46586. }
  46587. else {
  46588. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  46589. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  46590. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  46591. this._storeIndex(ib, ibi, 0, v1);
  46592. this._storeIndex(ib, ibi, 1, v2);
  46593. this._storeIndex(ib, ibi, 2, v3);
  46594. }
  46595. break;
  46596. }
  46597. case Lines2D.RoundCap:
  46598. {
  46599. if (borderMode) {
  46600. var curA = -Math.PI / 2;
  46601. var incA = Math.PI / (sd / 2 - 1);
  46602. var ii = 0;
  46603. for (var i = 0; i < (sd / 2); i++) {
  46604. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  46605. 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);
  46606. if (i > 0) {
  46607. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46608. this._storeIndex(ib, ibi, ii++, v2 - 2);
  46609. this._storeIndex(ib, ibi, ii++, v2);
  46610. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46611. this._storeIndex(ib, ibi, ii++, v2);
  46612. this._storeIndex(ib, ibi, ii++, v1);
  46613. }
  46614. curA += incA;
  46615. }
  46616. }
  46617. else {
  46618. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  46619. var curA = -Math.PI / 2;
  46620. var incA = Math.PI / (sd / 2 - 1);
  46621. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  46622. curA += incA;
  46623. for (var i = 1; i < (sd / 2); i++) {
  46624. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  46625. this._storeIndex(ib, ibi, i * 3 + 0, c);
  46626. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  46627. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  46628. curA += incA;
  46629. }
  46630. }
  46631. break;
  46632. }
  46633. case Lines2D.SquareAnchorCap:
  46634. {
  46635. var vi = 0;
  46636. var c = borderMode ? null : contour;
  46637. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  46638. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  46639. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  46640. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  46641. if (borderMode) {
  46642. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  46643. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  46644. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  46645. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  46646. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  46647. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  46648. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  46649. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  46650. var ii = 0;
  46651. this._storeIndex(ib, ibi, ii++, v6);
  46652. this._storeIndex(ib, ibi, ii++, v1);
  46653. this._storeIndex(ib, ibi, ii++, v5);
  46654. this._storeIndex(ib, ibi, ii++, v6);
  46655. this._storeIndex(ib, ibi, ii++, v7);
  46656. this._storeIndex(ib, ibi, ii++, v1);
  46657. this._storeIndex(ib, ibi, ii++, v1);
  46658. this._storeIndex(ib, ibi, ii++, v7);
  46659. this._storeIndex(ib, ibi, ii++, v8);
  46660. this._storeIndex(ib, ibi, ii++, v1);
  46661. this._storeIndex(ib, ibi, ii++, v8);
  46662. this._storeIndex(ib, ibi, ii++, v2);
  46663. this._storeIndex(ib, ibi, ii++, v2);
  46664. this._storeIndex(ib, ibi, ii++, v8);
  46665. this._storeIndex(ib, ibi, ii++, v9);
  46666. this._storeIndex(ib, ibi, ii++, v2);
  46667. this._storeIndex(ib, ibi, ii++, v9);
  46668. this._storeIndex(ib, ibi, ii++, v3);
  46669. this._storeIndex(ib, ibi, ii++, v3);
  46670. this._storeIndex(ib, ibi, ii++, v9);
  46671. this._storeIndex(ib, ibi, ii++, v10);
  46672. this._storeIndex(ib, ibi, ii++, v3);
  46673. this._storeIndex(ib, ibi, ii++, v10);
  46674. this._storeIndex(ib, ibi, ii++, v4);
  46675. this._storeIndex(ib, ibi, ii++, v10);
  46676. this._storeIndex(ib, ibi, ii++, v11);
  46677. this._storeIndex(ib, ibi, ii++, v4);
  46678. this._storeIndex(ib, ibi, ii++, v11);
  46679. this._storeIndex(ib, ibi, ii++, v12);
  46680. this._storeIndex(ib, ibi, ii++, v4);
  46681. }
  46682. else {
  46683. this._storeIndex(ib, ibi, 0, v1);
  46684. this._storeIndex(ib, ibi, 1, v2);
  46685. this._storeIndex(ib, ibi, 2, v3);
  46686. this._storeIndex(ib, ibi, 3, v1);
  46687. this._storeIndex(ib, ibi, 4, v3);
  46688. this._storeIndex(ib, ibi, 5, v4);
  46689. }
  46690. break;
  46691. }
  46692. case Lines2D.RoundAnchorCap:
  46693. {
  46694. var cpos = Math.sqrt(t * t - ht * ht);
  46695. var center = new BABYLON.Vector2(cpos, 0);
  46696. var curA = BABYLON.Tools.ToRadians(-150);
  46697. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  46698. if (borderMode) {
  46699. var ii = 0;
  46700. for (var i = 0; i < sd; i++) {
  46701. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  46702. 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);
  46703. if (i > 0) {
  46704. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46705. this._storeIndex(ib, ibi, ii++, v2 - 2);
  46706. this._storeIndex(ib, ibi, ii++, v2);
  46707. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46708. this._storeIndex(ib, ibi, ii++, v2);
  46709. this._storeIndex(ib, ibi, ii++, v1);
  46710. }
  46711. curA += incA;
  46712. }
  46713. }
  46714. else {
  46715. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  46716. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  46717. curA += incA;
  46718. for (var i = 1; i < sd; i++) {
  46719. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  46720. this._storeIndex(ib, ibi, i * 3 + 0, c);
  46721. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  46722. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  46723. curA += incA;
  46724. }
  46725. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  46726. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  46727. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  46728. }
  46729. break;
  46730. }
  46731. case Lines2D.DiamondAnchorCap:
  46732. {
  46733. var vi = 0;
  46734. var c = borderMode ? null : contour;
  46735. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  46736. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  46737. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  46738. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  46739. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  46740. if (borderMode) {
  46741. var f = Math.sqrt(bt * bt * 2);
  46742. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  46743. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  46744. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  46745. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  46746. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  46747. var ii = 0;
  46748. this._storeIndex(ib, ibi, ii++, v6);
  46749. this._storeIndex(ib, ibi, ii++, v7);
  46750. this._storeIndex(ib, ibi, ii++, v1);
  46751. this._storeIndex(ib, ibi, ii++, v1);
  46752. this._storeIndex(ib, ibi, ii++, v7);
  46753. this._storeIndex(ib, ibi, ii++, v2);
  46754. this._storeIndex(ib, ibi, ii++, v2);
  46755. this._storeIndex(ib, ibi, ii++, v7);
  46756. this._storeIndex(ib, ibi, ii++, v8);
  46757. this._storeIndex(ib, ibi, ii++, v2);
  46758. this._storeIndex(ib, ibi, ii++, v8);
  46759. this._storeIndex(ib, ibi, ii++, v3);
  46760. this._storeIndex(ib, ibi, ii++, v3);
  46761. this._storeIndex(ib, ibi, ii++, v8);
  46762. this._storeIndex(ib, ibi, ii++, v9);
  46763. this._storeIndex(ib, ibi, ii++, v3);
  46764. this._storeIndex(ib, ibi, ii++, v9);
  46765. this._storeIndex(ib, ibi, ii++, v4);
  46766. this._storeIndex(ib, ibi, ii++, v4);
  46767. this._storeIndex(ib, ibi, ii++, v9);
  46768. this._storeIndex(ib, ibi, ii++, v10);
  46769. this._storeIndex(ib, ibi, ii++, v4);
  46770. this._storeIndex(ib, ibi, ii++, v10);
  46771. this._storeIndex(ib, ibi, ii++, v5);
  46772. }
  46773. else {
  46774. this._storeIndex(ib, ibi, 0, v1);
  46775. this._storeIndex(ib, ibi, 1, v2);
  46776. this._storeIndex(ib, ibi, 2, v3);
  46777. this._storeIndex(ib, ibi, 3, v1);
  46778. this._storeIndex(ib, ibi, 4, v3);
  46779. this._storeIndex(ib, ibi, 5, v5);
  46780. this._storeIndex(ib, ibi, 6, v5);
  46781. this._storeIndex(ib, ibi, 7, v3);
  46782. this._storeIndex(ib, ibi, 8, v4);
  46783. }
  46784. break;
  46785. }
  46786. }
  46787. return null;
  46788. };
  46789. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  46790. var lineA = BABYLON.Vector2.Zero();
  46791. var lineB = BABYLON.Vector2.Zero();
  46792. var tangent = BABYLON.Vector2.Zero();
  46793. var miter = BABYLON.Vector2.Zero();
  46794. var curNormal = null;
  46795. if (this.closed) {
  46796. this.points.push(this.points[0]);
  46797. }
  46798. var total = this.points.length;
  46799. for (var i = 1; i < total; i++) {
  46800. var last = this.points[i - 1];
  46801. var cur = this.points[i];
  46802. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  46803. this._direction(cur, last, lineA);
  46804. if (!curNormal) {
  46805. curNormal = BABYLON.Vector2.Zero();
  46806. this._perp(lineA, curNormal);
  46807. }
  46808. if (i === 1) {
  46809. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  46810. }
  46811. if (!next) {
  46812. this._perp(lineA, curNormal);
  46813. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  46814. }
  46815. else {
  46816. this._direction(next, cur, lineB);
  46817. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  46818. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  46819. }
  46820. }
  46821. if (this.points.length > 2 && this.closed) {
  46822. var last2 = this.points[total - 2];
  46823. var cur2 = this.points[0];
  46824. var next2 = this.points[1];
  46825. this._direction(cur2, last2, lineA);
  46826. this._direction(next2, cur2, lineB);
  46827. this._perp(lineA, curNormal);
  46828. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  46829. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  46830. // Patch contour
  46831. if (contour) {
  46832. var off = (bt == null) ? 0 : 4;
  46833. contour[0].x = vb[off + 0];
  46834. contour[0].y = vb[off + 1];
  46835. contour[1].x = vb[off + 2];
  46836. contour[1].y = vb[off + 3];
  46837. }
  46838. }
  46839. // Remove the point we added at the beginning
  46840. if (this.closed) {
  46841. this.points.splice(total - 1);
  46842. }
  46843. };
  46844. // Methods for Lines building
  46845. ///////////////////////////////////////////////////////////////////////////////////
  46846. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  46847. var renderCache = modelRenderCache;
  46848. var engine = this.owner.engine;
  46849. if (this._fillVB === null) {
  46850. this._computeLines2D();
  46851. }
  46852. // Need to create WebGL resources for fill part?
  46853. if (this.fill) {
  46854. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  46855. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  46856. renderCache.fillIndicesCount = this._fillIB.length;
  46857. // 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
  46858. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  46859. if (ei) {
  46860. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  46861. }
  46862. // Get the non instanced version
  46863. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  46864. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  46865. }
  46866. // Need to create WebGL resources for border part?
  46867. if (this.border) {
  46868. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  46869. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  46870. renderCache.borderIndicesCount = this._borderIB.length;
  46871. // 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
  46872. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  46873. if (ei) {
  46874. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  46875. }
  46876. // Get the non instanced version
  46877. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  46878. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  46879. }
  46880. this._fillVB = null;
  46881. this._fillIB = null;
  46882. this._borderVB = null;
  46883. this._borderIB = null;
  46884. return renderCache;
  46885. };
  46886. Lines2D.prototype._computeLines2D = function () {
  46887. // Init min/max because their being computed here
  46888. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  46889. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  46890. var contour = new Array();
  46891. var startCapContour = new Array();
  46892. var endCapContour = new Array();
  46893. // Need to create WebGL resources for fill part?
  46894. if (this.fill) {
  46895. var startCapInfo = this._getCapSize(this.startCap);
  46896. var endCapInfo = this._getCapSize(this.endCap);
  46897. var count = this.points.length;
  46898. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  46899. this._fillVB = new Float32Array(vbSize);
  46900. var vb = this._fillVB;
  46901. var ht = this.fillThickness / 2;
  46902. var total = this.points.length;
  46903. this._buildLine(vb, this.border ? null : contour, ht);
  46904. var max = total * 2;
  46905. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  46906. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  46907. var ib = this._fillIB;
  46908. for (var i = 0; i < triCount; i += 2) {
  46909. ib[i * 3 + 0] = i + 0;
  46910. ib[i * 3 + 1] = i + 1;
  46911. ib[i * 3 + 2] = (i + 2) % max;
  46912. ib[i * 3 + 3] = i + 1;
  46913. ib[i * 3 + 4] = (i + 3) % max;
  46914. ib[i * 3 + 5] = (i + 2) % max;
  46915. }
  46916. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  46917. 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);
  46918. }
  46919. // Need to create WebGL resources for border part?
  46920. if (this.border) {
  46921. var startCapInfo = this._getCapSize(this.startCap, true);
  46922. var endCapInfo = this._getCapSize(this.endCap, true);
  46923. var count = this.points.length;
  46924. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  46925. this._borderVB = new Float32Array(vbSize);
  46926. var vb = this._borderVB;
  46927. var ht = this.fillThickness / 2;
  46928. var bt = this.borderThickness;
  46929. var total = this.points.length;
  46930. this._buildLine(vb, contour, ht, bt);
  46931. var max = total * 2 * 2;
  46932. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  46933. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  46934. var ib = this._borderIB;
  46935. for (var i = 0; i < triCount; i += 4) {
  46936. ib[i * 3 + 0] = i + 0;
  46937. ib[i * 3 + 1] = i + 2;
  46938. ib[i * 3 + 2] = (i + 6) % max;
  46939. ib[i * 3 + 3] = i + 0;
  46940. ib[i * 3 + 4] = (i + 6) % max;
  46941. ib[i * 3 + 5] = (i + 4) % max;
  46942. ib[i * 3 + 6] = i + 3;
  46943. ib[i * 3 + 7] = i + 1;
  46944. ib[i * 3 + 8] = (i + 5) % max;
  46945. ib[i * 3 + 9] = i + 3;
  46946. ib[i * 3 + 10] = (i + 5) % max;
  46947. ib[i * 3 + 11] = (i + 7) % max;
  46948. }
  46949. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  46950. 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);
  46951. }
  46952. this._contour = contour;
  46953. if (startCapContour.length > 0) {
  46954. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  46955. this._startCapTriIndices = startCapTri;
  46956. this._startCapContour = startCapContour;
  46957. }
  46958. else {
  46959. this._startCapTriIndices = null;
  46960. this._startCapContour = null;
  46961. }
  46962. if (endCapContour.length > 0) {
  46963. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  46964. this._endCapContour = endCapContour;
  46965. this._endCapTriIndices = endCapTri;
  46966. }
  46967. else {
  46968. this._endCapContour = null;
  46969. this._endCapTriIndices = null;
  46970. }
  46971. var bs = this._boundingMax.subtract(this._boundingMin);
  46972. this._size.width = bs.x;
  46973. this._size.height = bs.y;
  46974. };
  46975. Object.defineProperty(Lines2D.prototype, "size", {
  46976. get: function () {
  46977. if (this._size == null) {
  46978. this._computeLines2D();
  46979. }
  46980. return this._size;
  46981. },
  46982. enumerable: true,
  46983. configurable: true
  46984. });
  46985. Lines2D.prototype.createInstanceDataParts = function () {
  46986. var res = new Array();
  46987. if (this.border) {
  46988. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  46989. }
  46990. if (this.fill) {
  46991. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  46992. }
  46993. return res;
  46994. };
  46995. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  46996. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  46997. return false;
  46998. }
  46999. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  47000. var d = part;
  47001. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  47002. d.boundingMin = this.boundingMin;
  47003. d.boundingMax = this.boundingMax;
  47004. }
  47005. }
  47006. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  47007. var d = part;
  47008. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  47009. d.boundingMin = this.boundingMin;
  47010. d.boundingMax = this.boundingMax;
  47011. }
  47012. }
  47013. return true;
  47014. };
  47015. Lines2D._prevA = BABYLON.Vector2.Zero();
  47016. Lines2D._prevB = BABYLON.Vector2.Zero();
  47017. Lines2D._curA = BABYLON.Vector2.Zero();
  47018. Lines2D._curB = BABYLON.Vector2.Zero();
  47019. Lines2D._miterTps = BABYLON.Vector2.Zero();
  47020. Lines2D._startDir = BABYLON.Vector2.Zero();
  47021. Lines2D._endDir = BABYLON.Vector2.Zero();
  47022. Lines2D._tpsV = BABYLON.Vector2.Zero();
  47023. Lines2D._noCap = 0;
  47024. Lines2D._roundCap = 1;
  47025. Lines2D._triangleCap = 2;
  47026. Lines2D._squareAnchorCap = 3;
  47027. Lines2D._roundAnchorCap = 4;
  47028. Lines2D._diamondAnchorCap = 5;
  47029. Lines2D._arrowCap = 6;
  47030. Lines2D._roundCapSubDiv = 36;
  47031. __decorate([
  47032. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  47033. ], Lines2D.prototype, "points", null);
  47034. __decorate([
  47035. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  47036. ], Lines2D.prototype, "fillThickness", null);
  47037. __decorate([
  47038. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  47039. ], Lines2D.prototype, "closed", null);
  47040. __decorate([
  47041. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  47042. ], Lines2D.prototype, "startCap", null);
  47043. __decorate([
  47044. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  47045. ], Lines2D.prototype, "endCap", null);
  47046. Lines2D = __decorate([
  47047. BABYLON.className("Lines2D")
  47048. ], Lines2D);
  47049. return Lines2D;
  47050. })(BABYLON.Shape2D);
  47051. BABYLON.Lines2D = Lines2D;
  47052. })(BABYLON || (BABYLON = {}));
  47053. var BABYLON;
  47054. (function (BABYLON) {
  47055. // This class contains data that lifetime is bounding to the Babylon Engine object
  47056. var Canvas2DEngineBoundData = (function () {
  47057. function Canvas2DEngineBoundData() {
  47058. this._modelCache = new BABYLON.StringDictionary();
  47059. }
  47060. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  47061. return this._modelCache.getOrAddWithFactory(key, factory);
  47062. };
  47063. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  47064. if (!modelRenderCache.isDisposed) {
  47065. return false;
  47066. }
  47067. this._modelCache.remove(modelRenderCache.modelKey);
  47068. return true;
  47069. };
  47070. return Canvas2DEngineBoundData;
  47071. })();
  47072. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  47073. var Canvas2D = (function (_super) {
  47074. __extends(Canvas2D, _super);
  47075. function Canvas2D(scene, settings) {
  47076. var _this = this;
  47077. _super.call(this, settings);
  47078. /**
  47079. * 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.
  47080. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  47081. */
  47082. this.worldSpaceToNodeLocal = function (worldPos) {
  47083. var node = _this._worldSpaceNode;
  47084. if (!node) {
  47085. return;
  47086. }
  47087. var mtx = node.getWorldMatrix().clone();
  47088. mtx.invert();
  47089. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  47090. var res = new BABYLON.Vector2(v.x, v.y);
  47091. var size = _this.actualSize;
  47092. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  47093. res.y += size.height * 0.5;
  47094. return res;
  47095. };
  47096. /**
  47097. * 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
  47098. */
  47099. this.worldSpaceCacheChanged = function () {
  47100. var plane = _this.worldSpaceCanvasNode;
  47101. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  47102. vd.uvs = new Float32Array(8);
  47103. var material = plane.material;
  47104. var tex = _this._renderableData._cacheTexture;
  47105. if (material.diffuseTexture !== tex) {
  47106. material.diffuseTexture = tex;
  47107. tex.hasAlpha = true;
  47108. }
  47109. var nodeuv = _this._renderableData._cacheNodeUVs;
  47110. for (var i = 0; i < 4; i++) {
  47111. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  47112. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  47113. }
  47114. vd.applyToMesh(plane);
  47115. };
  47116. this._notifDebugMode = false;
  47117. this._mapCounter = 0;
  47118. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  47119. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  47120. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  47121. this._groupRenderCounter = new BABYLON.PerfCounter();
  47122. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  47123. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  47124. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  47125. this._updateLayoutCounter = new BABYLON.PerfCounter();
  47126. this._updatePositioningCounter = new BABYLON.PerfCounter();
  47127. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  47128. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  47129. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  47130. this._profileInfoText = null;
  47131. BABYLON.Prim2DBase._isCanvasInit = false;
  47132. if (!settings) {
  47133. settings = {};
  47134. }
  47135. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  47136. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  47137. this._background.zOrder = 1.0;
  47138. this._background.isPickable = false;
  47139. this._background.origin = BABYLON.Vector2.Zero();
  47140. this._background.levelVisible = false;
  47141. if (settings.backgroundRoundRadius != null) {
  47142. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  47143. }
  47144. if (settings.backgroundBorder != null) {
  47145. if (typeof (settings.backgroundBorder) === "string") {
  47146. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  47147. }
  47148. else {
  47149. this.backgroundBorder = settings.backgroundBorder;
  47150. }
  47151. }
  47152. if (settings.backgroundBorderThickNess != null) {
  47153. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  47154. }
  47155. if (settings.backgroundFill != null) {
  47156. if (typeof (settings.backgroundFill) === "string") {
  47157. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  47158. }
  47159. else {
  47160. this.backgroundFill = settings.backgroundFill;
  47161. }
  47162. }
  47163. this._background._patchHierarchy(this);
  47164. }
  47165. var engine = scene.getEngine();
  47166. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  47167. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  47168. this._capturedPointers = new BABYLON.StringDictionary();
  47169. this._pickStartingPosition = BABYLON.Vector2.Zero();
  47170. this._hierarchyLevelMaxSiblingCount = 50;
  47171. this._hierarchyDepth = 0;
  47172. this._zOrder = 0;
  47173. this._zMax = 1;
  47174. this._scene = scene;
  47175. this._engine = engine;
  47176. this._renderingSize = new BABYLON.Size(0, 0);
  47177. this._trackedGroups = new Array();
  47178. this._maxAdaptiveWorldSpaceCanvasSize = null;
  47179. this._groupCacheMaps = new BABYLON.StringDictionary();
  47180. this._patchHierarchy(this);
  47181. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  47182. this._fitRenderingDevice = !settings.size;
  47183. if (!settings.size) {
  47184. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  47185. }
  47186. // Register scene dispose to also dispose the canvas when it'll happens
  47187. scene.onDisposeObservable.add(function (d, s) {
  47188. _this.dispose();
  47189. });
  47190. if (this._isScreenSpace) {
  47191. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  47192. _this._engine.clear(null, false, true, true);
  47193. _this._render();
  47194. });
  47195. }
  47196. else {
  47197. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  47198. _this._render();
  47199. });
  47200. }
  47201. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  47202. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  47203. this._setupInteraction(enableInteraction);
  47204. }
  47205. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  47206. get: function () {
  47207. return this._drawCallsOpaqueCounter;
  47208. },
  47209. enumerable: true,
  47210. configurable: true
  47211. });
  47212. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  47213. get: function () {
  47214. return this._drawCallsAlphaTestCounter;
  47215. },
  47216. enumerable: true,
  47217. configurable: true
  47218. });
  47219. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  47220. get: function () {
  47221. return this._drawCallsTransparentCounter;
  47222. },
  47223. enumerable: true,
  47224. configurable: true
  47225. });
  47226. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  47227. get: function () {
  47228. return this._groupRenderCounter;
  47229. },
  47230. enumerable: true,
  47231. configurable: true
  47232. });
  47233. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  47234. get: function () {
  47235. return this._updateTransparentDataCounter;
  47236. },
  47237. enumerable: true,
  47238. configurable: true
  47239. });
  47240. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  47241. get: function () {
  47242. return this._cachedGroupRenderCounter;
  47243. },
  47244. enumerable: true,
  47245. configurable: true
  47246. });
  47247. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  47248. get: function () {
  47249. return this._updateCachedStateCounter;
  47250. },
  47251. enumerable: true,
  47252. configurable: true
  47253. });
  47254. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  47255. get: function () {
  47256. return this._updateLayoutCounter;
  47257. },
  47258. enumerable: true,
  47259. configurable: true
  47260. });
  47261. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  47262. get: function () {
  47263. return this._updatePositioningCounter;
  47264. },
  47265. enumerable: true,
  47266. configurable: true
  47267. });
  47268. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  47269. get: function () {
  47270. return this._updateLocalTransformCounter;
  47271. },
  47272. enumerable: true,
  47273. configurable: true
  47274. });
  47275. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  47276. get: function () {
  47277. return this._updateGlobalTransformCounter;
  47278. },
  47279. enumerable: true,
  47280. configurable: true
  47281. });
  47282. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  47283. get: function () {
  47284. return this._boundingInfoRecomputeCounter;
  47285. },
  47286. enumerable: true,
  47287. configurable: true
  47288. });
  47289. Canvas2D.prototype._canvasPreInit = function (settings) {
  47290. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  47291. this._cachingStrategy = cachingStrategy;
  47292. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  47293. };
  47294. Canvas2D.prototype._setupInteraction = function (enable) {
  47295. var _this = this;
  47296. // No change detection
  47297. if (enable === this._interactionEnabled) {
  47298. return;
  47299. }
  47300. // Set the new state
  47301. this._interactionEnabled = enable;
  47302. // ScreenSpace mode
  47303. if (this._isScreenSpace) {
  47304. // Disable interaction
  47305. if (!enable) {
  47306. if (this._scenePrePointerObserver) {
  47307. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  47308. this._scenePrePointerObserver = null;
  47309. }
  47310. return;
  47311. }
  47312. // Enable Interaction
  47313. // Register the observable
  47314. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  47315. if (_this.isVisible === false) {
  47316. return;
  47317. }
  47318. var hs = 1 / _this.engine.getHardwareScalingLevel();
  47319. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  47320. _this._handlePointerEventForInteraction(e, localPos, s);
  47321. });
  47322. }
  47323. else {
  47324. var scene = this.scene;
  47325. if (enable) {
  47326. scene.constantlyUpdateMeshUnderPointer = true;
  47327. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  47328. if (_this.isVisible === false) {
  47329. return;
  47330. }
  47331. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  47332. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  47333. _this._handlePointerEventForInteraction(e, localPos, s);
  47334. }
  47335. });
  47336. }
  47337. else {
  47338. if (this._scenePointerObserver) {
  47339. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  47340. this._scenePointerObserver = null;
  47341. }
  47342. }
  47343. }
  47344. };
  47345. /**
  47346. * Internal method, you should use the Prim2DBase version instead
  47347. */
  47348. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  47349. if (this.isPointerCaptured(pointerId)) {
  47350. return false;
  47351. }
  47352. // Try to capture the pointer on the HTML side
  47353. try {
  47354. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  47355. }
  47356. catch (e) {
  47357. }
  47358. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  47359. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  47360. this._capturedPointers.add(pointerId.toString(), primitive);
  47361. return true;
  47362. };
  47363. /**
  47364. * Internal method, you should use the Prim2DBase version instead
  47365. */
  47366. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  47367. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  47368. return false;
  47369. }
  47370. // Try to release the pointer on the HTML side
  47371. try {
  47372. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  47373. }
  47374. catch (e) {
  47375. }
  47376. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  47377. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  47378. this._capturedPointers.remove(pointerId.toString());
  47379. return true;
  47380. };
  47381. /**
  47382. * Determine if the given pointer is captured or not
  47383. * @param pointerId the Id of the pointer
  47384. * @return true if it's captured, false otherwise
  47385. */
  47386. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  47387. return this._capturedPointers.contains(pointerId.toString());
  47388. };
  47389. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  47390. // Avoid unnecessary lookup
  47391. if (this._capturedPointers.count === 0) {
  47392. return null;
  47393. }
  47394. return this._capturedPointers.get(pointerId.toString());
  47395. };
  47396. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  47397. // Dispose check
  47398. if (this.isDisposed) {
  47399. return;
  47400. }
  47401. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  47402. this._updatePointerInfo(eventData, localPosition);
  47403. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  47404. // 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.
  47405. // 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.
  47406. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  47407. // 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
  47408. this._updateOverStatus();
  47409. // Check if we have nothing to raise
  47410. if (!this._actualOverPrimitive && !capturedPrim) {
  47411. return;
  47412. }
  47413. // Update the relatedTarget info with the over primitive or the captured one (if any)
  47414. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  47415. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  47416. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  47417. // Analyze the pointer event type and fire proper events on the primitive
  47418. var skip = false;
  47419. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  47420. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData);
  47421. }
  47422. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47423. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData);
  47424. }
  47425. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  47426. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData);
  47427. }
  47428. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  47429. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData);
  47430. }
  47431. eventState.skipNextObservers = skip;
  47432. };
  47433. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  47434. var pii = this._primPointerInfo;
  47435. if (!pii.canvasPointerPos) {
  47436. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  47437. }
  47438. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  47439. var engine = this._scene.getEngine();
  47440. if (this._isScreenSpace) {
  47441. var cameraViewport = camera.viewport;
  47442. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47443. // Moving coordinates to local viewport world
  47444. var x = localPosition.x - viewport.x;
  47445. var y = localPosition.y - viewport.y;
  47446. pii.canvasPointerPos.x = x - this.actualPosition.x;
  47447. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  47448. }
  47449. else {
  47450. pii.canvasPointerPos.x = localPosition.x;
  47451. pii.canvasPointerPos.y = localPosition.y;
  47452. }
  47453. //console.log(`UpdatePointerInfo for ${this.id}, X:${pii.canvasPointerPos.x}, Y:${pii.canvasPointerPos.y}`);
  47454. pii.mouseWheelDelta = 0;
  47455. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  47456. var event = eventData.event;
  47457. if (event.wheelDelta) {
  47458. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  47459. }
  47460. else if (event.detail) {
  47461. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  47462. }
  47463. }
  47464. else {
  47465. var pe = eventData.event;
  47466. pii.ctrlKey = pe.ctrlKey;
  47467. pii.altKey = pe.altKey;
  47468. pii.shiftKey = pe.shiftKey;
  47469. pii.metaKey = pe.metaKey;
  47470. pii.button = pe.button;
  47471. pii.buttons = pe.buttons;
  47472. pii.pointerId = pe.pointerId;
  47473. pii.width = pe.width;
  47474. pii.height = pe.height;
  47475. pii.presssure = pe.pressure;
  47476. pii.tilt.x = pe.tiltX;
  47477. pii.tilt.y = pe.tiltY;
  47478. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  47479. }
  47480. };
  47481. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  47482. if (this.scene.getRenderId() === this._intersectionRenderId) {
  47483. return;
  47484. }
  47485. // 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
  47486. if (!this._globalTransform) {
  47487. this.updateCachedStates(true);
  47488. }
  47489. var ii = Canvas2D._interInfo;
  47490. ii.pickPosition.x = mouseLocalPos.x;
  47491. ii.pickPosition.y = mouseLocalPos.y;
  47492. ii.findFirstOnly = false;
  47493. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  47494. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  47495. this._previousIntersectionList = this._actualIntersectionList;
  47496. this._actualIntersectionList = null;
  47497. this._previousOverPrimitive = this._actualOverPrimitive;
  47498. this._actualOverPrimitive = null;
  47499. return;
  47500. }
  47501. this.intersect(ii);
  47502. this._previousIntersectionList = this._actualIntersectionList;
  47503. this._actualIntersectionList = ii.intersectedPrimitives;
  47504. this._previousOverPrimitive = this._actualOverPrimitive;
  47505. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  47506. this._intersectionRenderId = this.scene.getRenderId();
  47507. };
  47508. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  47509. Canvas2D.prototype._updateOverStatus = function () {
  47510. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  47511. return;
  47512. }
  47513. // Detect a change of over
  47514. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  47515. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  47516. if (prevPrim !== actualPrim) {
  47517. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  47518. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  47519. // Notify the previous "over" prim that the pointer is no longer over it
  47520. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  47521. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  47522. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  47523. }
  47524. // Notify the new "over" prim that the pointer is over it
  47525. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  47526. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  47527. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  47528. }
  47529. }
  47530. this._hoverStatusRenderId = this.scene.getRenderId();
  47531. };
  47532. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  47533. if (this._primPointerInfo.isCaptured) {
  47534. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  47535. }
  47536. else {
  47537. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  47538. var pii = _a[_i];
  47539. if (pii.prim === prim) {
  47540. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  47541. return;
  47542. }
  47543. }
  47544. }
  47545. };
  47546. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  47547. if (!this._notifDebugMode) {
  47548. return;
  47549. }
  47550. var debug = "";
  47551. for (var i = 0; i < prim.hierarchyDepth; i++) {
  47552. debug += " ";
  47553. }
  47554. var pii = this._primPointerInfo;
  47555. 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();
  47556. console.log(debug);
  47557. };
  47558. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  47559. var ppi = this._primPointerInfo;
  47560. var event = eventData ? eventData.event : null;
  47561. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  47562. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  47563. this._notifParents(prim, mask);
  47564. }
  47565. var bubbleCancelled = false;
  47566. var cur = prim;
  47567. while (cur) {
  47568. // Only trigger the observers if the primitive is intersected (except for out)
  47569. if (!bubbleCancelled) {
  47570. this._updatePrimPointerPos(cur);
  47571. // Exec the observers
  47572. this._debugExecObserver(cur, mask);
  47573. if (!cur._pointerEventObservable.notifyObservers(ppi, mask) && eventData instanceof BABYLON.PointerInfoPre) {
  47574. eventData.skipOnPointerObservable = true;
  47575. return false;
  47576. }
  47577. this._triggerActionManager(cur, ppi, mask, event);
  47578. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  47579. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  47580. if (ppi.cancelBubble) {
  47581. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  47582. return false;
  47583. }
  47584. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  47585. bubbleCancelled = true;
  47586. }
  47587. }
  47588. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  47589. if (bubbleCancelled) {
  47590. this._updatePrimPointerPos(cur);
  47591. }
  47592. // Trigger a PointerEnter corresponding to the PointerOver
  47593. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  47594. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  47595. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  47596. }
  47597. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  47598. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  47599. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  47600. }
  47601. // Loop to the parent
  47602. cur = cur.parent;
  47603. }
  47604. return true;
  47605. };
  47606. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  47607. var _this = this;
  47608. // 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
  47609. if (!this._globalTransform) {
  47610. this.updateCachedStates(true);
  47611. }
  47612. // Process Trigger related to PointerDown
  47613. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  47614. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  47615. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  47616. this._pickStartingTime = new Date().getTime();
  47617. this._pickedDownPrim = null;
  47618. if (prim.actionManager) {
  47619. this._pickedDownPrim = prim;
  47620. if (prim.actionManager.hasPickTriggers) {
  47621. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47622. switch (eventData.button) {
  47623. case 0:
  47624. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  47625. break;
  47626. case 1:
  47627. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  47628. break;
  47629. case 2:
  47630. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  47631. break;
  47632. }
  47633. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  47634. }
  47635. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  47636. window.setTimeout(function () {
  47637. var ppi = _this._primPointerInfo;
  47638. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  47639. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  47640. var ii = new BABYLON.IntersectInfo2D();
  47641. ii.pickPosition = ppi.canvasPointerPos.clone();
  47642. ii.findFirstOnly = false;
  47643. _this.intersect(ii);
  47644. if (ii.isPrimIntersected(prim) !== null) {
  47645. if (prim.actionManager) {
  47646. 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)) {
  47647. _this._pickStartingTime = 0;
  47648. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  47649. }
  47650. }
  47651. }
  47652. }, BABYLON.ActionManager.LongPressDelay);
  47653. }
  47654. }
  47655. }
  47656. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  47657. this._pickStartingTime = 0;
  47658. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47659. if (prim.actionManager) {
  47660. // OnPickUpTrigger
  47661. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  47662. // OnPickTrigger
  47663. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  47664. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  47665. }
  47666. }
  47667. // OnPickOutTrigger
  47668. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  47669. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  47670. }
  47671. }
  47672. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  47673. if (prim.actionManager) {
  47674. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47675. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  47676. }
  47677. }
  47678. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  47679. if (prim.actionManager) {
  47680. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47681. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  47682. }
  47683. }
  47684. };
  47685. Canvas2D.prototype._notifParents = function (prim, mask) {
  47686. var pii = this._primPointerInfo;
  47687. var curPrim = this;
  47688. while (curPrim) {
  47689. this._updatePrimPointerPos(curPrim);
  47690. // Fire the proper notification
  47691. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  47692. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  47693. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  47694. }
  47695. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  47696. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  47697. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  47698. }
  47699. curPrim = curPrim.parent;
  47700. }
  47701. };
  47702. /**
  47703. * Don't forget to call the dispose method when you're done with the Canvas instance.
  47704. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  47705. */
  47706. Canvas2D.prototype.dispose = function () {
  47707. if (!_super.prototype.dispose.call(this)) {
  47708. return false;
  47709. }
  47710. if (this._profilingCanvas) {
  47711. this._profilingCanvas.dispose();
  47712. this._profilingCanvas = null;
  47713. }
  47714. if (this.interactionEnabled) {
  47715. this._setupInteraction(false);
  47716. }
  47717. if (this._beforeRenderObserver) {
  47718. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  47719. this._beforeRenderObserver = null;
  47720. }
  47721. if (this._afterRenderObserver) {
  47722. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  47723. this._afterRenderObserver = null;
  47724. }
  47725. if (this._groupCacheMaps) {
  47726. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  47727. this._groupCacheMaps = null;
  47728. }
  47729. };
  47730. Object.defineProperty(Canvas2D.prototype, "scene", {
  47731. /**
  47732. * Accessor to the Scene that owns the Canvas
  47733. * @returns The instance of the Scene object
  47734. */
  47735. get: function () {
  47736. return this._scene;
  47737. },
  47738. enumerable: true,
  47739. configurable: true
  47740. });
  47741. Object.defineProperty(Canvas2D.prototype, "engine", {
  47742. /**
  47743. * Accessor to the Engine that drives the Scene used by this Canvas
  47744. * @returns The instance of the Engine object
  47745. */
  47746. get: function () {
  47747. return this._engine;
  47748. },
  47749. enumerable: true,
  47750. configurable: true
  47751. });
  47752. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  47753. /**
  47754. * Accessor of the Caching Strategy used by this Canvas.
  47755. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  47756. * @returns the value corresponding to the used strategy.
  47757. */
  47758. get: function () {
  47759. return this._cachingStrategy;
  47760. },
  47761. enumerable: true,
  47762. configurable: true
  47763. });
  47764. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  47765. /**
  47766. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  47767. * @returns {}
  47768. */
  47769. get: function () {
  47770. return this._isScreenSpace;
  47771. },
  47772. enumerable: true,
  47773. configurable: true
  47774. });
  47775. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  47776. /**
  47777. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  47778. */
  47779. get: function () {
  47780. return this._worldSpaceNode;
  47781. },
  47782. set: function (val) {
  47783. this._worldSpaceNode = val;
  47784. },
  47785. enumerable: true,
  47786. configurable: true
  47787. });
  47788. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  47789. /**
  47790. * Check if the WebGL Instanced Array extension is supported or not
  47791. */
  47792. get: function () {
  47793. return this._supprtInstancedArray;
  47794. },
  47795. enumerable: true,
  47796. configurable: true
  47797. });
  47798. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  47799. /**
  47800. * Property that defines the fill object used to draw the background of the Canvas.
  47801. * Note that Canvas with a Caching Strategy of
  47802. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  47803. */
  47804. get: function () {
  47805. if (!this._background || !this._background.isVisible) {
  47806. return null;
  47807. }
  47808. return this._background.fill;
  47809. },
  47810. set: function (value) {
  47811. this.checkBackgroundAvailability();
  47812. if (value === this._background.fill) {
  47813. return;
  47814. }
  47815. this._background.fill = value;
  47816. this._background.levelVisible = true;
  47817. },
  47818. enumerable: true,
  47819. configurable: true
  47820. });
  47821. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  47822. /**
  47823. * Property that defines the border object used to draw the background of the Canvas.
  47824. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  47825. */
  47826. get: function () {
  47827. if (!this._background || !this._background.isVisible) {
  47828. return null;
  47829. }
  47830. return this._background.border;
  47831. },
  47832. set: function (value) {
  47833. this.checkBackgroundAvailability();
  47834. if (value === this._background.border) {
  47835. return;
  47836. }
  47837. this._background.border = value;
  47838. this._background.levelVisible = true;
  47839. },
  47840. enumerable: true,
  47841. configurable: true
  47842. });
  47843. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  47844. /**
  47845. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  47846. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  47847. */
  47848. get: function () {
  47849. if (!this._background || !this._background.isVisible) {
  47850. return null;
  47851. }
  47852. return this._background.borderThickness;
  47853. },
  47854. set: function (value) {
  47855. this.checkBackgroundAvailability();
  47856. if (value === this._background.borderThickness) {
  47857. return;
  47858. }
  47859. this._background.borderThickness = value;
  47860. },
  47861. enumerable: true,
  47862. configurable: true
  47863. });
  47864. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  47865. /**
  47866. * You can set the roundRadius of the background
  47867. * @returns The current roundRadius
  47868. */
  47869. get: function () {
  47870. if (!this._background || !this._background.isVisible) {
  47871. return null;
  47872. }
  47873. return this._background.roundRadius;
  47874. },
  47875. set: function (value) {
  47876. this.checkBackgroundAvailability();
  47877. if (value === this._background.roundRadius) {
  47878. return;
  47879. }
  47880. this._background.roundRadius = value;
  47881. this._background.levelVisible = true;
  47882. },
  47883. enumerable: true,
  47884. configurable: true
  47885. });
  47886. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  47887. /**
  47888. * Enable/Disable interaction for this Canvas
  47889. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  47890. */
  47891. get: function () {
  47892. return this._interactionEnabled;
  47893. },
  47894. set: function (enable) {
  47895. this._setupInteraction(enable);
  47896. },
  47897. enumerable: true,
  47898. configurable: true
  47899. });
  47900. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  47901. /**
  47902. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  47903. * @returns {}
  47904. */
  47905. get: function () {
  47906. return this.__engineData;
  47907. },
  47908. enumerable: true,
  47909. configurable: true
  47910. });
  47911. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  47912. if (this._profilingCanvas) {
  47913. return this._profilingCanvas;
  47914. }
  47915. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  47916. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  47917. new BABYLON.Rectangle2D({
  47918. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  47919. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  47920. ]
  47921. })
  47922. ]
  47923. });
  47924. this._profileInfoText = canvas.findById("ProfileInfoText");
  47925. this._profilingCanvas = canvas;
  47926. return canvas;
  47927. };
  47928. Canvas2D.prototype.checkBackgroundAvailability = function () {
  47929. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  47930. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  47931. }
  47932. };
  47933. Canvas2D.prototype._initPerfMetrics = function () {
  47934. this._drawCallsOpaqueCounter.fetchNewFrame();
  47935. this._drawCallsAlphaTestCounter.fetchNewFrame();
  47936. this._drawCallsTransparentCounter.fetchNewFrame();
  47937. this._groupRenderCounter.fetchNewFrame();
  47938. this._updateTransparentDataCounter.fetchNewFrame();
  47939. this._cachedGroupRenderCounter.fetchNewFrame();
  47940. this._updateCachedStateCounter.fetchNewFrame();
  47941. this._updateLayoutCounter.fetchNewFrame();
  47942. this._updatePositioningCounter.fetchNewFrame();
  47943. this._updateLocalTransformCounter.fetchNewFrame();
  47944. this._updateGlobalTransformCounter.fetchNewFrame();
  47945. this._boundingInfoRecomputeCounter.fetchNewFrame();
  47946. };
  47947. Canvas2D.prototype._fetchPerfMetrics = function () {
  47948. this._drawCallsOpaqueCounter.addCount(0, true);
  47949. this._drawCallsAlphaTestCounter.addCount(0, true);
  47950. this._drawCallsTransparentCounter.addCount(0, true);
  47951. this._groupRenderCounter.addCount(0, true);
  47952. this._updateTransparentDataCounter.addCount(0, true);
  47953. this._cachedGroupRenderCounter.addCount(0, true);
  47954. this._updateCachedStateCounter.addCount(0, true);
  47955. this._updateLayoutCounter.addCount(0, true);
  47956. this._updatePositioningCounter.addCount(0, true);
  47957. this._updateLocalTransformCounter.addCount(0, true);
  47958. this._updateGlobalTransformCounter.addCount(0, true);
  47959. this._boundingInfoRecomputeCounter.addCount(0, true);
  47960. };
  47961. Canvas2D.prototype._updateProfileCanvas = function () {
  47962. if (this._profileInfoText == null) {
  47963. return;
  47964. }
  47965. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  47966. var p = "Draw Calls:\n" +
  47967. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  47968. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  47969. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  47970. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  47971. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  47972. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  47973. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  47974. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  47975. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  47976. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  47977. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  47978. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  47979. this._profileInfoText.text = p;
  47980. };
  47981. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  47982. switch (renderMode) {
  47983. case BABYLON.Render2DContext.RenderModeOpaque:
  47984. this._drawCallsOpaqueCounter.addCount(count, false);
  47985. return;
  47986. case BABYLON.Render2DContext.RenderModeAlphaTest:
  47987. this._drawCallsAlphaTestCounter.addCount(count, false);
  47988. return;
  47989. case BABYLON.Render2DContext.RenderModeTransparent:
  47990. this._drawCallsTransparentCounter.addCount(count, false);
  47991. return;
  47992. }
  47993. };
  47994. Canvas2D.prototype._addGroupRenderCount = function (count) {
  47995. this._groupRenderCounter.addCount(count, false);
  47996. };
  47997. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  47998. this._updateTransparentDataCounter.addCount(count, false);
  47999. };
  48000. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  48001. this._cachedGroupRenderCounter.addCount(count, false);
  48002. };
  48003. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  48004. this._updateCachedStateCounter.addCount(count, false);
  48005. };
  48006. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  48007. this._updateLayoutCounter.addCount(count, false);
  48008. };
  48009. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  48010. this._updatePositioningCounter.addCount(count, false);
  48011. };
  48012. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  48013. this._updateLocalTransformCounter.addCount(count, false);
  48014. };
  48015. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  48016. this._updateGlobalTransformCounter.addCount(count, false);
  48017. };
  48018. Canvas2D.prototype._updateTrackedNodes = function () {
  48019. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  48020. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  48021. var rh = this.engine.getRenderHeight();
  48022. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  48023. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  48024. var group = _a[_i];
  48025. if (group.isDisposed || !group.isVisible) {
  48026. continue;
  48027. }
  48028. var node = group.trackedNode;
  48029. var worldMtx = node.getWorldMatrix();
  48030. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  48031. group.x = Math.round(proj.x);
  48032. group.y = Math.round(rh - proj.y);
  48033. }
  48034. };
  48035. /**
  48036. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  48037. */
  48038. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  48039. this._updateCanvasState(forceRecompute);
  48040. };
  48041. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  48042. if (this._globalTransformStep < 2) {
  48043. return;
  48044. }
  48045. var n = this.worldSpaceCanvasNode;
  48046. var bi = n.getBoundingInfo().boundingBox;
  48047. var v = bi.vectorsWorld;
  48048. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  48049. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  48050. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  48051. var projPoints = new Array(4);
  48052. for (var i = 0; i < 4; i++) {
  48053. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  48054. }
  48055. var left = projPoints[3].subtract(projPoints[0]).length();
  48056. var top = projPoints[3].subtract(projPoints[1]).length();
  48057. var right = projPoints[1].subtract(projPoints[2]).length();
  48058. var bottom = projPoints[2].subtract(projPoints[0]).length();
  48059. var w = Math.round(Math.max(top, bottom));
  48060. var h = Math.round(Math.max(right, left));
  48061. var isW = w > h;
  48062. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  48063. var edge = Math.max(w, h);
  48064. if (edge < 256) {
  48065. edge = 256;
  48066. }
  48067. else {
  48068. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  48069. }
  48070. // Clip values if needed
  48071. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  48072. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  48073. if (newScale !== this.scale) {
  48074. var scale = newScale;
  48075. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  48076. this._setRenderingScale(scale);
  48077. }
  48078. };
  48079. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  48080. // Check if the update has already been made for this render Frame
  48081. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  48082. return;
  48083. }
  48084. // Detect a change of rendering size
  48085. var renderingSizeChanged = false;
  48086. var newWidth = this.engine.getRenderWidth();
  48087. if (newWidth !== this._renderingSize.width) {
  48088. renderingSizeChanged = true;
  48089. }
  48090. this._renderingSize.width = newWidth;
  48091. var newHeight = this.engine.getRenderHeight();
  48092. if (newHeight !== this._renderingSize.height) {
  48093. renderingSizeChanged = true;
  48094. }
  48095. this._renderingSize.height = newHeight;
  48096. // If the canvas fit the rendering size and it changed, update
  48097. if (renderingSizeChanged && this._fitRenderingDevice) {
  48098. this.size = this._renderingSize;
  48099. if (this._background) {
  48100. this._background.size = this.size;
  48101. }
  48102. // Dirty the Layout at the Canvas level to recompute as the size changed
  48103. this._setLayoutDirty();
  48104. }
  48105. var context = new BABYLON.PrepareRender2DContext();
  48106. ++this._globalTransformProcessStep;
  48107. this.updateCachedStates(false);
  48108. this._prepareGroupRender(context);
  48109. this._updateRenderId = this.scene.getRenderId();
  48110. };
  48111. /**
  48112. * Method that renders the Canvas, you should not invoke
  48113. */
  48114. Canvas2D.prototype._render = function () {
  48115. this._initPerfMetrics();
  48116. this._updateTrackedNodes();
  48117. this._updateCanvasState(false);
  48118. // Nothing to do is the Canvas is not visible
  48119. if (this.isVisible === false) {
  48120. return;
  48121. }
  48122. if (!this._isScreenSpace) {
  48123. this._updateAdaptiveSizeWorldCanvas();
  48124. }
  48125. this._updateCanvasState(false);
  48126. if (this._primPointerInfo.canvasPointerPos) {
  48127. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  48128. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  48129. }
  48130. this.engine.setState(false);
  48131. this._groupRender();
  48132. if (!this._isScreenSpace) {
  48133. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  48134. this.worldSpaceCacheChanged();
  48135. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  48136. }
  48137. }
  48138. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  48139. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  48140. this._cachedCanvasGroup._renderCachedCanvas();
  48141. }
  48142. this._fetchPerfMetrics();
  48143. this._updateProfileCanvas();
  48144. };
  48145. /**
  48146. * Internal method that allocate a cache for the given group.
  48147. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  48148. * @param group The group to allocate the cache of.
  48149. * @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.
  48150. */
  48151. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  48152. if (useMipMap === void 0) { useMipMap = false; }
  48153. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  48154. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  48155. // Determine size
  48156. var size = group.actualSize;
  48157. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  48158. if (minSize) {
  48159. size.width = Math.max(minSize.width, size.width);
  48160. size.height = Math.max(minSize.height, size.height);
  48161. }
  48162. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  48163. // Try to find a spot in one of the cached texture
  48164. var res = null;
  48165. var map;
  48166. for (var _i = 0; _i < mapArray.length; _i++) {
  48167. var _map = mapArray[_i];
  48168. map = _map;
  48169. var node = map.allocateRect(size);
  48170. if (node) {
  48171. res = { node: node, texture: map };
  48172. break;
  48173. }
  48174. }
  48175. // Couldn't find a map that could fit the rect, create a new map for it
  48176. if (!res) {
  48177. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  48178. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  48179. if (size.width > mapSize.width || size.height > mapSize.height) {
  48180. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  48181. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  48182. }
  48183. var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
  48184. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  48185. map.hasAlpha = true;
  48186. map.anisotropicFilteringLevel = 4;
  48187. mapArray.splice(0, 0, map);
  48188. var node = map.allocateRect(size);
  48189. res = { node: node, texture: map };
  48190. }
  48191. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  48192. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  48193. if (group !== this || this._isScreenSpace) {
  48194. var node = res.node;
  48195. // 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
  48196. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  48197. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  48198. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  48199. sprite.zOrder = 1;
  48200. sprite.origin = BABYLON.Vector2.Zero();
  48201. }
  48202. else {
  48203. 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 });
  48204. sprite.origin = group.origin.clone();
  48205. sprite.addExternalData("__cachedGroup__", group);
  48206. sprite.pointerEventObservable.add(function (e, s) {
  48207. if (group.pointerEventObservable !== null) {
  48208. group.pointerEventObservable.notifyObservers(e, s.mask);
  48209. }
  48210. });
  48211. res.sprite = sprite;
  48212. }
  48213. }
  48214. return res;
  48215. };
  48216. /**
  48217. * Internal method used to register a Scene Node to track position for the given group
  48218. * Do not invoke this method, for internal purpose only.
  48219. * @param group the group to track its associated Scene Node
  48220. */
  48221. Canvas2D.prototype._registerTrackedNode = function (group) {
  48222. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  48223. return;
  48224. }
  48225. this._trackedGroups.push(group);
  48226. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  48227. };
  48228. /**
  48229. * Internal method used to unregister a tracked Scene Node
  48230. * Do not invoke this method, it's for internal purpose only.
  48231. * @param group the group to unregister its tracked Scene Node from.
  48232. */
  48233. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  48234. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  48235. return;
  48236. }
  48237. var i = this._trackedGroups.indexOf(group);
  48238. if (i !== -1) {
  48239. this._trackedGroups.splice(i, 1);
  48240. }
  48241. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  48242. };
  48243. /**
  48244. * Get a Solid Color Brush instance matching the given color.
  48245. * @param color The color to retrieve
  48246. * @return A shared instance of the SolidColorBrush2D class that use the given color
  48247. */
  48248. Canvas2D.GetSolidColorBrush = function (color) {
  48249. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  48250. };
  48251. /**
  48252. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  48253. * @param color The color to retrieve
  48254. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  48255. */
  48256. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  48257. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  48258. };
  48259. /**
  48260. * Get a Gradient Color Brush
  48261. * @param color1 starting color
  48262. * @param color2 engine color
  48263. * @param translation translation vector to apply. default is [0;0]
  48264. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  48265. * @param scale scaling factor to apply. default is 1.
  48266. */
  48267. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  48268. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  48269. if (rotation === void 0) { rotation = 0; }
  48270. if (scale === void 0) { scale = 1; }
  48271. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  48272. };
  48273. /**
  48274. * Create a solid or gradient brush from a string value.
  48275. * @param brushString should be either
  48276. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  48277. * - "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.
  48278. */
  48279. Canvas2D.GetBrushFromString = function (brushString) {
  48280. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  48281. brushString = brushString.trim();
  48282. var split = brushString.split(",");
  48283. // Solid, formatted as: "[solid:]#FF808080"
  48284. if (split.length === 1) {
  48285. var value = null;
  48286. if (brushString.indexOf("solid:") === 0) {
  48287. value = brushString.substr(6).trim();
  48288. }
  48289. else if (brushString.indexOf("#") === 0) {
  48290. value = brushString;
  48291. }
  48292. else {
  48293. return null;
  48294. }
  48295. return Canvas2D.GetSolidColorBrushFromHex(value);
  48296. }
  48297. else {
  48298. if (split[0].indexOf("gradient:") === 0) {
  48299. split[0] = split[0].substr(9).trim();
  48300. }
  48301. try {
  48302. var start = BABYLON.Color4.FromHexString(split[0].trim());
  48303. var end = BABYLON.Color4.FromHexString(split[1].trim());
  48304. var t = BABYLON.Vector2.Zero();
  48305. if (split.length > 2) {
  48306. var v = split[2].trim();
  48307. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  48308. return null;
  48309. }
  48310. var sep = v.indexOf(":");
  48311. var x = parseFloat(v.substr(1, sep));
  48312. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  48313. t = new BABYLON.Vector2(x, y);
  48314. }
  48315. var r = 0;
  48316. if (split.length > 3) {
  48317. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  48318. }
  48319. var s = 1;
  48320. if (split.length > 4) {
  48321. s = parseFloat(split[4].trim());
  48322. }
  48323. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  48324. }
  48325. catch (e) {
  48326. return null;
  48327. }
  48328. }
  48329. };
  48330. /**
  48331. * 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.
  48332. * This strategy doesn't allow primitives added directly as children of the Canvas.
  48333. * 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.
  48334. */
  48335. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  48336. /**
  48337. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  48338. * 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.
  48339. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  48340. * 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.
  48341. */
  48342. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  48343. /**
  48344. * 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).
  48345. */
  48346. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  48347. /**
  48348. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  48349. * 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).
  48350. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  48351. */
  48352. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  48353. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  48354. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  48355. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  48356. Canvas2D._m = BABYLON.Matrix.Identity();
  48357. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  48358. /**
  48359. * Define the default size used for both the width and height of a MapTexture to allocate.
  48360. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  48361. */
  48362. Canvas2D._groupTextureCacheSize = 1024;
  48363. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  48364. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  48365. Canvas2D = __decorate([
  48366. BABYLON.className("Canvas2D")
  48367. ], Canvas2D);
  48368. return Canvas2D;
  48369. })(BABYLON.Group2D);
  48370. BABYLON.Canvas2D = Canvas2D;
  48371. var WorldSpaceCanvas2D = (function (_super) {
  48372. __extends(WorldSpaceCanvas2D, _super);
  48373. /**
  48374. * 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.
  48375. * 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.
  48376. * @param scene the Scene that owns the Canvas
  48377. * @param size the dimension of the Canvas in World Space
  48378. * @param settings a combination of settings, possible ones are
  48379. * - children: an array of direct children primitives
  48380. * - id: a text identifier, for information purpose only, default is null.
  48381. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  48382. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  48383. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  48384. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  48385. * - 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).
  48386. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  48387. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  48388. * - 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.
  48389. * - 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.
  48390. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  48391. * - 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.
  48392. * - 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.
  48393. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48394. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48395. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48396. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48397. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  48398. */
  48399. function WorldSpaceCanvas2D(scene, size, settings) {
  48400. BABYLON.Prim2DBase._isCanvasInit = true;
  48401. var s = settings;
  48402. s.isScreenSpace = false;
  48403. s.size = size.clone();
  48404. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  48405. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  48406. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  48407. }
  48408. _super.call(this, scene, settings);
  48409. BABYLON.Prim2DBase._isCanvasInit = false;
  48410. this._renderableData._useMipMap = true;
  48411. this._renderableData._anisotropicLevel = 8;
  48412. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  48413. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  48414. //}
  48415. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  48416. var id = settings ? settings.id || null : null;
  48417. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  48418. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  48419. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  48420. if (settings.maxAdaptiveCanvasSize == null) {
  48421. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  48422. }
  48423. else {
  48424. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  48425. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  48426. }
  48427. if (createWorldSpaceNode) {
  48428. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  48429. var vertexData = BABYLON.VertexData.CreatePlane({
  48430. width: size.width,
  48431. height: size.height,
  48432. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  48433. });
  48434. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  48435. this.applyCachedTexture(vertexData, mtl);
  48436. vertexData.applyToMesh(plane, true);
  48437. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  48438. mtl.disableLighting = true;
  48439. mtl.useAlphaFromDiffuseTexture = true;
  48440. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  48441. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  48442. plane.material = mtl;
  48443. this._worldSpaceNode = plane;
  48444. }
  48445. else {
  48446. this._worldSpaceNode = settings.customWorldSpaceNode;
  48447. this.applyCachedTexture(null, null);
  48448. }
  48449. }
  48450. WorldSpaceCanvas2D = __decorate([
  48451. BABYLON.className("WorldSpaceCanvas2D")
  48452. ], WorldSpaceCanvas2D);
  48453. return WorldSpaceCanvas2D;
  48454. })(Canvas2D);
  48455. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  48456. var ScreenSpaceCanvas2D = (function (_super) {
  48457. __extends(ScreenSpaceCanvas2D, _super);
  48458. /**
  48459. * 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.
  48460. * 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.
  48461. * All caching strategies will be available.
  48462. * 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]
  48463. * @param scene the Scene that owns the Canvas
  48464. * @param settings a combination of settings, possible ones are
  48465. * - children: an array of direct children primitives
  48466. * - id: a text identifier, for information purpose only
  48467. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  48468. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  48469. * - 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]
  48470. * - width: the width of the Canvas. you can alternatively use the size setting.
  48471. * - height: the height of the Canvas. you can alternatively use the size setting.
  48472. * - 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
  48473. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  48474. * - 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.
  48475. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  48476. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  48477. * - 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.
  48478. * - 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.
  48479. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  48480. * - 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.
  48481. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48482. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48483. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48484. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48485. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  48486. */
  48487. function ScreenSpaceCanvas2D(scene, settings) {
  48488. BABYLON.Prim2DBase._isCanvasInit = true;
  48489. _super.call(this, scene, settings);
  48490. }
  48491. ScreenSpaceCanvas2D = __decorate([
  48492. BABYLON.className("ScreenSpaceCanvas2D")
  48493. ], ScreenSpaceCanvas2D);
  48494. return ScreenSpaceCanvas2D;
  48495. })(Canvas2D);
  48496. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  48497. })(BABYLON || (BABYLON = {}));
  48498. var BABYLON;
  48499. (function (BABYLON) {
  48500. /**
  48501. * This is the class that is used to display a World Space Canvas into a 3D scene
  48502. */
  48503. var WorldSpaceCanvas2DNode = (function (_super) {
  48504. __extends(WorldSpaceCanvas2DNode, _super);
  48505. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  48506. _super.call(this, name, scene);
  48507. this._canvas = canvas;
  48508. }
  48509. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  48510. _super.prototype.dispose.call(this);
  48511. if (this._canvas) {
  48512. this._canvas.dispose();
  48513. this._canvas = null;
  48514. }
  48515. };
  48516. return WorldSpaceCanvas2DNode;
  48517. })(BABYLON.Mesh);
  48518. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  48519. })(BABYLON || (BABYLON = {}));
  48520. var BABYLON;
  48521. (function (BABYLON) {
  48522. var LayoutEngineBase = (function () {
  48523. function LayoutEngineBase() {
  48524. this.layoutDirtyOnPropertyChangedMask = 0;
  48525. }
  48526. LayoutEngineBase.prototype.updateLayout = function (prim) {
  48527. };
  48528. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  48529. get: function () {
  48530. return false;
  48531. },
  48532. enumerable: true,
  48533. configurable: true
  48534. });
  48535. LayoutEngineBase.prototype.isLocked = function () {
  48536. return this._isLocked;
  48537. };
  48538. LayoutEngineBase.prototype.lock = function () {
  48539. if (this._isLocked) {
  48540. return false;
  48541. }
  48542. this._isLocked = true;
  48543. return true;
  48544. };
  48545. LayoutEngineBase = __decorate([
  48546. BABYLON.className("LayoutEngineBase")
  48547. ], LayoutEngineBase);
  48548. return LayoutEngineBase;
  48549. })();
  48550. BABYLON.LayoutEngineBase = LayoutEngineBase;
  48551. var CanvasLayoutEngine = (function (_super) {
  48552. __extends(CanvasLayoutEngine, _super);
  48553. function CanvasLayoutEngine() {
  48554. _super.apply(this, arguments);
  48555. }
  48556. // A very simple (no) layout computing...
  48557. // The Canvas and its direct children gets the Canvas' size as Layout Area
  48558. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  48559. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  48560. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  48561. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  48562. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  48563. var child = _a[_i];
  48564. this._doUpdate(child);
  48565. }
  48566. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  48567. }
  48568. };
  48569. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  48570. // Canvas ?
  48571. if (prim instanceof BABYLON.Canvas2D) {
  48572. prim.layoutArea = prim.actualSize;
  48573. }
  48574. else if (prim.parent instanceof BABYLON.Canvas2D) {
  48575. prim.layoutArea = prim.owner.actualSize;
  48576. }
  48577. else {
  48578. prim.layoutArea = prim.parent.contentArea;
  48579. }
  48580. };
  48581. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  48582. get: function () {
  48583. return true;
  48584. },
  48585. enumerable: true,
  48586. configurable: true
  48587. });
  48588. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  48589. CanvasLayoutEngine = __decorate([
  48590. BABYLON.className("CanvasLayoutEngine")
  48591. ], CanvasLayoutEngine);
  48592. return CanvasLayoutEngine;
  48593. })(LayoutEngineBase);
  48594. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  48595. var StackPanelLayoutEngine = (function (_super) {
  48596. __extends(StackPanelLayoutEngine, _super);
  48597. function StackPanelLayoutEngine() {
  48598. _super.call(this);
  48599. this._isHorizontal = true;
  48600. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  48601. }
  48602. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  48603. get: function () {
  48604. if (!StackPanelLayoutEngine._horizontal) {
  48605. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  48606. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  48607. StackPanelLayoutEngine._horizontal.lock();
  48608. }
  48609. return StackPanelLayoutEngine._horizontal;
  48610. },
  48611. enumerable: true,
  48612. configurable: true
  48613. });
  48614. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  48615. get: function () {
  48616. if (!StackPanelLayoutEngine._vertical) {
  48617. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  48618. StackPanelLayoutEngine._vertical.isHorizontal = false;
  48619. StackPanelLayoutEngine._vertical.lock();
  48620. }
  48621. return StackPanelLayoutEngine._vertical;
  48622. },
  48623. enumerable: true,
  48624. configurable: true
  48625. });
  48626. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  48627. get: function () {
  48628. return this._isHorizontal;
  48629. },
  48630. set: function (val) {
  48631. if (this.isLocked()) {
  48632. return;
  48633. }
  48634. this._isHorizontal = val;
  48635. },
  48636. enumerable: true,
  48637. configurable: true
  48638. });
  48639. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  48640. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  48641. var x = 0;
  48642. var y = 0;
  48643. var h = this.isHorizontal;
  48644. var max = 0;
  48645. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  48646. var child = _a[_i];
  48647. var layoutArea = child.layoutArea;
  48648. child.margin.computeArea(child.actualSize, layoutArea);
  48649. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  48650. }
  48651. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  48652. var child = _c[_b];
  48653. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  48654. var layoutArea = child.layoutArea;
  48655. if (h) {
  48656. x += layoutArea.width;
  48657. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  48658. }
  48659. else {
  48660. y += layoutArea.height;
  48661. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  48662. }
  48663. }
  48664. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  48665. }
  48666. };
  48667. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  48668. get: function () {
  48669. return false;
  48670. },
  48671. enumerable: true,
  48672. configurable: true
  48673. });
  48674. StackPanelLayoutEngine._horizontal = null;
  48675. StackPanelLayoutEngine._vertical = null;
  48676. StackPanelLayoutEngine = __decorate([
  48677. BABYLON.className("StackPanelLayoutEngine")
  48678. ], StackPanelLayoutEngine);
  48679. return StackPanelLayoutEngine;
  48680. })(LayoutEngineBase);
  48681. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  48682. })(BABYLON || (BABYLON = {}));
  48683. var BABYLON;
  48684. (function (BABYLON) {
  48685. var ShaderMaterial = (function (_super) {
  48686. __extends(ShaderMaterial, _super);
  48687. function ShaderMaterial(name, scene, shaderPath, options) {
  48688. _super.call(this, name, scene);
  48689. this._textures = {};
  48690. this._textureArrays = {};
  48691. this._floats = {};
  48692. this._floatsArrays = {};
  48693. this._colors3 = {};
  48694. this._colors4 = {};
  48695. this._vectors2 = {};
  48696. this._vectors3 = {};
  48697. this._vectors4 = {};
  48698. this._matrices = {};
  48699. this._matrices3x3 = {};
  48700. this._matrices2x2 = {};
  48701. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48702. this._shaderPath = shaderPath;
  48703. options.needAlphaBlending = options.needAlphaBlending || false;
  48704. options.needAlphaTesting = options.needAlphaTesting || false;
  48705. options.attributes = options.attributes || ["position", "normal", "uv"];
  48706. options.uniforms = options.uniforms || ["worldViewProjection"];
  48707. options.samplers = options.samplers || [];
  48708. options.defines = options.defines || [];
  48709. this._options = options;
  48710. }
  48711. ShaderMaterial.prototype.needAlphaBlending = function () {
  48712. return this._options.needAlphaBlending;
  48713. };
  48714. ShaderMaterial.prototype.needAlphaTesting = function () {
  48715. return this._options.needAlphaTesting;
  48716. };
  48717. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48718. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48719. this._options.uniforms.push(uniformName);
  48720. }
  48721. };
  48722. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48723. if (this._options.samplers.indexOf(name) === -1) {
  48724. this._options.samplers.push(name);
  48725. }
  48726. this._textures[name] = texture;
  48727. return this;
  48728. };
  48729. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48730. if (this._options.samplers.indexOf(name) === -1) {
  48731. this._options.samplers.push(name);
  48732. }
  48733. this._checkUniform(name);
  48734. this._textureArrays[name] = textures;
  48735. return this;
  48736. };
  48737. ShaderMaterial.prototype.setFloat = function (name, value) {
  48738. this._checkUniform(name);
  48739. this._floats[name] = value;
  48740. return this;
  48741. };
  48742. ShaderMaterial.prototype.setFloats = function (name, value) {
  48743. this._checkUniform(name);
  48744. this._floatsArrays[name] = value;
  48745. return this;
  48746. };
  48747. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48748. this._checkUniform(name);
  48749. this._colors3[name] = value;
  48750. return this;
  48751. };
  48752. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48753. this._checkUniform(name);
  48754. this._colors4[name] = value;
  48755. return this;
  48756. };
  48757. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48758. this._checkUniform(name);
  48759. this._vectors2[name] = value;
  48760. return this;
  48761. };
  48762. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48763. this._checkUniform(name);
  48764. this._vectors3[name] = value;
  48765. return this;
  48766. };
  48767. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48768. this._checkUniform(name);
  48769. this._vectors4[name] = value;
  48770. return this;
  48771. };
  48772. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48773. this._checkUniform(name);
  48774. this._matrices[name] = value;
  48775. return this;
  48776. };
  48777. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48778. this._checkUniform(name);
  48779. this._matrices3x3[name] = value;
  48780. return this;
  48781. };
  48782. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48783. this._checkUniform(name);
  48784. this._matrices2x2[name] = value;
  48785. return this;
  48786. };
  48787. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48788. var scene = this.getScene();
  48789. var engine = scene.getEngine();
  48790. if (!this.checkReadyOnEveryCall) {
  48791. if (this._renderId === scene.getRenderId()) {
  48792. return true;
  48793. }
  48794. }
  48795. // Instances
  48796. var defines = [];
  48797. var fallbacks = new BABYLON.EffectFallbacks();
  48798. if (useInstances) {
  48799. defines.push("#define INSTANCES");
  48800. }
  48801. for (var index = 0; index < this._options.defines.length; index++) {
  48802. defines.push(this._options.defines[index]);
  48803. }
  48804. // Bones
  48805. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  48806. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48807. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48808. fallbacks.addCPUSkinningFallback(0, mesh);
  48809. }
  48810. // Alpha test
  48811. if (engine.getAlphaTesting()) {
  48812. defines.push("#define ALPHATEST");
  48813. }
  48814. var previousEffect = this._effect;
  48815. var join = defines.join("\n");
  48816. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  48817. if (!this._effect.isReady()) {
  48818. return false;
  48819. }
  48820. if (previousEffect !== this._effect) {
  48821. scene.resetCachedMaterial();
  48822. }
  48823. this._renderId = scene.getRenderId();
  48824. return true;
  48825. };
  48826. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48827. var scene = this.getScene();
  48828. if (this._options.uniforms.indexOf("world") !== -1) {
  48829. this._effect.setMatrix("world", world);
  48830. }
  48831. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48832. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48833. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48834. }
  48835. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48836. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48837. }
  48838. };
  48839. ShaderMaterial.prototype.bind = function (world, mesh) {
  48840. // Std values
  48841. this.bindOnlyWorldMatrix(world);
  48842. if (this.getScene().getCachedMaterial() !== this) {
  48843. if (this._options.uniforms.indexOf("view") !== -1) {
  48844. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48845. }
  48846. if (this._options.uniforms.indexOf("projection") !== -1) {
  48847. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48848. }
  48849. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48850. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48851. }
  48852. // Bones
  48853. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  48854. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48855. }
  48856. var name;
  48857. // Texture
  48858. for (name in this._textures) {
  48859. this._effect.setTexture(name, this._textures[name]);
  48860. }
  48861. // Texture arrays
  48862. for (name in this._textureArrays) {
  48863. this._effect.setTextureArray(name, this._textureArrays[name]);
  48864. }
  48865. // Float
  48866. for (name in this._floats) {
  48867. this._effect.setFloat(name, this._floats[name]);
  48868. }
  48869. // Float s
  48870. for (name in this._floatsArrays) {
  48871. this._effect.setArray(name, this._floatsArrays[name]);
  48872. }
  48873. // Color3
  48874. for (name in this._colors3) {
  48875. this._effect.setColor3(name, this._colors3[name]);
  48876. }
  48877. // Color4
  48878. for (name in this._colors4) {
  48879. var color = this._colors4[name];
  48880. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48881. }
  48882. // Vector2
  48883. for (name in this._vectors2) {
  48884. this._effect.setVector2(name, this._vectors2[name]);
  48885. }
  48886. // Vector3
  48887. for (name in this._vectors3) {
  48888. this._effect.setVector3(name, this._vectors3[name]);
  48889. }
  48890. // Vector4
  48891. for (name in this._vectors4) {
  48892. this._effect.setVector4(name, this._vectors4[name]);
  48893. }
  48894. // Matrix
  48895. for (name in this._matrices) {
  48896. this._effect.setMatrix(name, this._matrices[name]);
  48897. }
  48898. // Matrix 3x3
  48899. for (name in this._matrices3x3) {
  48900. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48901. }
  48902. // Matrix 2x2
  48903. for (name in this._matrices2x2) {
  48904. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48905. }
  48906. }
  48907. _super.prototype.bind.call(this, world, mesh);
  48908. };
  48909. ShaderMaterial.prototype.clone = function (name) {
  48910. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48911. return newShaderMaterial;
  48912. };
  48913. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48914. if (forceDisposeTextures) {
  48915. var name;
  48916. for (name in this._textures) {
  48917. this._textures[name].dispose();
  48918. }
  48919. for (name in this._textureArrays) {
  48920. var array = this._textureArrays[name];
  48921. for (var index = 0; index < array.length; index++) {
  48922. array[index].dispose();
  48923. }
  48924. }
  48925. }
  48926. this._textures = {};
  48927. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48928. };
  48929. ShaderMaterial.prototype.serialize = function () {
  48930. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48931. serializationObject.customType = "BABYLON.ShaderMaterial";
  48932. serializationObject.options = this._options;
  48933. serializationObject.shaderPath = this._shaderPath;
  48934. var name;
  48935. // Texture
  48936. serializationObject.textures = {};
  48937. for (name in this._textures) {
  48938. serializationObject.textures[name] = this._textures[name].serialize();
  48939. }
  48940. // Texture arrays
  48941. serializationObject.textureArrays = {};
  48942. for (name in this._textureArrays) {
  48943. serializationObject.textureArrays[name] = [];
  48944. var array = this._textureArrays[name];
  48945. for (var index = 0; index < array.length; index++) {
  48946. serializationObject.textureArrays[name].push(array[index].serialize());
  48947. }
  48948. }
  48949. // Float
  48950. serializationObject.floats = {};
  48951. for (name in this._floats) {
  48952. serializationObject.floats[name] = this._floats[name];
  48953. }
  48954. // Float s
  48955. serializationObject.floatArrays = {};
  48956. for (name in this._floatsArrays) {
  48957. serializationObject.floatArrays[name] = this._floatsArrays[name];
  48958. }
  48959. // Color3
  48960. serializationObject.colors3 = {};
  48961. for (name in this._colors3) {
  48962. serializationObject.colors3[name] = this._colors3[name].asArray();
  48963. }
  48964. // Color4
  48965. serializationObject.colors4 = {};
  48966. for (name in this._colors4) {
  48967. serializationObject.colors4[name] = this._colors4[name].asArray();
  48968. }
  48969. // Vector2
  48970. serializationObject.vectors2 = {};
  48971. for (name in this._vectors2) {
  48972. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48973. }
  48974. // Vector3
  48975. serializationObject.vectors3 = {};
  48976. for (name in this._vectors3) {
  48977. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48978. }
  48979. // Vector4
  48980. serializationObject.vectors4 = {};
  48981. for (name in this._vectors4) {
  48982. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48983. }
  48984. // Matrix
  48985. serializationObject.matrices = {};
  48986. for (name in this._matrices) {
  48987. serializationObject.matrices[name] = this._matrices[name].asArray();
  48988. }
  48989. // Matrix 3x3
  48990. serializationObject.matrices3x3 = {};
  48991. for (name in this._matrices3x3) {
  48992. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48993. }
  48994. // Matrix 2x2
  48995. serializationObject.matrices2x2 = {};
  48996. for (name in this._matrices2x2) {
  48997. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48998. }
  48999. return serializationObject;
  49000. };
  49001. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  49002. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  49003. var name;
  49004. // Texture
  49005. for (name in source.textures) {
  49006. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  49007. }
  49008. // Texture arrays
  49009. for (name in source.textureArrays) {
  49010. var array = source.textureArrays[name];
  49011. var textureArray = new Array();
  49012. for (var index = 0; index < array.length; index++) {
  49013. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  49014. }
  49015. material.setTextureArray(name, textureArray);
  49016. }
  49017. // Float
  49018. for (name in source.floats) {
  49019. material.setFloat(name, source.floats[name]);
  49020. }
  49021. // Float s
  49022. for (name in source.floatsArrays) {
  49023. material.setFloats(name, source.floatsArrays[name]);
  49024. }
  49025. // Color3
  49026. for (name in source.colors3) {
  49027. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  49028. }
  49029. // Color4
  49030. for (name in source.colors4) {
  49031. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  49032. }
  49033. // Vector2
  49034. for (name in source.vectors2) {
  49035. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  49036. }
  49037. // Vector3
  49038. for (name in source.vectors3) {
  49039. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  49040. }
  49041. // Vector4
  49042. for (name in source.vectors4) {
  49043. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  49044. }
  49045. // Matrix
  49046. for (name in source.matrices) {
  49047. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  49048. }
  49049. // Matrix 3x3
  49050. for (name in source.matrices3x3) {
  49051. material.setMatrix3x3(name, source.matrices3x3[name]);
  49052. }
  49053. // Matrix 2x2
  49054. for (name in source.matrices2x2) {
  49055. material.setMatrix2x2(name, source.matrices2x2[name]);
  49056. }
  49057. return material;
  49058. };
  49059. return ShaderMaterial;
  49060. })(BABYLON.Material);
  49061. BABYLON.ShaderMaterial = ShaderMaterial;
  49062. })(BABYLON || (BABYLON = {}));
  49063. var BABYLON;
  49064. (function (BABYLON) {
  49065. var Internals;
  49066. (function (Internals) {
  49067. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  49068. // All values and structures referenced from:
  49069. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  49070. var DDS_MAGIC = 0x20534444;
  49071. 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;
  49072. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  49073. 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;
  49074. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  49075. function FourCCToInt32(value) {
  49076. return value.charCodeAt(0) +
  49077. (value.charCodeAt(1) << 8) +
  49078. (value.charCodeAt(2) << 16) +
  49079. (value.charCodeAt(3) << 24);
  49080. }
  49081. function Int32ToFourCC(value) {
  49082. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  49083. }
  49084. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  49085. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  49086. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  49087. var headerLengthInt = 31; // The header length in 32 bit ints
  49088. // Offsets into the header array
  49089. var off_magic = 0;
  49090. var off_size = 1;
  49091. var off_flags = 2;
  49092. var off_height = 3;
  49093. var off_width = 4;
  49094. var off_mipmapCount = 7;
  49095. var off_pfFlags = 20;
  49096. var off_pfFourCC = 21;
  49097. var off_RGBbpp = 22;
  49098. var off_RMask = 23;
  49099. var off_GMask = 24;
  49100. var off_BMask = 25;
  49101. var off_AMask = 26;
  49102. var off_caps1 = 27;
  49103. var off_caps2 = 28;
  49104. ;
  49105. var DDSTools = (function () {
  49106. function DDSTools() {
  49107. }
  49108. DDSTools.GetDDSInfo = function (arrayBuffer) {
  49109. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  49110. var mipmapCount = 1;
  49111. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  49112. mipmapCount = Math.max(1, header[off_mipmapCount]);
  49113. }
  49114. return {
  49115. width: header[off_width],
  49116. height: header[off_height],
  49117. mipmapCount: mipmapCount,
  49118. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  49119. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  49120. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  49121. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  49122. };
  49123. };
  49124. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49125. var byteArray = new Uint8Array(dataLength);
  49126. var srcData = new Uint8Array(arrayBuffer);
  49127. var index = 0;
  49128. for (var y = height - 1; y >= 0; y--) {
  49129. for (var x = 0; x < width; x++) {
  49130. var srcPos = dataOffset + (x + y * width) * 4;
  49131. byteArray[index + 2] = srcData[srcPos];
  49132. byteArray[index + 1] = srcData[srcPos + 1];
  49133. byteArray[index] = srcData[srcPos + 2];
  49134. byteArray[index + 3] = srcData[srcPos + 3];
  49135. index += 4;
  49136. }
  49137. }
  49138. return byteArray;
  49139. };
  49140. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49141. var byteArray = new Uint8Array(dataLength);
  49142. var srcData = new Uint8Array(arrayBuffer);
  49143. var index = 0;
  49144. for (var y = height - 1; y >= 0; y--) {
  49145. for (var x = 0; x < width; x++) {
  49146. var srcPos = dataOffset + (x + y * width) * 3;
  49147. byteArray[index + 2] = srcData[srcPos];
  49148. byteArray[index + 1] = srcData[srcPos + 1];
  49149. byteArray[index] = srcData[srcPos + 2];
  49150. index += 3;
  49151. }
  49152. }
  49153. return byteArray;
  49154. };
  49155. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49156. var byteArray = new Uint8Array(dataLength);
  49157. var srcData = new Uint8Array(arrayBuffer);
  49158. var index = 0;
  49159. for (var y = height - 1; y >= 0; y--) {
  49160. for (var x = 0; x < width; x++) {
  49161. var srcPos = dataOffset + (x + y * width);
  49162. byteArray[index] = srcData[srcPos];
  49163. index++;
  49164. }
  49165. }
  49166. return byteArray;
  49167. };
  49168. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  49169. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  49170. if (header[off_magic] != DDS_MAGIC) {
  49171. BABYLON.Tools.Error("Invalid magic number in DDS header");
  49172. return;
  49173. }
  49174. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  49175. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  49176. return;
  49177. }
  49178. if (info.isFourCC) {
  49179. fourCC = header[off_pfFourCC];
  49180. switch (fourCC) {
  49181. case FOURCC_DXT1:
  49182. blockBytes = 8;
  49183. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  49184. break;
  49185. case FOURCC_DXT3:
  49186. blockBytes = 16;
  49187. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  49188. break;
  49189. case FOURCC_DXT5:
  49190. blockBytes = 16;
  49191. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  49192. break;
  49193. default:
  49194. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  49195. return;
  49196. }
  49197. }
  49198. mipmapCount = 1;
  49199. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  49200. mipmapCount = Math.max(1, header[off_mipmapCount]);
  49201. }
  49202. var bpp = header[off_RGBbpp];
  49203. for (var face = 0; face < faces; face++) {
  49204. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  49205. width = header[off_width];
  49206. height = header[off_height];
  49207. dataOffset = header[off_size] + 4;
  49208. for (i = 0; i < mipmapCount; ++i) {
  49209. if (info.isRGB) {
  49210. if (bpp === 24) {
  49211. dataLength = width * height * 3;
  49212. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49213. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  49214. }
  49215. else {
  49216. dataLength = width * height * 4;
  49217. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49218. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  49219. }
  49220. }
  49221. else if (info.isLuminance) {
  49222. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  49223. var unpaddedRowSize = width;
  49224. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  49225. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  49226. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49227. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  49228. }
  49229. else {
  49230. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  49231. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  49232. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  49233. }
  49234. dataOffset += dataLength;
  49235. width *= 0.5;
  49236. height *= 0.5;
  49237. width = Math.max(1.0, width);
  49238. height = Math.max(1.0, height);
  49239. }
  49240. }
  49241. };
  49242. return DDSTools;
  49243. })();
  49244. Internals.DDSTools = DDSTools;
  49245. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49246. })(BABYLON || (BABYLON = {}));
  49247. var BABYLON;
  49248. (function (BABYLON) {
  49249. var CannonJSPlugin = (function () {
  49250. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  49251. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  49252. if (iterations === void 0) { iterations = 10; }
  49253. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  49254. this.name = "CannonJSPlugin";
  49255. this._physicsMaterials = [];
  49256. this._fixedTimeStep = 1 / 60;
  49257. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  49258. this._currentCollisionGroup = 2;
  49259. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  49260. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  49261. this._tmpPosition = BABYLON.Vector3.Zero();
  49262. this._tmpQuaternion = new BABYLON.Quaternion();
  49263. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  49264. this._tmpDeltaRotation = new BABYLON.Quaternion();
  49265. this._tmpUnityRotation = new BABYLON.Quaternion();
  49266. if (!this.isSupported()) {
  49267. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  49268. return;
  49269. }
  49270. this.world = new CANNON.World();
  49271. this.world.broadphase = new CANNON.NaiveBroadphase();
  49272. this.world.solver.iterations = iterations;
  49273. }
  49274. CannonJSPlugin.prototype.setGravity = function (gravity) {
  49275. this.world.gravity.copy(gravity);
  49276. };
  49277. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  49278. this._fixedTimeStep = timeStep;
  49279. };
  49280. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  49281. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  49282. };
  49283. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  49284. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  49285. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  49286. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  49287. };
  49288. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  49289. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  49290. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  49291. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  49292. };
  49293. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  49294. //parent-child relationship. Does this impostor has a parent impostor?
  49295. if (impostor.parent) {
  49296. if (impostor.physicsBody) {
  49297. this.removePhysicsBody(impostor);
  49298. //TODO is that needed?
  49299. impostor.forceUpdate();
  49300. }
  49301. return;
  49302. }
  49303. //should a new body be created for this impostor?
  49304. if (impostor.isBodyInitRequired()) {
  49305. var shape = this._createShape(impostor);
  49306. //unregister events, if body is being changed
  49307. var oldBody = impostor.physicsBody;
  49308. if (oldBody) {
  49309. this.removePhysicsBody(impostor);
  49310. }
  49311. //create the body and material
  49312. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  49313. var bodyCreationObject = {
  49314. mass: impostor.getParam("mass"),
  49315. material: material
  49316. };
  49317. // A simple extend, in case native options were used.
  49318. var nativeOptions = impostor.getParam("nativeOptions");
  49319. for (var key in nativeOptions) {
  49320. if (nativeOptions.hasOwnProperty(key)) {
  49321. bodyCreationObject[key] = nativeOptions[key];
  49322. }
  49323. }
  49324. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  49325. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  49326. this.world.addEventListener("preStep", impostor.beforeStep);
  49327. this.world.addEventListener("postStep", impostor.afterStep);
  49328. impostor.physicsBody.addShape(shape);
  49329. this.world.add(impostor.physicsBody);
  49330. //try to keep the body moving in the right direction by taking old properties.
  49331. //Should be tested!
  49332. if (oldBody) {
  49333. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  49334. impostor.physicsBody[param].copy(oldBody[param]);
  49335. });
  49336. }
  49337. this._processChildMeshes(impostor);
  49338. }
  49339. //now update the body's transformation
  49340. this._updatePhysicsBodyTransformation(impostor);
  49341. };
  49342. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  49343. var _this = this;
  49344. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  49345. if (meshChildren.length) {
  49346. var processMesh = function (localPosition, mesh) {
  49347. var childImpostor = mesh.getPhysicsImpostor();
  49348. if (childImpostor) {
  49349. var parent = childImpostor.parent;
  49350. if (parent !== mainImpostor) {
  49351. var localPosition = mesh.position;
  49352. if (childImpostor.physicsBody) {
  49353. _this.removePhysicsBody(childImpostor);
  49354. childImpostor.physicsBody = null;
  49355. }
  49356. childImpostor.parent = mainImpostor;
  49357. childImpostor.resetUpdateFlags();
  49358. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  49359. //Add the mass of the children.
  49360. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  49361. }
  49362. }
  49363. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  49364. };
  49365. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  49366. }
  49367. };
  49368. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  49369. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  49370. this.world.removeEventListener("preStep", impostor.beforeStep);
  49371. this.world.removeEventListener("postStep", impostor.afterStep);
  49372. this.world.remove(impostor.physicsBody);
  49373. };
  49374. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  49375. var mainBody = impostorJoint.mainImpostor.physicsBody;
  49376. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  49377. if (!mainBody || !connectedBody) {
  49378. return;
  49379. }
  49380. var constraint;
  49381. var jointData = impostorJoint.joint.jointData;
  49382. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  49383. var constraintData = {
  49384. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  49385. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  49386. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  49387. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  49388. maxForce: jointData.nativeParams.maxForce,
  49389. collideConnected: !!jointData.collision
  49390. };
  49391. //Not needed, Cannon has a collideConnected flag
  49392. /*if (!jointData.collision) {
  49393. //add 1st body to a collision group of its own, if it is not in 1
  49394. if (mainBody.collisionFilterGroup === 1) {
  49395. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  49396. this._currentCollisionGroup <<= 1;
  49397. }
  49398. if (connectedBody.collisionFilterGroup === 1) {
  49399. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  49400. this._currentCollisionGroup <<= 1;
  49401. }
  49402. //add their mask to the collisionFilterMask of each other:
  49403. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  49404. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  49405. }*/
  49406. switch (impostorJoint.joint.type) {
  49407. case BABYLON.PhysicsJoint.HingeJoint:
  49408. case BABYLON.PhysicsJoint.Hinge2Joint:
  49409. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  49410. break;
  49411. case BABYLON.PhysicsJoint.DistanceJoint:
  49412. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  49413. break;
  49414. case BABYLON.PhysicsJoint.SpringJoint:
  49415. var springData = jointData;
  49416. constraint = new CANNON.Spring(mainBody, connectedBody, {
  49417. restLength: springData.length,
  49418. stiffness: springData.stiffness,
  49419. damping: springData.damping,
  49420. localAnchorA: constraintData.pivotA,
  49421. localAnchorB: constraintData.pivotB
  49422. });
  49423. break;
  49424. case BABYLON.PhysicsJoint.LockJoint:
  49425. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  49426. break;
  49427. case BABYLON.PhysicsJoint.PointToPointJoint:
  49428. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  49429. default:
  49430. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  49431. break;
  49432. }
  49433. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  49434. constraint.collideConnected = !!jointData.collision;
  49435. impostorJoint.joint.physicsJoint = constraint;
  49436. //don't add spring as constraint, as it is not one.
  49437. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  49438. this.world.addConstraint(constraint);
  49439. }
  49440. else {
  49441. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  49442. constraint.applyForce();
  49443. });
  49444. }
  49445. };
  49446. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  49447. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  49448. };
  49449. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  49450. var index;
  49451. var mat;
  49452. for (index = 0; index < this._physicsMaterials.length; index++) {
  49453. mat = this._physicsMaterials[index];
  49454. if (mat.friction === friction && mat.restitution === restitution) {
  49455. return mat;
  49456. }
  49457. }
  49458. var currentMat = new CANNON.Material(name);
  49459. currentMat.friction = friction;
  49460. currentMat.restitution = restitution;
  49461. this._physicsMaterials.push(currentMat);
  49462. return currentMat;
  49463. };
  49464. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  49465. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  49466. };
  49467. CannonJSPlugin.prototype._createShape = function (impostor) {
  49468. var object = impostor.object;
  49469. var returnValue;
  49470. var extendSize = impostor.getObjectExtendSize();
  49471. switch (impostor.type) {
  49472. case BABYLON.PhysicsEngine.SphereImpostor:
  49473. var radiusX = extendSize.x;
  49474. var radiusY = extendSize.y;
  49475. var radiusZ = extendSize.z;
  49476. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  49477. break;
  49478. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  49479. case BABYLON.PhysicsImpostor.CylinderImpostor:
  49480. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  49481. break;
  49482. case BABYLON.PhysicsImpostor.BoxImpostor:
  49483. var box = extendSize.scale(0.5);
  49484. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  49485. break;
  49486. case BABYLON.PhysicsImpostor.PlaneImpostor:
  49487. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  49488. returnValue = new CANNON.Plane();
  49489. break;
  49490. case BABYLON.PhysicsImpostor.MeshImpostor:
  49491. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  49492. var rawFaces = object.getIndices ? object.getIndices() : [];
  49493. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  49494. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  49495. break;
  49496. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  49497. returnValue = this._createHeightmap(object);
  49498. break;
  49499. case BABYLON.PhysicsImpostor.ParticleImpostor:
  49500. returnValue = new CANNON.Particle();
  49501. break;
  49502. }
  49503. return returnValue;
  49504. };
  49505. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  49506. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49507. var matrix = [];
  49508. //For now pointDepth will not be used and will be automatically calculated.
  49509. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  49510. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  49511. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  49512. var elementSize = dim * 2 / arraySize;
  49513. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  49514. for (var i = 0; i < pos.length; i = i + 3) {
  49515. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  49516. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  49517. var y = pos[i + 1] + minY;
  49518. if (!matrix[x]) {
  49519. matrix[x] = [];
  49520. }
  49521. if (!matrix[x][z]) {
  49522. matrix[x][z] = y;
  49523. }
  49524. matrix[x][z] = Math.max(y, matrix[x][z]);
  49525. }
  49526. for (var x = 0; x <= arraySize; ++x) {
  49527. if (!matrix[x]) {
  49528. var loc = 1;
  49529. while (!matrix[(x + loc) % arraySize]) {
  49530. loc++;
  49531. }
  49532. matrix[x] = matrix[(x + loc) % arraySize].slice();
  49533. }
  49534. for (var z = 0; z <= arraySize; ++z) {
  49535. if (!matrix[x][z]) {
  49536. var loc = 1;
  49537. var newValue;
  49538. while (newValue === undefined) {
  49539. newValue = matrix[x][(z + loc++) % arraySize];
  49540. }
  49541. matrix[x][z] = newValue;
  49542. }
  49543. }
  49544. }
  49545. var shape = new CANNON.Heightfield(matrix, {
  49546. elementSize: elementSize
  49547. });
  49548. //For future reference, needed for body transformation
  49549. shape.minY = minY;
  49550. return shape;
  49551. };
  49552. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  49553. var object = impostor.object;
  49554. //make sure it is updated...
  49555. object.computeWorldMatrix && object.computeWorldMatrix(true);
  49556. // The delta between the mesh position and the mesh bounding box center
  49557. var center = impostor.getObjectCenter();
  49558. var extendSize = impostor.getObjectExtendSize();
  49559. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  49560. this._tmpPosition.copyFrom(center);
  49561. var quaternion = object.rotationQuaternion;
  49562. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  49563. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  49564. //-90 DEG in X, precalculated
  49565. quaternion = quaternion.multiply(this._minus90X);
  49566. //Invert! (Precalculated, 90 deg in X)
  49567. //No need to clone. this will never change.
  49568. impostor.setDeltaRotation(this._plus90X);
  49569. }
  49570. //If it is a heightfield, if should be centered.
  49571. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  49572. var mesh = object;
  49573. //calculate the correct body position:
  49574. var rotationQuaternion = mesh.rotationQuaternion;
  49575. mesh.rotationQuaternion = this._tmpUnityRotation;
  49576. mesh.computeWorldMatrix(true);
  49577. //get original center with no rotation
  49578. var c = center.clone();
  49579. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  49580. //rotation is back
  49581. mesh.rotationQuaternion = rotationQuaternion;
  49582. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  49583. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  49584. mesh.setPivotMatrix(p);
  49585. mesh.computeWorldMatrix(true);
  49586. //calculate the translation
  49587. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  49588. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  49589. //add it inverted to the delta
  49590. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  49591. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  49592. mesh.setPivotMatrix(oldPivot);
  49593. mesh.computeWorldMatrix(true);
  49594. }
  49595. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  49596. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  49597. this._tmpPosition.copyFrom(object.position);
  49598. }
  49599. impostor.setDeltaPosition(this._tmpDeltaPosition);
  49600. //Now update the impostor object
  49601. impostor.physicsBody.position.copy(this._tmpPosition);
  49602. impostor.physicsBody.quaternion.copy(quaternion);
  49603. };
  49604. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  49605. impostor.object.position.copyFrom(impostor.physicsBody.position);
  49606. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  49607. };
  49608. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  49609. impostor.physicsBody.position.copy(newPosition);
  49610. impostor.physicsBody.quaternion.copy(newRotation);
  49611. };
  49612. CannonJSPlugin.prototype.isSupported = function () {
  49613. return window.CANNON !== undefined;
  49614. };
  49615. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  49616. impostor.physicsBody.velocity.copy(velocity);
  49617. };
  49618. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  49619. impostor.physicsBody.angularVelocity.copy(velocity);
  49620. };
  49621. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  49622. var v = impostor.physicsBody.velocity;
  49623. if (!v)
  49624. return null;
  49625. return new BABYLON.Vector3(v.x, v.y, v.z);
  49626. };
  49627. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  49628. var v = impostor.physicsBody.angularVelocity;
  49629. if (!v)
  49630. return null;
  49631. return new BABYLON.Vector3(v.x, v.y, v.z);
  49632. };
  49633. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  49634. impostor.physicsBody.mass = mass;
  49635. impostor.physicsBody.updateMassProperties();
  49636. };
  49637. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  49638. impostor.physicsBody.sleep();
  49639. };
  49640. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  49641. impostor.physicsBody.wakeUp();
  49642. };
  49643. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  49644. joint.physicsJoint.distance = maxDistance;
  49645. };
  49646. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  49647. if (!motorIndex) {
  49648. joint.physicsJoint.enableMotor();
  49649. }
  49650. };
  49651. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  49652. if (!motorIndex) {
  49653. joint.physicsJoint.disableMotor();
  49654. }
  49655. };
  49656. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  49657. if (!motorIndex) {
  49658. joint.physicsJoint.enableMotor();
  49659. joint.physicsJoint.setMotorSpeed(speed);
  49660. if (maxForce) {
  49661. this.setLimit(joint, maxForce);
  49662. }
  49663. }
  49664. };
  49665. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  49666. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  49667. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  49668. };
  49669. CannonJSPlugin.prototype.dispose = function () {
  49670. //nothing to do, actually.
  49671. };
  49672. return CannonJSPlugin;
  49673. })();
  49674. BABYLON.CannonJSPlugin = CannonJSPlugin;
  49675. })(BABYLON || (BABYLON = {}));
  49676. var BABYLON;
  49677. (function (BABYLON) {
  49678. var OimoJSPlugin = (function () {
  49679. function OimoJSPlugin(iterations) {
  49680. this.name = "OimoJSPlugin";
  49681. this._tmpImpostorsArray = [];
  49682. this._tmpPositionVector = BABYLON.Vector3.Zero();
  49683. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  49684. this.world.clear();
  49685. //making sure no stats are calculated
  49686. this.world.isNoStat = true;
  49687. }
  49688. OimoJSPlugin.prototype.setGravity = function (gravity) {
  49689. this.world.gravity.copy(gravity);
  49690. };
  49691. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  49692. this.world.timeStep = timeStep;
  49693. };
  49694. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  49695. var _this = this;
  49696. impostors.forEach(function (impostor) {
  49697. impostor.beforeStep();
  49698. });
  49699. this.world.step();
  49700. impostors.forEach(function (impostor) {
  49701. impostor.afterStep();
  49702. //update the ordered impostors array
  49703. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  49704. });
  49705. //check for collisions
  49706. var contact = this.world.contacts;
  49707. while (contact !== null) {
  49708. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  49709. contact = contact.next;
  49710. continue;
  49711. }
  49712. //is this body colliding with any other? get the impostor
  49713. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  49714. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  49715. if (!mainImpostor || !collidingImpostor) {
  49716. contact = contact.next;
  49717. continue;
  49718. }
  49719. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  49720. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  49721. contact = contact.next;
  49722. }
  49723. };
  49724. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  49725. var mass = impostor.physicsBody.massInfo.mass;
  49726. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  49727. };
  49728. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  49729. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  49730. this.applyImpulse(impostor, force, contactPoint);
  49731. };
  49732. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  49733. var _this = this;
  49734. //parent-child relationship. Does this impostor has a parent impostor?
  49735. if (impostor.parent) {
  49736. if (impostor.physicsBody) {
  49737. this.removePhysicsBody(impostor);
  49738. //TODO is that needed?
  49739. impostor.forceUpdate();
  49740. }
  49741. return;
  49742. }
  49743. if (impostor.isBodyInitRequired()) {
  49744. var bodyConfig = {
  49745. name: impostor.uniqueId,
  49746. //Oimo must have mass, also for static objects.
  49747. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  49748. size: [],
  49749. type: [],
  49750. pos: [],
  49751. rot: [],
  49752. move: impostor.getParam("mass") !== 0,
  49753. //Supporting older versions of Oimo
  49754. world: this.world
  49755. };
  49756. var impostors = [impostor];
  49757. function addToArray(parent) {
  49758. if (!parent.getChildMeshes)
  49759. return;
  49760. parent.getChildMeshes().forEach(function (m) {
  49761. if (m.physicsImpostor) {
  49762. impostors.push(m.physicsImpostor);
  49763. m.physicsImpostor._init();
  49764. }
  49765. });
  49766. }
  49767. addToArray(impostor.object);
  49768. function checkWithEpsilon(value) {
  49769. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  49770. }
  49771. impostors.forEach(function (i) {
  49772. //get the correct bounding box
  49773. var oldQuaternion = i.object.rotationQuaternion;
  49774. var rot = new OIMO.Euler().setFromQuaternion({
  49775. x: impostor.object.rotationQuaternion.x,
  49776. y: impostor.object.rotationQuaternion.y,
  49777. z: impostor.object.rotationQuaternion.z,
  49778. s: impostor.object.rotationQuaternion.w
  49779. });
  49780. var extendSize = i.getObjectExtendSize();
  49781. if (i === impostor) {
  49782. var center = impostor.getObjectCenter();
  49783. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  49784. //Can also use Array.prototype.push.apply
  49785. bodyConfig.pos.push(center.x);
  49786. bodyConfig.pos.push(center.y);
  49787. bodyConfig.pos.push(center.z);
  49788. //tmp solution
  49789. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  49790. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  49791. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  49792. }
  49793. else {
  49794. bodyConfig.pos.push(i.object.position.x);
  49795. bodyConfig.pos.push(i.object.position.y);
  49796. bodyConfig.pos.push(i.object.position.z);
  49797. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  49798. bodyConfig.rot.push(0);
  49799. bodyConfig.rot.push(0);
  49800. bodyConfig.rot.push(0);
  49801. }
  49802. // register mesh
  49803. switch (i.type) {
  49804. case BABYLON.PhysicsImpostor.ParticleImpostor:
  49805. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  49806. case BABYLON.PhysicsImpostor.SphereImpostor:
  49807. var radiusX = extendSize.x;
  49808. var radiusY = extendSize.y;
  49809. var radiusZ = extendSize.z;
  49810. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  49811. bodyConfig.type.push('sphere');
  49812. //due to the way oimo works with compounds, add 3 times
  49813. bodyConfig.size.push(size);
  49814. bodyConfig.size.push(size);
  49815. bodyConfig.size.push(size);
  49816. break;
  49817. case BABYLON.PhysicsImpostor.CylinderImpostor:
  49818. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  49819. var sizeY = checkWithEpsilon(extendSize.y);
  49820. bodyConfig.type.push('cylinder');
  49821. bodyConfig.size.push(sizeX);
  49822. bodyConfig.size.push(sizeY);
  49823. //due to the way oimo works with compounds, add one more value.
  49824. bodyConfig.size.push(sizeY);
  49825. break;
  49826. case BABYLON.PhysicsImpostor.PlaneImpostor:
  49827. case BABYLON.PhysicsImpostor.BoxImpostor:
  49828. default:
  49829. var sizeX = checkWithEpsilon(extendSize.x);
  49830. var sizeY = checkWithEpsilon(extendSize.y);
  49831. var sizeZ = checkWithEpsilon(extendSize.z);
  49832. bodyConfig.type.push('box');
  49833. bodyConfig.size.push(sizeX);
  49834. bodyConfig.size.push(sizeY);
  49835. bodyConfig.size.push(sizeZ);
  49836. break;
  49837. }
  49838. //actually not needed, but hey...
  49839. i.object.rotationQuaternion = oldQuaternion;
  49840. });
  49841. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  49842. }
  49843. else {
  49844. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  49845. }
  49846. impostor.setDeltaPosition(this._tmpPositionVector);
  49847. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  49848. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  49849. };
  49850. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  49851. //impostor.physicsBody.dispose();
  49852. //Same as : (older oimo versions)
  49853. this.world.removeRigidBody(impostor.physicsBody);
  49854. };
  49855. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  49856. var mainBody = impostorJoint.mainImpostor.physicsBody;
  49857. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  49858. if (!mainBody || !connectedBody) {
  49859. return;
  49860. }
  49861. var jointData = impostorJoint.joint.jointData;
  49862. var options = jointData.nativeParams || {};
  49863. var type;
  49864. var nativeJointData = {
  49865. body1: mainBody,
  49866. body2: connectedBody,
  49867. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  49868. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  49869. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  49870. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  49871. min: options.min,
  49872. max: options.max,
  49873. collision: options.collision || jointData.collision,
  49874. spring: options.spring,
  49875. //supporting older version of Oimo
  49876. world: this.world
  49877. };
  49878. switch (impostorJoint.joint.type) {
  49879. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  49880. type = "jointBall";
  49881. break;
  49882. case BABYLON.PhysicsJoint.SpringJoint:
  49883. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  49884. var springData = jointData;
  49885. nativeJointData.min = springData.length || nativeJointData.min;
  49886. //Max should also be set, just make sure it is at least min
  49887. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  49888. case BABYLON.PhysicsJoint.DistanceJoint:
  49889. type = "jointDistance";
  49890. nativeJointData.max = jointData.maxDistance;
  49891. break;
  49892. case BABYLON.PhysicsJoint.PrismaticJoint:
  49893. type = "jointPrisme";
  49894. break;
  49895. case BABYLON.PhysicsJoint.SliderJoint:
  49896. type = "jointSlide";
  49897. break;
  49898. case BABYLON.PhysicsJoint.WheelJoint:
  49899. type = "jointWheel";
  49900. break;
  49901. case BABYLON.PhysicsJoint.HingeJoint:
  49902. default:
  49903. type = "jointHinge";
  49904. break;
  49905. }
  49906. nativeJointData.type = type;
  49907. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  49908. };
  49909. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  49910. //Bug in Oimo prevents us from disposing a joint in the playground
  49911. //joint.joint.physicsJoint.dispose();
  49912. //So we will bruteforce it!
  49913. try {
  49914. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  49915. }
  49916. catch (e) {
  49917. BABYLON.Tools.Warn(e);
  49918. }
  49919. };
  49920. OimoJSPlugin.prototype.isSupported = function () {
  49921. return OIMO !== undefined;
  49922. };
  49923. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  49924. if (!impostor.physicsBody.sleeping) {
  49925. //TODO check that
  49926. if (impostor.physicsBody.shapes.next) {
  49927. var parentShape = this._getLastShape(impostor.physicsBody);
  49928. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  49929. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  49930. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  49931. }
  49932. else {
  49933. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  49934. }
  49935. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  49936. impostor.object.rotationQuaternion.normalize();
  49937. }
  49938. };
  49939. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  49940. var body = impostor.physicsBody;
  49941. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  49942. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  49943. body.syncShapes();
  49944. body.awake();
  49945. };
  49946. OimoJSPlugin.prototype._getLastShape = function (body) {
  49947. var lastShape = body.shapes;
  49948. while (lastShape.next) {
  49949. lastShape = lastShape.next;
  49950. }
  49951. return lastShape;
  49952. };
  49953. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  49954. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  49955. };
  49956. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  49957. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  49958. };
  49959. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  49960. var v = impostor.physicsBody.linearVelocity;
  49961. if (!v)
  49962. return null;
  49963. return new BABYLON.Vector3(v.x, v.y, v.z);
  49964. };
  49965. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  49966. var v = impostor.physicsBody.angularVelocity;
  49967. if (!v)
  49968. return null;
  49969. return new BABYLON.Vector3(v.x, v.y, v.z);
  49970. };
  49971. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  49972. var staticBody = mass === 0;
  49973. //this will actually set the body's density and not its mass.
  49974. //But this is how oimo treats the mass variable.
  49975. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  49976. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  49977. };
  49978. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  49979. impostor.physicsBody.sleep();
  49980. };
  49981. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  49982. impostor.physicsBody.awake();
  49983. };
  49984. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  49985. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  49986. if (minDistance !== void 0) {
  49987. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  49988. }
  49989. };
  49990. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  49991. //TODO separate rotational and transational motors.
  49992. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  49993. if (motor) {
  49994. motor.setMotor(speed, maxForce);
  49995. }
  49996. };
  49997. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  49998. //TODO separate rotational and transational motors.
  49999. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  50000. if (motor) {
  50001. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  50002. }
  50003. };
  50004. OimoJSPlugin.prototype.dispose = function () {
  50005. this.world.clear();
  50006. };
  50007. return OimoJSPlugin;
  50008. })();
  50009. BABYLON.OimoJSPlugin = OimoJSPlugin;
  50010. })(BABYLON || (BABYLON = {}));
  50011. var BABYLON;
  50012. (function (BABYLON) {
  50013. var DisplayPassPostProcess = (function (_super) {
  50014. __extends(DisplayPassPostProcess, _super);
  50015. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  50016. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  50017. }
  50018. return DisplayPassPostProcess;
  50019. })(BABYLON.PostProcess);
  50020. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  50021. })(BABYLON || (BABYLON = {}));
  50022. var BABYLON;
  50023. (function (BABYLON) {
  50024. var SimplificationSettings = (function () {
  50025. function SimplificationSettings(quality, distance, optimizeMesh) {
  50026. this.quality = quality;
  50027. this.distance = distance;
  50028. this.optimizeMesh = optimizeMesh;
  50029. }
  50030. return SimplificationSettings;
  50031. })();
  50032. BABYLON.SimplificationSettings = SimplificationSettings;
  50033. var SimplificationQueue = (function () {
  50034. function SimplificationQueue() {
  50035. this.running = false;
  50036. this._simplificationArray = [];
  50037. }
  50038. SimplificationQueue.prototype.addTask = function (task) {
  50039. this._simplificationArray.push(task);
  50040. };
  50041. SimplificationQueue.prototype.executeNext = function () {
  50042. var task = this._simplificationArray.pop();
  50043. if (task) {
  50044. this.running = true;
  50045. this.runSimplification(task);
  50046. }
  50047. else {
  50048. this.running = false;
  50049. }
  50050. };
  50051. SimplificationQueue.prototype.runSimplification = function (task) {
  50052. var _this = this;
  50053. if (task.parallelProcessing) {
  50054. //parallel simplifier
  50055. task.settings.forEach(function (setting) {
  50056. var simplifier = _this.getSimplifier(task);
  50057. simplifier.simplify(setting, function (newMesh) {
  50058. task.mesh.addLODLevel(setting.distance, newMesh);
  50059. newMesh.isVisible = true;
  50060. //check if it is the last
  50061. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  50062. //all done, run the success callback.
  50063. task.successCallback();
  50064. }
  50065. _this.executeNext();
  50066. });
  50067. });
  50068. }
  50069. else {
  50070. //single simplifier.
  50071. var simplifier = this.getSimplifier(task);
  50072. var runDecimation = function (setting, callback) {
  50073. simplifier.simplify(setting, function (newMesh) {
  50074. task.mesh.addLODLevel(setting.distance, newMesh);
  50075. newMesh.isVisible = true;
  50076. //run the next quality level
  50077. callback();
  50078. });
  50079. };
  50080. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  50081. runDecimation(task.settings[loop.index], function () {
  50082. loop.executeNext();
  50083. });
  50084. }, function () {
  50085. //execution ended, run the success callback.
  50086. if (task.successCallback) {
  50087. task.successCallback();
  50088. }
  50089. _this.executeNext();
  50090. });
  50091. }
  50092. };
  50093. SimplificationQueue.prototype.getSimplifier = function (task) {
  50094. switch (task.simplificationType) {
  50095. case SimplificationType.QUADRATIC:
  50096. default:
  50097. return new QuadraticErrorSimplification(task.mesh);
  50098. }
  50099. };
  50100. return SimplificationQueue;
  50101. })();
  50102. BABYLON.SimplificationQueue = SimplificationQueue;
  50103. /**
  50104. * The implemented types of simplification.
  50105. * At the moment only Quadratic Error Decimation is implemented.
  50106. */
  50107. (function (SimplificationType) {
  50108. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  50109. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  50110. var SimplificationType = BABYLON.SimplificationType;
  50111. var DecimationTriangle = (function () {
  50112. function DecimationTriangle(vertices) {
  50113. this.vertices = vertices;
  50114. this.error = new Array(4);
  50115. this.deleted = false;
  50116. this.isDirty = false;
  50117. this.deletePending = false;
  50118. this.borderFactor = 0;
  50119. }
  50120. return DecimationTriangle;
  50121. })();
  50122. BABYLON.DecimationTriangle = DecimationTriangle;
  50123. var DecimationVertex = (function () {
  50124. function DecimationVertex(position, id) {
  50125. this.position = position;
  50126. this.id = id;
  50127. this.isBorder = true;
  50128. this.q = new QuadraticMatrix();
  50129. this.triangleCount = 0;
  50130. this.triangleStart = 0;
  50131. this.originalOffsets = [];
  50132. }
  50133. DecimationVertex.prototype.updatePosition = function (newPosition) {
  50134. this.position.copyFrom(newPosition);
  50135. };
  50136. return DecimationVertex;
  50137. })();
  50138. BABYLON.DecimationVertex = DecimationVertex;
  50139. var QuadraticMatrix = (function () {
  50140. function QuadraticMatrix(data) {
  50141. this.data = new Array(10);
  50142. for (var i = 0; i < 10; ++i) {
  50143. if (data && data[i]) {
  50144. this.data[i] = data[i];
  50145. }
  50146. else {
  50147. this.data[i] = 0;
  50148. }
  50149. }
  50150. }
  50151. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  50152. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  50153. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  50154. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  50155. return det;
  50156. };
  50157. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  50158. for (var i = 0; i < 10; ++i) {
  50159. this.data[i] += matrix.data[i];
  50160. }
  50161. };
  50162. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  50163. for (var i = 0; i < 10; ++i) {
  50164. this.data[i] += data[i];
  50165. }
  50166. };
  50167. QuadraticMatrix.prototype.add = function (matrix) {
  50168. var m = new QuadraticMatrix();
  50169. for (var i = 0; i < 10; ++i) {
  50170. m.data[i] = this.data[i] + matrix.data[i];
  50171. }
  50172. return m;
  50173. };
  50174. QuadraticMatrix.FromData = function (a, b, c, d) {
  50175. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  50176. };
  50177. //returning an array to avoid garbage collection
  50178. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  50179. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  50180. };
  50181. return QuadraticMatrix;
  50182. })();
  50183. BABYLON.QuadraticMatrix = QuadraticMatrix;
  50184. var Reference = (function () {
  50185. function Reference(vertexId, triangleId) {
  50186. this.vertexId = vertexId;
  50187. this.triangleId = triangleId;
  50188. }
  50189. return Reference;
  50190. })();
  50191. BABYLON.Reference = Reference;
  50192. /**
  50193. * An implementation of the Quadratic Error simplification algorithm.
  50194. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  50195. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  50196. * @author RaananW
  50197. */
  50198. var QuadraticErrorSimplification = (function () {
  50199. function QuadraticErrorSimplification(_mesh) {
  50200. this._mesh = _mesh;
  50201. this.initialized = false;
  50202. this.syncIterations = 5000;
  50203. this.aggressiveness = 7;
  50204. this.decimationIterations = 100;
  50205. this.boundingBoxEpsilon = BABYLON.Epsilon;
  50206. }
  50207. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  50208. var _this = this;
  50209. this.initDecimatedMesh();
  50210. //iterating through the submeshes array, one after the other.
  50211. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  50212. _this.initWithMesh(loop.index, function () {
  50213. _this.runDecimation(settings, loop.index, function () {
  50214. loop.executeNext();
  50215. });
  50216. }, settings.optimizeMesh);
  50217. }, function () {
  50218. setTimeout(function () {
  50219. successCallback(_this._reconstructedMesh);
  50220. }, 0);
  50221. });
  50222. };
  50223. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  50224. var _this = this;
  50225. var gCount = 0;
  50226. triangle.vertices.forEach(function (vertex) {
  50227. var count = 0;
  50228. var vPos = vertex.position;
  50229. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  50230. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  50231. ++count;
  50232. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  50233. ++count;
  50234. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  50235. ++count;
  50236. if (count > 1) {
  50237. ++gCount;
  50238. }
  50239. ;
  50240. });
  50241. if (gCount > 1) {
  50242. console.log(triangle, gCount);
  50243. }
  50244. return gCount > 1;
  50245. };
  50246. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  50247. var _this = this;
  50248. var targetCount = ~~(this.triangles.length * settings.quality);
  50249. var deletedTriangles = 0;
  50250. var triangleCount = this.triangles.length;
  50251. var iterationFunction = function (iteration, callback) {
  50252. setTimeout(function () {
  50253. if (iteration % 5 === 0) {
  50254. _this.updateMesh(iteration === 0);
  50255. }
  50256. for (var i = 0; i < _this.triangles.length; ++i) {
  50257. _this.triangles[i].isDirty = false;
  50258. }
  50259. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  50260. var trianglesIterator = function (i) {
  50261. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  50262. var t = _this.triangles[tIdx];
  50263. if (!t)
  50264. return;
  50265. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  50266. return;
  50267. }
  50268. for (var j = 0; j < 3; ++j) {
  50269. if (t.error[j] < threshold) {
  50270. var deleted0 = [];
  50271. var deleted1 = [];
  50272. var v0 = t.vertices[j];
  50273. var v1 = t.vertices[(j + 1) % 3];
  50274. if (v0.isBorder || v1.isBorder)
  50275. continue;
  50276. var p = BABYLON.Vector3.Zero();
  50277. var n = BABYLON.Vector3.Zero();
  50278. var uv = BABYLON.Vector2.Zero();
  50279. var color = new BABYLON.Color4(0, 0, 0, 1);
  50280. _this.calculateError(v0, v1, p, n, uv, color);
  50281. var delTr = [];
  50282. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  50283. continue;
  50284. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  50285. continue;
  50286. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  50287. continue;
  50288. var uniqueArray = [];
  50289. delTr.forEach(function (deletedT) {
  50290. if (uniqueArray.indexOf(deletedT) === -1) {
  50291. deletedT.deletePending = true;
  50292. uniqueArray.push(deletedT);
  50293. }
  50294. });
  50295. if (uniqueArray.length % 2 !== 0) {
  50296. continue;
  50297. }
  50298. v0.q = v1.q.add(v0.q);
  50299. v0.updatePosition(p);
  50300. var tStart = _this.references.length;
  50301. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  50302. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  50303. var tCount = _this.references.length - tStart;
  50304. if (tCount <= v0.triangleCount) {
  50305. if (tCount) {
  50306. for (var c = 0; c < tCount; c++) {
  50307. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  50308. }
  50309. }
  50310. }
  50311. else {
  50312. v0.triangleStart = tStart;
  50313. }
  50314. v0.triangleCount = tCount;
  50315. break;
  50316. }
  50317. }
  50318. };
  50319. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  50320. }, 0);
  50321. };
  50322. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  50323. if (triangleCount - deletedTriangles <= targetCount)
  50324. loop.breakLoop();
  50325. else {
  50326. iterationFunction(loop.index, function () {
  50327. loop.executeNext();
  50328. });
  50329. }
  50330. }, function () {
  50331. setTimeout(function () {
  50332. //reconstruct this part of the mesh
  50333. _this.reconstructMesh(submeshIndex);
  50334. successCallback();
  50335. }, 0);
  50336. });
  50337. };
  50338. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  50339. var _this = this;
  50340. this.vertices = [];
  50341. this.triangles = [];
  50342. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50343. var indices = this._mesh.getIndices();
  50344. var submesh = this._mesh.subMeshes[submeshIndex];
  50345. var findInVertices = function (positionToSearch) {
  50346. if (optimizeMesh) {
  50347. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  50348. if (_this.vertices[ii].position.equals(positionToSearch)) {
  50349. return _this.vertices[ii];
  50350. }
  50351. }
  50352. }
  50353. return null;
  50354. };
  50355. var vertexReferences = [];
  50356. var vertexInit = function (i) {
  50357. var offset = i + submesh.verticesStart;
  50358. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  50359. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  50360. vertex.originalOffsets.push(offset);
  50361. if (vertex.id === _this.vertices.length) {
  50362. _this.vertices.push(vertex);
  50363. }
  50364. vertexReferences.push(vertex.id);
  50365. };
  50366. //var totalVertices = mesh.getTotalVertices();
  50367. var totalVertices = submesh.verticesCount;
  50368. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  50369. var indicesInit = function (i) {
  50370. var offset = (submesh.indexStart / 3) + i;
  50371. var pos = (offset * 3);
  50372. var i0 = indices[pos + 0];
  50373. var i1 = indices[pos + 1];
  50374. var i2 = indices[pos + 2];
  50375. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  50376. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  50377. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  50378. var triangle = new DecimationTriangle([v0, v1, v2]);
  50379. triangle.originalOffset = pos;
  50380. _this.triangles.push(triangle);
  50381. };
  50382. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  50383. _this.init(callback);
  50384. });
  50385. });
  50386. };
  50387. QuadraticErrorSimplification.prototype.init = function (callback) {
  50388. var _this = this;
  50389. var triangleInit1 = function (i) {
  50390. var t = _this.triangles[i];
  50391. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  50392. for (var j = 0; j < 3; j++) {
  50393. 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))));
  50394. }
  50395. };
  50396. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  50397. var triangleInit2 = function (i) {
  50398. var t = _this.triangles[i];
  50399. for (var j = 0; j < 3; ++j) {
  50400. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  50401. }
  50402. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  50403. };
  50404. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  50405. _this.initialized = true;
  50406. callback();
  50407. });
  50408. });
  50409. };
  50410. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  50411. var newTriangles = [];
  50412. var i;
  50413. for (i = 0; i < this.vertices.length; ++i) {
  50414. this.vertices[i].triangleCount = 0;
  50415. }
  50416. var t;
  50417. var j;
  50418. for (i = 0; i < this.triangles.length; ++i) {
  50419. if (!this.triangles[i].deleted) {
  50420. t = this.triangles[i];
  50421. for (j = 0; j < 3; ++j) {
  50422. t.vertices[j].triangleCount = 1;
  50423. }
  50424. newTriangles.push(t);
  50425. }
  50426. }
  50427. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  50428. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  50429. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  50430. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  50431. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50432. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50433. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50434. var vertexCount = 0;
  50435. for (i = 0; i < this.vertices.length; ++i) {
  50436. var vertex = this.vertices[i];
  50437. vertex.id = vertexCount;
  50438. if (vertex.triangleCount) {
  50439. vertex.originalOffsets.forEach(function (originalOffset) {
  50440. newPositionData.push(vertex.position.x);
  50441. newPositionData.push(vertex.position.y);
  50442. newPositionData.push(vertex.position.z);
  50443. newNormalData.push(normalData[originalOffset * 3]);
  50444. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  50445. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  50446. if (uvs && uvs.length) {
  50447. newUVsData.push(uvs[(originalOffset * 2)]);
  50448. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  50449. }
  50450. else if (colorsData && colorsData.length) {
  50451. newColorsData.push(colorsData[(originalOffset * 4)]);
  50452. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  50453. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  50454. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  50455. }
  50456. ++vertexCount;
  50457. });
  50458. }
  50459. }
  50460. var startingIndex = this._reconstructedMesh.getTotalIndices();
  50461. var startingVertex = this._reconstructedMesh.getTotalVertices();
  50462. var submeshesArray = this._reconstructedMesh.subMeshes;
  50463. this._reconstructedMesh.subMeshes = [];
  50464. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  50465. var originalIndices = this._mesh.getIndices();
  50466. for (i = 0; i < newTriangles.length; ++i) {
  50467. t = newTriangles[i]; //now get the new referencing point for each vertex
  50468. [0, 1, 2].forEach(function (idx) {
  50469. var id = originalIndices[t.originalOffset + idx];
  50470. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  50471. if (offset < 0)
  50472. offset = 0;
  50473. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  50474. });
  50475. }
  50476. //overwriting the old vertex buffers and indices.
  50477. this._reconstructedMesh.setIndices(newIndicesArray);
  50478. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  50479. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  50480. if (newUVsData.length > 0)
  50481. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  50482. if (newColorsData.length > 0)
  50483. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  50484. //create submesh
  50485. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  50486. if (submeshIndex > 0) {
  50487. this._reconstructedMesh.subMeshes = [];
  50488. submeshesArray.forEach(function (submesh) {
  50489. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  50490. });
  50491. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  50492. }
  50493. };
  50494. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  50495. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  50496. this._reconstructedMesh.material = this._mesh.material;
  50497. this._reconstructedMesh.parent = this._mesh.parent;
  50498. this._reconstructedMesh.isVisible = false;
  50499. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  50500. };
  50501. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  50502. for (var i = 0; i < vertex1.triangleCount; ++i) {
  50503. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  50504. if (t.deleted)
  50505. continue;
  50506. var s = this.references[vertex1.triangleStart + i].vertexId;
  50507. var v1 = t.vertices[(s + 1) % 3];
  50508. var v2 = t.vertices[(s + 2) % 3];
  50509. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  50510. deletedArray[i] = true;
  50511. delTr.push(t);
  50512. continue;
  50513. }
  50514. var d1 = v1.position.subtract(point);
  50515. d1 = d1.normalize();
  50516. var d2 = v2.position.subtract(point);
  50517. d2 = d2.normalize();
  50518. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  50519. return true;
  50520. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  50521. deletedArray[i] = false;
  50522. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  50523. return true;
  50524. }
  50525. return false;
  50526. };
  50527. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  50528. var newDeleted = deletedTriangles;
  50529. for (var i = 0; i < vertex.triangleCount; ++i) {
  50530. var ref = this.references[vertex.triangleStart + i];
  50531. var t = this.triangles[ref.triangleId];
  50532. if (t.deleted)
  50533. continue;
  50534. if (deletedArray[i] && t.deletePending) {
  50535. t.deleted = true;
  50536. newDeleted++;
  50537. continue;
  50538. }
  50539. t.vertices[ref.vertexId] = origVertex;
  50540. t.isDirty = true;
  50541. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  50542. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  50543. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  50544. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  50545. this.references.push(ref);
  50546. }
  50547. return newDeleted;
  50548. };
  50549. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  50550. for (var i = 0; i < this.vertices.length; ++i) {
  50551. var vCount = [];
  50552. var vId = [];
  50553. var v = this.vertices[i];
  50554. var j;
  50555. for (j = 0; j < v.triangleCount; ++j) {
  50556. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  50557. for (var ii = 0; ii < 3; ii++) {
  50558. var ofs = 0;
  50559. var vv = triangle.vertices[ii];
  50560. while (ofs < vCount.length) {
  50561. if (vId[ofs] === vv.id)
  50562. break;
  50563. ++ofs;
  50564. }
  50565. if (ofs === vCount.length) {
  50566. vCount.push(1);
  50567. vId.push(vv.id);
  50568. }
  50569. else {
  50570. vCount[ofs]++;
  50571. }
  50572. }
  50573. }
  50574. for (j = 0; j < vCount.length; ++j) {
  50575. if (vCount[j] === 1) {
  50576. this.vertices[vId[j]].isBorder = true;
  50577. }
  50578. else {
  50579. this.vertices[vId[j]].isBorder = false;
  50580. }
  50581. }
  50582. }
  50583. };
  50584. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  50585. if (identifyBorders === void 0) { identifyBorders = false; }
  50586. var i;
  50587. if (!identifyBorders) {
  50588. var newTrianglesVector = [];
  50589. for (i = 0; i < this.triangles.length; ++i) {
  50590. if (!this.triangles[i].deleted) {
  50591. newTrianglesVector.push(this.triangles[i]);
  50592. }
  50593. }
  50594. this.triangles = newTrianglesVector;
  50595. }
  50596. for (i = 0; i < this.vertices.length; ++i) {
  50597. this.vertices[i].triangleCount = 0;
  50598. this.vertices[i].triangleStart = 0;
  50599. }
  50600. var t;
  50601. var j;
  50602. var v;
  50603. for (i = 0; i < this.triangles.length; ++i) {
  50604. t = this.triangles[i];
  50605. for (j = 0; j < 3; ++j) {
  50606. v = t.vertices[j];
  50607. v.triangleCount++;
  50608. }
  50609. }
  50610. var tStart = 0;
  50611. for (i = 0; i < this.vertices.length; ++i) {
  50612. this.vertices[i].triangleStart = tStart;
  50613. tStart += this.vertices[i].triangleCount;
  50614. this.vertices[i].triangleCount = 0;
  50615. }
  50616. var newReferences = new Array(this.triangles.length * 3);
  50617. for (i = 0; i < this.triangles.length; ++i) {
  50618. t = this.triangles[i];
  50619. for (j = 0; j < 3; ++j) {
  50620. v = t.vertices[j];
  50621. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  50622. v.triangleCount++;
  50623. }
  50624. }
  50625. this.references = newReferences;
  50626. if (identifyBorders) {
  50627. this.identifyBorder();
  50628. }
  50629. };
  50630. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  50631. var x = point.x;
  50632. var y = point.y;
  50633. var z = point.z;
  50634. 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
  50635. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  50636. };
  50637. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  50638. var q = vertex1.q.add(vertex2.q);
  50639. var border = vertex1.isBorder && vertex2.isBorder;
  50640. var error = 0;
  50641. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  50642. if (qDet !== 0 && !border) {
  50643. if (!pointResult) {
  50644. pointResult = BABYLON.Vector3.Zero();
  50645. }
  50646. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  50647. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  50648. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  50649. error = this.vertexError(q, pointResult);
  50650. }
  50651. else {
  50652. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  50653. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  50654. var error1 = this.vertexError(q, vertex1.position);
  50655. var error2 = this.vertexError(q, vertex2.position);
  50656. var error3 = this.vertexError(q, p3);
  50657. error = Math.min(error1, error2, error3);
  50658. if (error === error1) {
  50659. if (pointResult) {
  50660. pointResult.copyFrom(vertex1.position);
  50661. }
  50662. }
  50663. else if (error === error2) {
  50664. if (pointResult) {
  50665. pointResult.copyFrom(vertex2.position);
  50666. }
  50667. }
  50668. else {
  50669. if (pointResult) {
  50670. pointResult.copyFrom(p3);
  50671. }
  50672. }
  50673. }
  50674. return error;
  50675. };
  50676. return QuadraticErrorSimplification;
  50677. })();
  50678. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  50679. })(BABYLON || (BABYLON = {}));
  50680. var BABYLON;
  50681. (function (BABYLON) {
  50682. var serializedGeometries = [];
  50683. var serializeGeometry = function (geometry, serializationGeometries) {
  50684. if (serializedGeometries[geometry.id]) {
  50685. return;
  50686. }
  50687. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  50688. serializationGeometries.boxes.push(geometry.serialize());
  50689. }
  50690. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  50691. serializationGeometries.spheres.push(geometry.serialize());
  50692. }
  50693. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  50694. serializationGeometries.cylinders.push(geometry.serialize());
  50695. }
  50696. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  50697. serializationGeometries.toruses.push(geometry.serialize());
  50698. }
  50699. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  50700. serializationGeometries.grounds.push(geometry.serialize());
  50701. }
  50702. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  50703. serializationGeometries.planes.push(geometry.serialize());
  50704. }
  50705. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  50706. serializationGeometries.torusKnots.push(geometry.serialize());
  50707. }
  50708. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  50709. throw new Error("Unknown primitive type");
  50710. }
  50711. else {
  50712. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  50713. }
  50714. serializedGeometries[geometry.id] = true;
  50715. };
  50716. var serializeMesh = function (mesh, serializationScene) {
  50717. var serializationObject = {};
  50718. serializationObject.name = mesh.name;
  50719. serializationObject.id = mesh.id;
  50720. if (BABYLON.Tags.HasTags(mesh)) {
  50721. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  50722. }
  50723. serializationObject.position = mesh.position.asArray();
  50724. if (mesh.rotationQuaternion) {
  50725. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  50726. }
  50727. else if (mesh.rotation) {
  50728. serializationObject.rotation = mesh.rotation.asArray();
  50729. }
  50730. serializationObject.scaling = mesh.scaling.asArray();
  50731. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  50732. serializationObject.isEnabled = mesh.isEnabled();
  50733. serializationObject.isVisible = mesh.isVisible;
  50734. serializationObject.infiniteDistance = mesh.infiniteDistance;
  50735. serializationObject.pickable = mesh.isPickable;
  50736. serializationObject.receiveShadows = mesh.receiveShadows;
  50737. serializationObject.billboardMode = mesh.billboardMode;
  50738. serializationObject.visibility = mesh.visibility;
  50739. serializationObject.checkCollisions = mesh.checkCollisions;
  50740. // Parent
  50741. if (mesh.parent) {
  50742. serializationObject.parentId = mesh.parent.id;
  50743. }
  50744. // Geometry
  50745. var geometry = mesh._geometry;
  50746. if (geometry) {
  50747. var geometryId = geometry.id;
  50748. serializationObject.geometryId = geometryId;
  50749. if (!mesh.getScene().getGeometryByID(geometryId)) {
  50750. // 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
  50751. serializeGeometry(geometry, serializationScene.geometries);
  50752. }
  50753. // SubMeshes
  50754. serializationObject.subMeshes = [];
  50755. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  50756. var subMesh = mesh.subMeshes[subIndex];
  50757. serializationObject.subMeshes.push({
  50758. materialIndex: subMesh.materialIndex,
  50759. verticesStart: subMesh.verticesStart,
  50760. verticesCount: subMesh.verticesCount,
  50761. indexStart: subMesh.indexStart,
  50762. indexCount: subMesh.indexCount
  50763. });
  50764. }
  50765. }
  50766. // Material
  50767. if (mesh.material) {
  50768. serializationObject.materialId = mesh.material.id;
  50769. }
  50770. else {
  50771. mesh.material = null;
  50772. }
  50773. // Skeleton
  50774. if (mesh.skeleton) {
  50775. serializationObject.skeletonId = mesh.skeleton.id;
  50776. }
  50777. // Physics
  50778. //TODO implement correct serialization for physics impostors.
  50779. if (mesh.getPhysicsImpostor()) {
  50780. serializationObject.physicsMass = mesh.getPhysicsMass();
  50781. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  50782. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  50783. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  50784. }
  50785. // Instances
  50786. serializationObject.instances = [];
  50787. for (var index = 0; index < mesh.instances.length; index++) {
  50788. var instance = mesh.instances[index];
  50789. var serializationInstance = {
  50790. name: instance.name,
  50791. position: instance.position.asArray(),
  50792. scaling: instance.scaling.asArray()
  50793. };
  50794. if (instance.rotationQuaternion) {
  50795. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  50796. }
  50797. else if (instance.rotation) {
  50798. serializationInstance.rotation = instance.rotation.asArray();
  50799. }
  50800. serializationObject.instances.push(serializationInstance);
  50801. // Animations
  50802. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  50803. serializationInstance.ranges = instance.serializeAnimationRanges();
  50804. }
  50805. // Animations
  50806. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  50807. serializationObject.ranges = mesh.serializeAnimationRanges();
  50808. // Layer mask
  50809. serializationObject.layerMask = mesh.layerMask;
  50810. // Action Manager
  50811. if (mesh.actionManager) {
  50812. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  50813. }
  50814. return serializationObject;
  50815. };
  50816. var finalizeSingleMesh = function (mesh, serializationObject) {
  50817. //only works if the mesh is already loaded
  50818. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  50819. //serialize material
  50820. if (mesh.material) {
  50821. if (mesh.material instanceof BABYLON.StandardMaterial) {
  50822. serializationObject.materials = serializationObject.materials || [];
  50823. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  50824. serializationObject.materials.push(mesh.material.serialize());
  50825. }
  50826. }
  50827. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  50828. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  50829. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  50830. serializationObject.multiMaterials.push(mesh.material.serialize());
  50831. }
  50832. }
  50833. }
  50834. //serialize geometry
  50835. var geometry = mesh._geometry;
  50836. if (geometry) {
  50837. if (!serializationObject.geometries) {
  50838. serializationObject.geometries = {};
  50839. serializationObject.geometries.boxes = [];
  50840. serializationObject.geometries.spheres = [];
  50841. serializationObject.geometries.cylinders = [];
  50842. serializationObject.geometries.toruses = [];
  50843. serializationObject.geometries.grounds = [];
  50844. serializationObject.geometries.planes = [];
  50845. serializationObject.geometries.torusKnots = [];
  50846. serializationObject.geometries.vertexData = [];
  50847. }
  50848. serializeGeometry(geometry, serializationObject.geometries);
  50849. }
  50850. // Skeletons
  50851. if (mesh.skeleton) {
  50852. serializationObject.skeletons = serializationObject.skeletons || [];
  50853. serializationObject.skeletons.push(mesh.skeleton.serialize());
  50854. }
  50855. //serialize the actual mesh
  50856. serializationObject.meshes = serializationObject.meshes || [];
  50857. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  50858. }
  50859. };
  50860. var SceneSerializer = (function () {
  50861. function SceneSerializer() {
  50862. }
  50863. SceneSerializer.ClearCache = function () {
  50864. serializedGeometries = [];
  50865. };
  50866. SceneSerializer.Serialize = function (scene) {
  50867. var serializationObject = {};
  50868. // Scene
  50869. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  50870. serializationObject.autoClear = scene.autoClear;
  50871. serializationObject.clearColor = scene.clearColor.asArray();
  50872. serializationObject.ambientColor = scene.ambientColor.asArray();
  50873. serializationObject.gravity = scene.gravity.asArray();
  50874. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  50875. serializationObject.workerCollisions = scene.workerCollisions;
  50876. // Fog
  50877. if (scene.fogMode && scene.fogMode !== 0) {
  50878. serializationObject.fogMode = scene.fogMode;
  50879. serializationObject.fogColor = scene.fogColor.asArray();
  50880. serializationObject.fogStart = scene.fogStart;
  50881. serializationObject.fogEnd = scene.fogEnd;
  50882. serializationObject.fogDensity = scene.fogDensity;
  50883. }
  50884. //Physics
  50885. if (scene.isPhysicsEnabled()) {
  50886. serializationObject.physicsEnabled = true;
  50887. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  50888. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  50889. }
  50890. // Lights
  50891. serializationObject.lights = [];
  50892. var index;
  50893. var light;
  50894. for (index = 0; index < scene.lights.length; index++) {
  50895. light = scene.lights[index];
  50896. serializationObject.lights.push(light.serialize());
  50897. }
  50898. // Cameras
  50899. serializationObject.cameras = [];
  50900. for (index = 0; index < scene.cameras.length; index++) {
  50901. var camera = scene.cameras[index];
  50902. serializationObject.cameras.push(camera.serialize());
  50903. }
  50904. if (scene.activeCamera) {
  50905. serializationObject.activeCameraID = scene.activeCamera.id;
  50906. }
  50907. // Animations
  50908. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  50909. // Materials
  50910. serializationObject.materials = [];
  50911. serializationObject.multiMaterials = [];
  50912. var material;
  50913. for (index = 0; index < scene.materials.length; index++) {
  50914. material = scene.materials[index];
  50915. serializationObject.materials.push(material.serialize());
  50916. }
  50917. // MultiMaterials
  50918. serializationObject.multiMaterials = [];
  50919. for (index = 0; index < scene.multiMaterials.length; index++) {
  50920. var multiMaterial = scene.multiMaterials[index];
  50921. serializationObject.multiMaterials.push(multiMaterial.serialize());
  50922. }
  50923. // Skeletons
  50924. serializationObject.skeletons = [];
  50925. for (index = 0; index < scene.skeletons.length; index++) {
  50926. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  50927. }
  50928. // Geometries
  50929. serializationObject.geometries = {};
  50930. serializationObject.geometries.boxes = [];
  50931. serializationObject.geometries.spheres = [];
  50932. serializationObject.geometries.cylinders = [];
  50933. serializationObject.geometries.toruses = [];
  50934. serializationObject.geometries.grounds = [];
  50935. serializationObject.geometries.planes = [];
  50936. serializationObject.geometries.torusKnots = [];
  50937. serializationObject.geometries.vertexData = [];
  50938. serializedGeometries = [];
  50939. var geometries = scene.getGeometries();
  50940. for (index = 0; index < geometries.length; index++) {
  50941. var geometry = geometries[index];
  50942. if (geometry.isReady()) {
  50943. serializeGeometry(geometry, serializationObject.geometries);
  50944. }
  50945. }
  50946. // Meshes
  50947. serializationObject.meshes = [];
  50948. for (index = 0; index < scene.meshes.length; index++) {
  50949. var abstractMesh = scene.meshes[index];
  50950. if (abstractMesh instanceof BABYLON.Mesh) {
  50951. var mesh = abstractMesh;
  50952. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  50953. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  50954. }
  50955. }
  50956. }
  50957. // Particles Systems
  50958. serializationObject.particleSystems = [];
  50959. for (index = 0; index < scene.particleSystems.length; index++) {
  50960. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  50961. }
  50962. // Lens flares
  50963. serializationObject.lensFlareSystems = [];
  50964. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  50965. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  50966. }
  50967. // Shadows
  50968. serializationObject.shadowGenerators = [];
  50969. for (index = 0; index < scene.lights.length; index++) {
  50970. light = scene.lights[index];
  50971. var shadowGenerator = light.getShadowGenerator();
  50972. // Only support serialization for official generator so far.
  50973. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  50974. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  50975. }
  50976. }
  50977. // Action Manager
  50978. if (scene.actionManager) {
  50979. serializationObject.actions = scene.actionManager.serialize("scene");
  50980. }
  50981. // Audio
  50982. serializationObject.sounds = [];
  50983. for (index = 0; index < scene.soundTracks.length; index++) {
  50984. var soundtrack = scene.soundTracks[index];
  50985. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  50986. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  50987. }
  50988. }
  50989. return serializationObject;
  50990. };
  50991. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  50992. if (withParents === void 0) { withParents = false; }
  50993. if (withChildren === void 0) { withChildren = false; }
  50994. var serializationObject = {};
  50995. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  50996. if (withParents || withChildren) {
  50997. //deliberate for loop! not for each, appended should be processed as well.
  50998. for (var i = 0; i < toSerialize.length; ++i) {
  50999. if (withChildren) {
  51000. toSerialize[i].getDescendants().forEach(function (node) {
  51001. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  51002. toSerialize.push(node);
  51003. }
  51004. });
  51005. }
  51006. //make sure the array doesn't contain the object already
  51007. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  51008. toSerialize.push(toSerialize[i].parent);
  51009. }
  51010. }
  51011. }
  51012. toSerialize.forEach(function (mesh) {
  51013. finalizeSingleMesh(mesh, serializationObject);
  51014. });
  51015. return serializationObject;
  51016. };
  51017. return SceneSerializer;
  51018. })();
  51019. BABYLON.SceneSerializer = SceneSerializer;
  51020. })(BABYLON || (BABYLON = {}));
  51021. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  51022. // Huge respect for a such great lib.
  51023. // Earcut license:
  51024. // Copyright (c) 2016, Mapbox
  51025. //
  51026. // Permission to use, copy, modify, and/or distribute this software for any purpose
  51027. // with or without fee is hereby granted, provided that the above copyright notice
  51028. // and this permission notice appear in all copies.
  51029. //
  51030. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  51031. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  51032. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  51033. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  51034. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  51035. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  51036. // THIS SOFTWARE.
  51037. var Earcut;
  51038. (function (Earcut) {
  51039. /**
  51040. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  51041. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  51042. * @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).
  51043. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  51044. */
  51045. function earcut(data, holeIndices, dim) {
  51046. dim = dim || 2;
  51047. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  51048. if (!outerNode)
  51049. return triangles;
  51050. var minX, minY, maxX, maxY, x, y, size;
  51051. if (hasHoles)
  51052. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  51053. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  51054. if (data.length > 80 * dim) {
  51055. minX = maxX = data[0];
  51056. minY = maxY = data[1];
  51057. for (var i = dim; i < outerLen; i += dim) {
  51058. x = data[i];
  51059. y = data[i + 1];
  51060. if (x < minX)
  51061. minX = x;
  51062. if (y < minY)
  51063. minY = y;
  51064. if (x > maxX)
  51065. maxX = x;
  51066. if (y > maxY)
  51067. maxY = y;
  51068. }
  51069. // minX, minY and size are later used to transform coords into integers for z-order calculation
  51070. size = Math.max(maxX - minX, maxY - minY);
  51071. }
  51072. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  51073. return triangles;
  51074. }
  51075. Earcut.earcut = earcut;
  51076. // create a circular doubly linked list from polygon points in the specified winding order
  51077. function linkedList(data, start, end, dim, clockwise) {
  51078. var i, last;
  51079. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  51080. for (i = start; i < end; i += dim)
  51081. last = insertNode(i, data[i], data[i + 1], last);
  51082. }
  51083. else {
  51084. for (i = end - dim; i >= start; i -= dim)
  51085. last = insertNode(i, data[i], data[i + 1], last);
  51086. }
  51087. if (last && equals(last, last.next)) {
  51088. removeNode(last);
  51089. last = last.next;
  51090. }
  51091. return last;
  51092. }
  51093. // eliminate colinear or duplicate points
  51094. function filterPoints(start, end) {
  51095. if (!start)
  51096. return start;
  51097. if (!end)
  51098. end = start;
  51099. var p = start, again;
  51100. do {
  51101. again = false;
  51102. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  51103. removeNode(p);
  51104. p = end = p.prev;
  51105. if (p === p.next)
  51106. return null;
  51107. again = true;
  51108. }
  51109. else {
  51110. p = p.next;
  51111. }
  51112. } while (again || p !== end);
  51113. return end;
  51114. }
  51115. // main ear slicing loop which triangulates a polygon (given as a linked list)
  51116. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  51117. if (!ear)
  51118. return;
  51119. // interlink polygon nodes in z-order
  51120. if (!pass && size)
  51121. indexCurve(ear, minX, minY, size);
  51122. var stop = ear, prev, next;
  51123. // iterate through ears, slicing them one by one
  51124. while (ear.prev !== ear.next) {
  51125. prev = ear.prev;
  51126. next = ear.next;
  51127. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  51128. // cut off the triangle
  51129. triangles.push(prev.i / dim);
  51130. triangles.push(ear.i / dim);
  51131. triangles.push(next.i / dim);
  51132. removeNode(ear);
  51133. // skipping the next vertice leads to less sliver triangles
  51134. ear = next.next;
  51135. stop = next.next;
  51136. continue;
  51137. }
  51138. ear = next;
  51139. // if we looped through the whole remaining polygon and can't find any more ears
  51140. if (ear === stop) {
  51141. // try filtering points and slicing again
  51142. if (!pass) {
  51143. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  51144. }
  51145. else if (pass === 1) {
  51146. ear = cureLocalIntersections(ear, triangles, dim);
  51147. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  51148. }
  51149. else if (pass === 2) {
  51150. splitEarcut(ear, triangles, dim, minX, minY, size);
  51151. }
  51152. break;
  51153. }
  51154. }
  51155. }
  51156. // check whether a polygon node forms a valid ear with adjacent nodes
  51157. function isEar(ear) {
  51158. var a = ear.prev, b = ear, c = ear.next;
  51159. if (area(a, b, c) >= 0)
  51160. return false; // reflex, can't be an ear
  51161. // now make sure we don't have other points inside the potential ear
  51162. var p = ear.next.next;
  51163. while (p !== ear.prev) {
  51164. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51165. area(p.prev, p, p.next) >= 0)
  51166. return false;
  51167. p = p.next;
  51168. }
  51169. return true;
  51170. }
  51171. function isEarHashed(ear, minX, minY, size) {
  51172. var a = ear.prev, b = ear, c = ear.next;
  51173. if (area(a, b, c) >= 0)
  51174. return false; // reflex, can't be an ear
  51175. // triangle bbox; min & max are calculated like this for speed
  51176. 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);
  51177. // z-order range for the current triangle bbox;
  51178. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  51179. // first look for points inside the triangle in increasing z-order
  51180. var p = ear.nextZ;
  51181. while (p && p.z <= maxZ) {
  51182. if (p !== ear.prev &&
  51183. p !== ear.next &&
  51184. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51185. area(p.prev, p, p.next) >= 0)
  51186. return false;
  51187. p = p.nextZ;
  51188. }
  51189. // then look for points in decreasing z-order
  51190. p = ear.prevZ;
  51191. while (p && p.z >= minZ) {
  51192. if (p !== ear.prev &&
  51193. p !== ear.next &&
  51194. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51195. area(p.prev, p, p.next) >= 0)
  51196. return false;
  51197. p = p.prevZ;
  51198. }
  51199. return true;
  51200. }
  51201. // go through all polygon nodes and cure small local self-intersections
  51202. function cureLocalIntersections(start, triangles, dim) {
  51203. var p = start;
  51204. do {
  51205. var a = p.prev, b = p.next.next;
  51206. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  51207. triangles.push(a.i / dim);
  51208. triangles.push(p.i / dim);
  51209. triangles.push(b.i / dim);
  51210. // remove two nodes involved
  51211. removeNode(p);
  51212. removeNode(p.next);
  51213. p = start = b;
  51214. }
  51215. p = p.next;
  51216. } while (p !== start);
  51217. return p;
  51218. }
  51219. // try splitting polygon into two and triangulate them independently
  51220. function splitEarcut(start, triangles, dim, minX, minY, size) {
  51221. // look for a valid diagonal that divides the polygon into two
  51222. var a = start;
  51223. do {
  51224. var b = a.next.next;
  51225. while (b !== a.prev) {
  51226. if (a.i !== b.i && isValidDiagonal(a, b)) {
  51227. // split the polygon in two by the diagonal
  51228. var c = splitPolygon(a, b);
  51229. // filter colinear points around the cuts
  51230. a = filterPoints(a, a.next);
  51231. c = filterPoints(c, c.next);
  51232. // run earcut on each half
  51233. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  51234. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  51235. return;
  51236. }
  51237. b = b.next;
  51238. }
  51239. a = a.next;
  51240. } while (a !== start);
  51241. }
  51242. // link every hole into the outer loop, producing a single-ring polygon without holes
  51243. function eliminateHoles(data, holeIndices, outerNode, dim) {
  51244. var queue = [], i, len, start, end, list;
  51245. for (i = 0, len = holeIndices.length; i < len; i++) {
  51246. start = holeIndices[i] * dim;
  51247. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  51248. list = linkedList(data, start, end, dim, false);
  51249. if (list === list.next)
  51250. list.steiner = true;
  51251. queue.push(getLeftmost(list));
  51252. }
  51253. queue.sort(compareX);
  51254. // process holes from left to right
  51255. for (i = 0; i < queue.length; i++) {
  51256. eliminateHole(queue[i], outerNode);
  51257. outerNode = filterPoints(outerNode, outerNode.next);
  51258. }
  51259. return outerNode;
  51260. }
  51261. function compareX(a, b) {
  51262. return a.x - b.x;
  51263. }
  51264. // find a bridge between vertices that connects hole with an outer ring and and link it
  51265. function eliminateHole(hole, outerNode) {
  51266. outerNode = findHoleBridge(hole, outerNode);
  51267. if (outerNode) {
  51268. var b = splitPolygon(outerNode, hole);
  51269. filterPoints(b, b.next);
  51270. }
  51271. }
  51272. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  51273. function findHoleBridge(hole, outerNode) {
  51274. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  51275. // find a segment intersected by a ray from the hole's leftmost point to the left;
  51276. // segment's endpoint with lesser x will be potential connection point
  51277. do {
  51278. if (hy <= p.y && hy >= p.next.y) {
  51279. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  51280. if (x <= hx && x > qx) {
  51281. qx = x;
  51282. if (x === hx) {
  51283. if (hy === p.y)
  51284. return p;
  51285. if (hy === p.next.y)
  51286. return p.next;
  51287. }
  51288. m = p.x < p.next.x ? p : p.next;
  51289. }
  51290. }
  51291. p = p.next;
  51292. } while (p !== outerNode);
  51293. if (!m)
  51294. return null;
  51295. if (hx === qx)
  51296. return m.prev; // hole touches outer segment; pick lower endpoint
  51297. // look for points inside the triangle of hole point, segment intersection and endpoint;
  51298. // if there are no points found, we have a valid connection;
  51299. // otherwise choose the point of the minimum angle with the ray as connection point
  51300. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  51301. p = m.next;
  51302. while (p !== stop) {
  51303. if (hx >= p.x &&
  51304. p.x >= mx &&
  51305. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  51306. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  51307. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  51308. m = p;
  51309. tanMin = tan;
  51310. }
  51311. }
  51312. p = p.next;
  51313. }
  51314. return m;
  51315. }
  51316. // interlink polygon nodes in z-order
  51317. function indexCurve(start, minX, minY, size) {
  51318. var p = start;
  51319. do {
  51320. if (p.z === null)
  51321. p.z = zOrder(p.x, p.y, minX, minY, size);
  51322. p.prevZ = p.prev;
  51323. p.nextZ = p.next;
  51324. p = p.next;
  51325. } while (p !== start);
  51326. p.prevZ.nextZ = null;
  51327. p.prevZ = null;
  51328. sortLinked(p);
  51329. }
  51330. // Simon Tatham's linked list merge sort algorithm
  51331. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  51332. function sortLinked(list) {
  51333. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  51334. do {
  51335. p = list;
  51336. list = null;
  51337. tail = null;
  51338. numMerges = 0;
  51339. while (p) {
  51340. numMerges++;
  51341. q = p;
  51342. pSize = 0;
  51343. for (i = 0; i < inSize; i++) {
  51344. pSize++;
  51345. q = q.nextZ;
  51346. if (!q)
  51347. break;
  51348. }
  51349. qSize = inSize;
  51350. while (pSize > 0 || (qSize > 0 && q)) {
  51351. if (pSize === 0) {
  51352. e = q;
  51353. q = q.nextZ;
  51354. qSize--;
  51355. }
  51356. else if (qSize === 0 || !q) {
  51357. e = p;
  51358. p = p.nextZ;
  51359. pSize--;
  51360. }
  51361. else if (p.z <= q.z) {
  51362. e = p;
  51363. p = p.nextZ;
  51364. pSize--;
  51365. }
  51366. else {
  51367. e = q;
  51368. q = q.nextZ;
  51369. qSize--;
  51370. }
  51371. if (tail)
  51372. tail.nextZ = e;
  51373. else
  51374. list = e;
  51375. e.prevZ = tail;
  51376. tail = e;
  51377. }
  51378. p = q;
  51379. }
  51380. tail.nextZ = null;
  51381. inSize *= 2;
  51382. } while (numMerges > 1);
  51383. return list;
  51384. }
  51385. // z-order of a point given coords and size of the data bounding box
  51386. function zOrder(x, y, minX, minY, size) {
  51387. // coords are transformed into non-negative 15-bit integer range
  51388. x = 32767 * (x - minX) / size;
  51389. y = 32767 * (y - minY) / size;
  51390. x = (x | (x << 8)) & 0x00FF00FF;
  51391. x = (x | (x << 4)) & 0x0F0F0F0F;
  51392. x = (x | (x << 2)) & 0x33333333;
  51393. x = (x | (x << 1)) & 0x55555555;
  51394. y = (y | (y << 8)) & 0x00FF00FF;
  51395. y = (y | (y << 4)) & 0x0F0F0F0F;
  51396. y = (y | (y << 2)) & 0x33333333;
  51397. y = (y | (y << 1)) & 0x55555555;
  51398. return x | (y << 1);
  51399. }
  51400. // find the leftmost node of a polygon ring
  51401. function getLeftmost(start) {
  51402. var p = start, leftmost = start;
  51403. do {
  51404. if (p.x < leftmost.x)
  51405. leftmost = p;
  51406. p = p.next;
  51407. } while (p !== start);
  51408. return leftmost;
  51409. }
  51410. // check if a point lies within a convex triangle
  51411. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  51412. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  51413. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  51414. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  51415. }
  51416. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  51417. function isValidDiagonal(a, b) {
  51418. return a.next.i !== b.i &&
  51419. a.prev.i !== b.i &&
  51420. !intersectsPolygon(a, b) &&
  51421. locallyInside(a, b) &&
  51422. locallyInside(b, a) &&
  51423. middleInside(a, b);
  51424. }
  51425. // signed area of a triangle
  51426. function area(p, q, r) {
  51427. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  51428. }
  51429. // check if two points are equal
  51430. function equals(p1, p2) {
  51431. return p1.x === p2.x && p1.y === p2.y;
  51432. }
  51433. // check if two segments intersect
  51434. function intersects(p1, q1, p2, q2) {
  51435. if ((equals(p1, q1) && equals(p2, q2)) ||
  51436. (equals(p1, q2) && equals(p2, q1)))
  51437. return true;
  51438. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  51439. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  51440. }
  51441. // check if a polygon diagonal intersects any polygon segments
  51442. function intersectsPolygon(a, b) {
  51443. var p = a;
  51444. do {
  51445. if (p.i !== a.i &&
  51446. p.next.i !== a.i &&
  51447. p.i !== b.i &&
  51448. p.next.i !== b.i &&
  51449. intersects(p, p.next, a, b))
  51450. return true;
  51451. p = p.next;
  51452. } while (p !== a);
  51453. return false;
  51454. }
  51455. // check if a polygon diagonal is locally inside the polygon
  51456. function locallyInside(a, b) {
  51457. return area(a.prev, a, a.next) < 0
  51458. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  51459. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  51460. }
  51461. // check if the middle point of a polygon diagonal is inside the polygon
  51462. function middleInside(a, b) {
  51463. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  51464. do {
  51465. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  51466. inside = !inside;
  51467. p = p.next;
  51468. } while (p !== a);
  51469. return inside;
  51470. }
  51471. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  51472. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  51473. function splitPolygon(a, b) {
  51474. 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;
  51475. a.next = b;
  51476. b.prev = a;
  51477. a2.next = an;
  51478. an.prev = a2;
  51479. b2.next = a2;
  51480. a2.prev = b2;
  51481. bp.next = b2;
  51482. b2.prev = bp;
  51483. return b2;
  51484. }
  51485. // create a node and optionally link it with previous one (in a circular doubly linked list)
  51486. function insertNode(i, x, y, last) {
  51487. var p = new Node(i, x, y);
  51488. if (!last) {
  51489. p.prev = p;
  51490. p.next = p;
  51491. }
  51492. else {
  51493. p.next = last.next;
  51494. p.prev = last;
  51495. last.next.prev = p;
  51496. last.next = p;
  51497. }
  51498. return p;
  51499. }
  51500. function removeNode(p) {
  51501. p.next.prev = p.prev;
  51502. p.prev.next = p.next;
  51503. if (p.prevZ)
  51504. p.prevZ.nextZ = p.nextZ;
  51505. if (p.nextZ)
  51506. p.nextZ.prevZ = p.prevZ;
  51507. }
  51508. function Node(i, x, y) {
  51509. // vertice index in coordinates array
  51510. this.i = i;
  51511. // vertex coordinates
  51512. this.x = x;
  51513. this.y = y;
  51514. // previous and next vertice nodes in a polygon ring
  51515. this.prev = null;
  51516. this.next = null;
  51517. // z-order curve value
  51518. this.z = null;
  51519. // previous and next nodes in z-order
  51520. this.prevZ = null;
  51521. this.nextZ = null;
  51522. // indicates whether this is a steiner point
  51523. this.steiner = false;
  51524. }
  51525. /**
  51526. * return a percentage difference between the polygon area and its triangulation area;
  51527. * used to verify correctness of triangulation
  51528. */
  51529. function deviation(data, holeIndices, dim, triangles) {
  51530. var hasHoles = holeIndices && holeIndices.length;
  51531. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  51532. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  51533. if (hasHoles) {
  51534. for (var i = 0, len = holeIndices.length; i < len; i++) {
  51535. var start = holeIndices[i] * dim;
  51536. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  51537. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  51538. }
  51539. }
  51540. var trianglesArea = 0;
  51541. for (i = 0; i < triangles.length; i += 3) {
  51542. var a = triangles[i] * dim;
  51543. var b = triangles[i + 1] * dim;
  51544. var c = triangles[i + 2] * dim;
  51545. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  51546. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  51547. }
  51548. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  51549. }
  51550. Earcut.deviation = deviation;
  51551. ;
  51552. function signedArea(data, start, end, dim) {
  51553. var sum = 0;
  51554. for (var i = start, j = end - dim; i < end; i += dim) {
  51555. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  51556. j = i;
  51557. }
  51558. return sum;
  51559. }
  51560. /**
  51561. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  51562. */
  51563. function flatten(data) {
  51564. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  51565. for (var i = 0; i < data.length; i++) {
  51566. for (var j = 0; j < data[i].length; j++) {
  51567. for (var d = 0; d < dim; d++)
  51568. result.vertices.push(data[i][j][d]);
  51569. }
  51570. if (i > 0) {
  51571. holeIndex += data[i - 1].length;
  51572. result.holes.push(holeIndex);
  51573. }
  51574. }
  51575. return result;
  51576. }
  51577. Earcut.flatten = flatten;
  51578. ;
  51579. })(Earcut || (Earcut = {}));
  51580. var BABYLON;
  51581. (function (BABYLON) {
  51582. // Unique ID when we import meshes from Babylon to CSG
  51583. var currentCSGMeshId = 0;
  51584. // # class Vertex
  51585. // Represents a vertex of a polygon. Use your own vertex class instead of this
  51586. // one to provide additional features like texture coordinates and vertex
  51587. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  51588. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  51589. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  51590. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  51591. // is not used anywhere else.
  51592. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  51593. var Vertex = (function () {
  51594. function Vertex(pos, normal, uv) {
  51595. this.pos = pos;
  51596. this.normal = normal;
  51597. this.uv = uv;
  51598. }
  51599. Vertex.prototype.clone = function () {
  51600. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  51601. };
  51602. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  51603. // orientation of a polygon is flipped.
  51604. Vertex.prototype.flip = function () {
  51605. this.normal = this.normal.scale(-1);
  51606. };
  51607. // Create a new vertex between this vertex and `other` by linearly
  51608. // interpolating all properties using a parameter of `t`. Subclasses should
  51609. // override this to interpolate additional properties.
  51610. Vertex.prototype.interpolate = function (other, t) {
  51611. 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));
  51612. };
  51613. return Vertex;
  51614. })();
  51615. // # class Plane
  51616. // Represents a plane in 3D space.
  51617. var Plane = (function () {
  51618. function Plane(normal, w) {
  51619. this.normal = normal;
  51620. this.w = w;
  51621. }
  51622. Plane.FromPoints = function (a, b, c) {
  51623. var v0 = c.subtract(a);
  51624. var v1 = b.subtract(a);
  51625. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  51626. return null;
  51627. }
  51628. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  51629. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  51630. };
  51631. Plane.prototype.clone = function () {
  51632. return new Plane(this.normal.clone(), this.w);
  51633. };
  51634. Plane.prototype.flip = function () {
  51635. this.normal.scaleInPlace(-1);
  51636. this.w = -this.w;
  51637. };
  51638. // Split `polygon` by this plane if needed, then put the polygon or polygon
  51639. // fragments in the appropriate lists. Coplanar polygons go into either
  51640. // `coplanarFront` or `coplanarBack` depending on their orientation with
  51641. // respect to this plane. Polygons in front or in back of this plane go into
  51642. // either `front` or `back`.
  51643. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  51644. var COPLANAR = 0;
  51645. var FRONT = 1;
  51646. var BACK = 2;
  51647. var SPANNING = 3;
  51648. // Classify each point as well as the entire polygon into one of the above
  51649. // four classes.
  51650. var polygonType = 0;
  51651. var types = [];
  51652. var i;
  51653. var t;
  51654. for (i = 0; i < polygon.vertices.length; i++) {
  51655. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  51656. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  51657. polygonType |= type;
  51658. types.push(type);
  51659. }
  51660. // Put the polygon in the correct list, splitting it when necessary.
  51661. switch (polygonType) {
  51662. case COPLANAR:
  51663. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  51664. break;
  51665. case FRONT:
  51666. front.push(polygon);
  51667. break;
  51668. case BACK:
  51669. back.push(polygon);
  51670. break;
  51671. case SPANNING:
  51672. var f = [], b = [];
  51673. for (i = 0; i < polygon.vertices.length; i++) {
  51674. var j = (i + 1) % polygon.vertices.length;
  51675. var ti = types[i], tj = types[j];
  51676. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  51677. if (ti !== BACK)
  51678. f.push(vi);
  51679. if (ti !== FRONT)
  51680. b.push(ti !== BACK ? vi.clone() : vi);
  51681. if ((ti | tj) === SPANNING) {
  51682. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  51683. var v = vi.interpolate(vj, t);
  51684. f.push(v);
  51685. b.push(v.clone());
  51686. }
  51687. }
  51688. var poly;
  51689. if (f.length >= 3) {
  51690. poly = new Polygon(f, polygon.shared);
  51691. if (poly.plane)
  51692. front.push(poly);
  51693. }
  51694. if (b.length >= 3) {
  51695. poly = new Polygon(b, polygon.shared);
  51696. if (poly.plane)
  51697. back.push(poly);
  51698. }
  51699. break;
  51700. }
  51701. };
  51702. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  51703. // point is on the plane.
  51704. Plane.EPSILON = 1e-5;
  51705. return Plane;
  51706. })();
  51707. // # class Polygon
  51708. // Represents a convex polygon. The vertices used to initialize a polygon must
  51709. // be coplanar and form a convex loop.
  51710. //
  51711. // Each convex polygon has a `shared` property, which is shared between all
  51712. // polygons that are clones of each other or were split from the same polygon.
  51713. // This can be used to define per-polygon properties (such as surface color).
  51714. var Polygon = (function () {
  51715. function Polygon(vertices, shared) {
  51716. this.vertices = vertices;
  51717. this.shared = shared;
  51718. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  51719. }
  51720. Polygon.prototype.clone = function () {
  51721. var vertices = this.vertices.map(function (v) { return v.clone(); });
  51722. return new Polygon(vertices, this.shared);
  51723. };
  51724. Polygon.prototype.flip = function () {
  51725. this.vertices.reverse().map(function (v) { v.flip(); });
  51726. this.plane.flip();
  51727. };
  51728. return Polygon;
  51729. })();
  51730. // # class Node
  51731. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  51732. // by picking a polygon to split along. That polygon (and all other coplanar
  51733. // polygons) are added directly to that node and the other polygons are added to
  51734. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  51735. // no distinction between internal and leaf nodes.
  51736. var Node = (function () {
  51737. function Node(polygons) {
  51738. this.plane = null;
  51739. this.front = null;
  51740. this.back = null;
  51741. this.polygons = [];
  51742. if (polygons) {
  51743. this.build(polygons);
  51744. }
  51745. }
  51746. Node.prototype.clone = function () {
  51747. var node = new Node();
  51748. node.plane = this.plane && this.plane.clone();
  51749. node.front = this.front && this.front.clone();
  51750. node.back = this.back && this.back.clone();
  51751. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  51752. return node;
  51753. };
  51754. // Convert solid space to empty space and empty space to solid space.
  51755. Node.prototype.invert = function () {
  51756. for (var i = 0; i < this.polygons.length; i++) {
  51757. this.polygons[i].flip();
  51758. }
  51759. if (this.plane) {
  51760. this.plane.flip();
  51761. }
  51762. if (this.front) {
  51763. this.front.invert();
  51764. }
  51765. if (this.back) {
  51766. this.back.invert();
  51767. }
  51768. var temp = this.front;
  51769. this.front = this.back;
  51770. this.back = temp;
  51771. };
  51772. // Recursively remove all polygons in `polygons` that are inside this BSP
  51773. // tree.
  51774. Node.prototype.clipPolygons = function (polygons) {
  51775. if (!this.plane)
  51776. return polygons.slice();
  51777. var front = [], back = [];
  51778. for (var i = 0; i < polygons.length; i++) {
  51779. this.plane.splitPolygon(polygons[i], front, back, front, back);
  51780. }
  51781. if (this.front) {
  51782. front = this.front.clipPolygons(front);
  51783. }
  51784. if (this.back) {
  51785. back = this.back.clipPolygons(back);
  51786. }
  51787. else {
  51788. back = [];
  51789. }
  51790. return front.concat(back);
  51791. };
  51792. // Remove all polygons in this BSP tree that are inside the other BSP tree
  51793. // `bsp`.
  51794. Node.prototype.clipTo = function (bsp) {
  51795. this.polygons = bsp.clipPolygons(this.polygons);
  51796. if (this.front)
  51797. this.front.clipTo(bsp);
  51798. if (this.back)
  51799. this.back.clipTo(bsp);
  51800. };
  51801. // Return a list of all polygons in this BSP tree.
  51802. Node.prototype.allPolygons = function () {
  51803. var polygons = this.polygons.slice();
  51804. if (this.front)
  51805. polygons = polygons.concat(this.front.allPolygons());
  51806. if (this.back)
  51807. polygons = polygons.concat(this.back.allPolygons());
  51808. return polygons;
  51809. };
  51810. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  51811. // new polygons are filtered down to the bottom of the tree and become new
  51812. // nodes there. Each set of polygons is partitioned using the first polygon
  51813. // (no heuristic is used to pick a good split).
  51814. Node.prototype.build = function (polygons) {
  51815. if (!polygons.length)
  51816. return;
  51817. if (!this.plane)
  51818. this.plane = polygons[0].plane.clone();
  51819. var front = [], back = [];
  51820. for (var i = 0; i < polygons.length; i++) {
  51821. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  51822. }
  51823. if (front.length) {
  51824. if (!this.front)
  51825. this.front = new Node();
  51826. this.front.build(front);
  51827. }
  51828. if (back.length) {
  51829. if (!this.back)
  51830. this.back = new Node();
  51831. this.back.build(back);
  51832. }
  51833. };
  51834. return Node;
  51835. })();
  51836. var CSG = (function () {
  51837. function CSG() {
  51838. this.polygons = new Array();
  51839. }
  51840. // Convert BABYLON.Mesh to BABYLON.CSG
  51841. CSG.FromMesh = function (mesh) {
  51842. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  51843. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  51844. if (mesh instanceof BABYLON.Mesh) {
  51845. mesh.computeWorldMatrix(true);
  51846. matrix = mesh.getWorldMatrix();
  51847. meshPosition = mesh.position.clone();
  51848. meshRotation = mesh.rotation.clone();
  51849. if (mesh.rotationQuaternion) {
  51850. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  51851. }
  51852. meshScaling = mesh.scaling.clone();
  51853. }
  51854. else {
  51855. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  51856. }
  51857. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51858. var subMeshes = mesh.subMeshes;
  51859. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  51860. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  51861. vertices = [];
  51862. for (var j = 0; j < 3; j++) {
  51863. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  51864. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  51865. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  51866. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  51867. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  51868. vertex = new Vertex(position, normal, uv);
  51869. vertices.push(vertex);
  51870. }
  51871. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  51872. // To handle the case of degenerated triangle
  51873. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  51874. if (polygon.plane)
  51875. polygons.push(polygon);
  51876. }
  51877. }
  51878. var csg = CSG.FromPolygons(polygons);
  51879. csg.matrix = matrix;
  51880. csg.position = meshPosition;
  51881. csg.rotation = meshRotation;
  51882. csg.scaling = meshScaling;
  51883. csg.rotationQuaternion = meshRotationQuaternion;
  51884. currentCSGMeshId++;
  51885. return csg;
  51886. };
  51887. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  51888. CSG.FromPolygons = function (polygons) {
  51889. var csg = new CSG();
  51890. csg.polygons = polygons;
  51891. return csg;
  51892. };
  51893. CSG.prototype.clone = function () {
  51894. var csg = new CSG();
  51895. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  51896. csg.copyTransformAttributes(this);
  51897. return csg;
  51898. };
  51899. CSG.prototype.toPolygons = function () {
  51900. return this.polygons;
  51901. };
  51902. CSG.prototype.union = function (csg) {
  51903. var a = new Node(this.clone().polygons);
  51904. var b = new Node(csg.clone().polygons);
  51905. a.clipTo(b);
  51906. b.clipTo(a);
  51907. b.invert();
  51908. b.clipTo(a);
  51909. b.invert();
  51910. a.build(b.allPolygons());
  51911. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51912. };
  51913. CSG.prototype.unionInPlace = function (csg) {
  51914. var a = new Node(this.polygons);
  51915. var b = new Node(csg.polygons);
  51916. a.clipTo(b);
  51917. b.clipTo(a);
  51918. b.invert();
  51919. b.clipTo(a);
  51920. b.invert();
  51921. a.build(b.allPolygons());
  51922. this.polygons = a.allPolygons();
  51923. };
  51924. CSG.prototype.subtract = function (csg) {
  51925. var a = new Node(this.clone().polygons);
  51926. var b = new Node(csg.clone().polygons);
  51927. a.invert();
  51928. a.clipTo(b);
  51929. b.clipTo(a);
  51930. b.invert();
  51931. b.clipTo(a);
  51932. b.invert();
  51933. a.build(b.allPolygons());
  51934. a.invert();
  51935. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51936. };
  51937. CSG.prototype.subtractInPlace = function (csg) {
  51938. var a = new Node(this.polygons);
  51939. var b = new Node(csg.polygons);
  51940. a.invert();
  51941. a.clipTo(b);
  51942. b.clipTo(a);
  51943. b.invert();
  51944. b.clipTo(a);
  51945. b.invert();
  51946. a.build(b.allPolygons());
  51947. a.invert();
  51948. this.polygons = a.allPolygons();
  51949. };
  51950. CSG.prototype.intersect = function (csg) {
  51951. var a = new Node(this.clone().polygons);
  51952. var b = new Node(csg.clone().polygons);
  51953. a.invert();
  51954. b.clipTo(a);
  51955. b.invert();
  51956. a.clipTo(b);
  51957. b.clipTo(a);
  51958. a.build(b.allPolygons());
  51959. a.invert();
  51960. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51961. };
  51962. CSG.prototype.intersectInPlace = function (csg) {
  51963. var a = new Node(this.polygons);
  51964. var b = new Node(csg.polygons);
  51965. a.invert();
  51966. b.clipTo(a);
  51967. b.invert();
  51968. a.clipTo(b);
  51969. b.clipTo(a);
  51970. a.build(b.allPolygons());
  51971. a.invert();
  51972. this.polygons = a.allPolygons();
  51973. };
  51974. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  51975. // not modified.
  51976. CSG.prototype.inverse = function () {
  51977. var csg = this.clone();
  51978. csg.inverseInPlace();
  51979. return csg;
  51980. };
  51981. CSG.prototype.inverseInPlace = function () {
  51982. this.polygons.map(function (p) { p.flip(); });
  51983. };
  51984. // This is used to keep meshes transformations so they can be restored
  51985. // when we build back a Babylon Mesh
  51986. // NB : All CSG operations are performed in world coordinates
  51987. CSG.prototype.copyTransformAttributes = function (csg) {
  51988. this.matrix = csg.matrix;
  51989. this.position = csg.position;
  51990. this.rotation = csg.rotation;
  51991. this.scaling = csg.scaling;
  51992. this.rotationQuaternion = csg.rotationQuaternion;
  51993. return this;
  51994. };
  51995. // Build Raw mesh from CSG
  51996. // Coordinates here are in world space
  51997. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  51998. var matrix = this.matrix.clone();
  51999. matrix.invert();
  52000. 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;
  52001. if (keepSubMeshes) {
  52002. // Sort Polygons, since subMeshes are indices range
  52003. polygons.sort(function (a, b) {
  52004. if (a.shared.meshId === b.shared.meshId) {
  52005. return a.shared.subMeshId - b.shared.subMeshId;
  52006. }
  52007. else {
  52008. return a.shared.meshId - b.shared.meshId;
  52009. }
  52010. });
  52011. }
  52012. for (var i = 0, il = polygons.length; i < il; i++) {
  52013. polygon = polygons[i];
  52014. // Building SubMeshes
  52015. if (!subMesh_dict[polygon.shared.meshId]) {
  52016. subMesh_dict[polygon.shared.meshId] = {};
  52017. }
  52018. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  52019. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  52020. indexStart: +Infinity,
  52021. indexEnd: -Infinity,
  52022. materialIndex: polygon.shared.materialIndex
  52023. };
  52024. }
  52025. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  52026. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  52027. polygonIndices[0] = 0;
  52028. polygonIndices[1] = j - 1;
  52029. polygonIndices[2] = j;
  52030. for (var k = 0; k < 3; k++) {
  52031. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  52032. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  52033. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  52034. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  52035. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  52036. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  52037. // Check if 2 points can be merged
  52038. if (!(typeof vertex_idx !== 'undefined' &&
  52039. normals[vertex_idx * 3] === localNormal.x &&
  52040. normals[vertex_idx * 3 + 1] === localNormal.y &&
  52041. normals[vertex_idx * 3 + 2] === localNormal.z &&
  52042. uvs[vertex_idx * 2] === uv.x &&
  52043. uvs[vertex_idx * 2 + 1] === uv.y)) {
  52044. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  52045. uvs.push(uv.x, uv.y);
  52046. normals.push(normal.x, normal.y, normal.z);
  52047. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  52048. }
  52049. indices.push(vertex_idx);
  52050. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  52051. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  52052. currentIndex++;
  52053. }
  52054. }
  52055. }
  52056. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  52057. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  52058. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  52059. mesh.setIndices(indices);
  52060. if (keepSubMeshes) {
  52061. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  52062. var materialIndexOffset = 0, materialMaxIndex;
  52063. mesh.subMeshes = new Array();
  52064. for (var m in subMesh_dict) {
  52065. materialMaxIndex = -1;
  52066. for (var sm in subMesh_dict[m]) {
  52067. subMesh_obj = subMesh_dict[m][sm];
  52068. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  52069. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  52070. }
  52071. materialIndexOffset += ++materialMaxIndex;
  52072. }
  52073. }
  52074. return mesh;
  52075. };
  52076. // Build Mesh from CSG taking material and transforms into account
  52077. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  52078. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  52079. mesh.material = material;
  52080. mesh.position.copyFrom(this.position);
  52081. mesh.rotation.copyFrom(this.rotation);
  52082. if (this.rotationQuaternion) {
  52083. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  52084. }
  52085. mesh.scaling.copyFrom(this.scaling);
  52086. mesh.computeWorldMatrix(true);
  52087. return mesh;
  52088. };
  52089. return CSG;
  52090. })();
  52091. BABYLON.CSG = CSG;
  52092. })(BABYLON || (BABYLON = {}));
  52093. var BABYLON;
  52094. (function (BABYLON) {
  52095. var VRDistortionCorrectionPostProcess = (function (_super) {
  52096. __extends(VRDistortionCorrectionPostProcess, _super);
  52097. //ANY
  52098. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  52099. var _this = this;
  52100. _super.call(this, name, "vrDistortionCorrection", [
  52101. 'LensCenter',
  52102. 'Scale',
  52103. 'ScaleIn',
  52104. 'HmdWarpParam'
  52105. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  52106. this._isRightEye = isRightEye;
  52107. this._distortionFactors = vrMetrics.distortionK;
  52108. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  52109. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  52110. this.onSizeChangedObservable.add(function () {
  52111. _this.aspectRatio = _this.width * .5 / _this.height;
  52112. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  52113. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  52114. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  52115. });
  52116. this.onApplyObservable.add(function (effect) {
  52117. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  52118. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  52119. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  52120. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  52121. });
  52122. }
  52123. return VRDistortionCorrectionPostProcess;
  52124. })(BABYLON.PostProcess);
  52125. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  52126. })(BABYLON || (BABYLON = {}));
  52127. // Mainly based on these 2 articles :
  52128. // 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
  52129. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  52130. var BABYLON;
  52131. (function (BABYLON) {
  52132. (function (JoystickAxis) {
  52133. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  52134. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  52135. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  52136. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  52137. var JoystickAxis = BABYLON.JoystickAxis;
  52138. var VirtualJoystick = (function () {
  52139. function VirtualJoystick(leftJoystick) {
  52140. var _this = this;
  52141. if (leftJoystick) {
  52142. this._leftJoystick = true;
  52143. }
  52144. else {
  52145. this._leftJoystick = false;
  52146. }
  52147. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  52148. VirtualJoystick._globalJoystickIndex++;
  52149. // By default left & right arrow keys are moving the X
  52150. // and up & down keys are moving the Y
  52151. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  52152. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  52153. this.reverseLeftRight = false;
  52154. this.reverseUpDown = false;
  52155. // collections of pointers
  52156. this._touches = new BABYLON.StringDictionary();
  52157. this.deltaPosition = BABYLON.Vector3.Zero();
  52158. this._joystickSensibility = 25;
  52159. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  52160. this._rotationSpeed = 25;
  52161. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  52162. this._rotateOnAxisRelativeToMesh = false;
  52163. this._onResize = function (evt) {
  52164. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  52165. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  52166. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  52167. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  52168. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  52169. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  52170. };
  52171. // injecting a canvas element on top of the canvas 3D game
  52172. if (!VirtualJoystick.vjCanvas) {
  52173. window.addEventListener("resize", this._onResize, false);
  52174. VirtualJoystick.vjCanvas = document.createElement("canvas");
  52175. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  52176. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  52177. VirtualJoystick.vjCanvas.width = window.innerWidth;
  52178. VirtualJoystick.vjCanvas.height = window.innerHeight;
  52179. VirtualJoystick.vjCanvas.style.width = "100%";
  52180. VirtualJoystick.vjCanvas.style.height = "100%";
  52181. VirtualJoystick.vjCanvas.style.position = "absolute";
  52182. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  52183. VirtualJoystick.vjCanvas.style.top = "0px";
  52184. VirtualJoystick.vjCanvas.style.left = "0px";
  52185. VirtualJoystick.vjCanvas.style.zIndex = "5";
  52186. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  52187. // Support for jQuery PEP polyfill
  52188. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  52189. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  52190. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  52191. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  52192. document.body.appendChild(VirtualJoystick.vjCanvas);
  52193. }
  52194. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  52195. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  52196. this.pressed = false;
  52197. // default joystick color
  52198. this._joystickColor = "cyan";
  52199. this._joystickPointerID = -1;
  52200. // current joystick position
  52201. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  52202. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  52203. // origin joystick position
  52204. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  52205. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  52206. this._onPointerDownHandlerRef = function (evt) {
  52207. _this._onPointerDown(evt);
  52208. };
  52209. this._onPointerMoveHandlerRef = function (evt) {
  52210. _this._onPointerMove(evt);
  52211. };
  52212. this._onPointerOutHandlerRef = function (evt) {
  52213. _this._onPointerUp(evt);
  52214. };
  52215. this._onPointerUpHandlerRef = function (evt) {
  52216. _this._onPointerUp(evt);
  52217. };
  52218. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  52219. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  52220. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  52221. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  52222. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  52223. evt.preventDefault(); // Disables system menu
  52224. }, false);
  52225. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  52226. }
  52227. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  52228. this._joystickSensibility = newJoystickSensibility;
  52229. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  52230. };
  52231. VirtualJoystick.prototype._onPointerDown = function (e) {
  52232. var positionOnScreenCondition;
  52233. e.preventDefault();
  52234. if (this._leftJoystick === true) {
  52235. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  52236. }
  52237. else {
  52238. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  52239. }
  52240. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  52241. // First contact will be dedicated to the virtual joystick
  52242. this._joystickPointerID = e.pointerId;
  52243. this._joystickPointerStartPos.x = e.clientX;
  52244. this._joystickPointerStartPos.y = e.clientY;
  52245. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  52246. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  52247. this._deltaJoystickVector.x = 0;
  52248. this._deltaJoystickVector.y = 0;
  52249. this.pressed = true;
  52250. this._touches.add(e.pointerId.toString(), e);
  52251. }
  52252. else {
  52253. // You can only trigger the action buttons with a joystick declared
  52254. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  52255. this._action();
  52256. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  52257. }
  52258. }
  52259. };
  52260. VirtualJoystick.prototype._onPointerMove = function (e) {
  52261. // If the current pointer is the one associated to the joystick (first touch contact)
  52262. if (this._joystickPointerID == e.pointerId) {
  52263. this._joystickPointerPos.x = e.clientX;
  52264. this._joystickPointerPos.y = e.clientY;
  52265. this._deltaJoystickVector = this._joystickPointerPos.clone();
  52266. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  52267. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  52268. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  52269. switch (this._axisTargetedByLeftAndRight) {
  52270. case JoystickAxis.X:
  52271. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  52272. break;
  52273. case JoystickAxis.Y:
  52274. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  52275. break;
  52276. case JoystickAxis.Z:
  52277. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  52278. break;
  52279. }
  52280. var directionUpDown = this.reverseUpDown ? 1 : -1;
  52281. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  52282. switch (this._axisTargetedByUpAndDown) {
  52283. case JoystickAxis.X:
  52284. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  52285. break;
  52286. case JoystickAxis.Y:
  52287. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  52288. break;
  52289. case JoystickAxis.Z:
  52290. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  52291. break;
  52292. }
  52293. }
  52294. else {
  52295. var data = this._touches.get(e.pointerId.toString());
  52296. if (data) {
  52297. data.x = e.clientX;
  52298. data.y = e.clientY;
  52299. }
  52300. }
  52301. };
  52302. VirtualJoystick.prototype._onPointerUp = function (e) {
  52303. if (this._joystickPointerID == e.pointerId) {
  52304. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  52305. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  52306. this._joystickPointerID = -1;
  52307. this.pressed = false;
  52308. }
  52309. else {
  52310. var touch = this._touches.get(e.pointerId.toString());
  52311. if (touch) {
  52312. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  52313. }
  52314. }
  52315. this._deltaJoystickVector.x = 0;
  52316. this._deltaJoystickVector.y = 0;
  52317. this._touches.remove(e.pointerId.toString());
  52318. };
  52319. /**
  52320. * Change the color of the virtual joystick
  52321. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  52322. */
  52323. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  52324. this._joystickColor = newColor;
  52325. };
  52326. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  52327. this._action = action;
  52328. };
  52329. // Define which axis you'd like to control for left & right
  52330. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  52331. switch (axis) {
  52332. case JoystickAxis.X:
  52333. case JoystickAxis.Y:
  52334. case JoystickAxis.Z:
  52335. this._axisTargetedByLeftAndRight = axis;
  52336. break;
  52337. default:
  52338. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  52339. break;
  52340. }
  52341. };
  52342. // Define which axis you'd like to control for up & down
  52343. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  52344. switch (axis) {
  52345. case JoystickAxis.X:
  52346. case JoystickAxis.Y:
  52347. case JoystickAxis.Z:
  52348. this._axisTargetedByUpAndDown = axis;
  52349. break;
  52350. default:
  52351. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  52352. break;
  52353. }
  52354. };
  52355. VirtualJoystick.prototype._clearCanvas = function () {
  52356. if (this._leftJoystick) {
  52357. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  52358. }
  52359. else {
  52360. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  52361. }
  52362. };
  52363. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  52364. var _this = this;
  52365. if (this.pressed) {
  52366. this._touches.forEach(function (touch) {
  52367. if (touch.pointerId === _this._joystickPointerID) {
  52368. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  52369. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  52370. VirtualJoystick.vjCanvasContext.beginPath();
  52371. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  52372. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52373. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  52374. VirtualJoystick.vjCanvasContext.stroke();
  52375. VirtualJoystick.vjCanvasContext.closePath();
  52376. VirtualJoystick.vjCanvasContext.beginPath();
  52377. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52378. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  52379. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  52380. VirtualJoystick.vjCanvasContext.stroke();
  52381. VirtualJoystick.vjCanvasContext.closePath();
  52382. VirtualJoystick.vjCanvasContext.beginPath();
  52383. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52384. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  52385. VirtualJoystick.vjCanvasContext.stroke();
  52386. VirtualJoystick.vjCanvasContext.closePath();
  52387. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  52388. }
  52389. else {
  52390. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  52391. VirtualJoystick.vjCanvasContext.beginPath();
  52392. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  52393. VirtualJoystick.vjCanvasContext.beginPath();
  52394. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  52395. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  52396. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  52397. VirtualJoystick.vjCanvasContext.stroke();
  52398. VirtualJoystick.vjCanvasContext.closePath();
  52399. touch.prevX = touch.x;
  52400. touch.prevY = touch.y;
  52401. }
  52402. ;
  52403. });
  52404. }
  52405. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  52406. };
  52407. VirtualJoystick.prototype.releaseCanvas = function () {
  52408. if (VirtualJoystick.vjCanvas) {
  52409. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  52410. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  52411. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  52412. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  52413. window.removeEventListener("resize", this._onResize);
  52414. document.body.removeChild(VirtualJoystick.vjCanvas);
  52415. VirtualJoystick.vjCanvas = null;
  52416. }
  52417. };
  52418. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  52419. VirtualJoystick._globalJoystickIndex = 0;
  52420. return VirtualJoystick;
  52421. })();
  52422. BABYLON.VirtualJoystick = VirtualJoystick;
  52423. })(BABYLON || (BABYLON = {}));
  52424. var BABYLON;
  52425. (function (BABYLON) {
  52426. // We're mainly based on the logic defined into the FreeCamera code
  52427. var VirtualJoysticksCamera = (function (_super) {
  52428. __extends(VirtualJoysticksCamera, _super);
  52429. function VirtualJoysticksCamera(name, position, scene) {
  52430. _super.call(this, name, position, scene);
  52431. this.inputs.addVirtualJoystick();
  52432. }
  52433. return VirtualJoysticksCamera;
  52434. })(BABYLON.FreeCamera);
  52435. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  52436. })(BABYLON || (BABYLON = {}));
  52437. var BABYLON;
  52438. (function (BABYLON) {
  52439. var FreeCameraVirtualJoystickInput = (function () {
  52440. function FreeCameraVirtualJoystickInput() {
  52441. }
  52442. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  52443. return this._leftjoystick;
  52444. };
  52445. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  52446. return this._rightjoystick;
  52447. };
  52448. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  52449. if (this._leftjoystick) {
  52450. var camera = this.camera;
  52451. var speed = camera._computeLocalCameraSpeed() * 50;
  52452. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  52453. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  52454. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  52455. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  52456. if (!this._leftjoystick.pressed) {
  52457. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  52458. }
  52459. if (!this._rightjoystick.pressed) {
  52460. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  52461. }
  52462. }
  52463. };
  52464. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  52465. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  52466. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  52467. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  52468. this._leftjoystick.setJoystickSensibility(0.15);
  52469. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  52470. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  52471. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  52472. this._rightjoystick.reverseUpDown = true;
  52473. this._rightjoystick.setJoystickSensibility(0.05);
  52474. this._rightjoystick.setJoystickColor("yellow");
  52475. };
  52476. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  52477. this._leftjoystick.releaseCanvas();
  52478. this._rightjoystick.releaseCanvas();
  52479. };
  52480. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  52481. return "FreeCameraVirtualJoystickInput";
  52482. };
  52483. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  52484. return "virtualJoystick";
  52485. };
  52486. return FreeCameraVirtualJoystickInput;
  52487. })();
  52488. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  52489. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  52490. })(BABYLON || (BABYLON = {}));
  52491. var BABYLON;
  52492. (function (BABYLON) {
  52493. var AnaglyphPostProcess = (function (_super) {
  52494. __extends(AnaglyphPostProcess, _super);
  52495. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  52496. var _this = this;
  52497. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  52498. this._passedProcess = rigCameras[0]._rigPostProcess;
  52499. this.onApplyObservable.add(function (effect) {
  52500. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  52501. });
  52502. }
  52503. return AnaglyphPostProcess;
  52504. })(BABYLON.PostProcess);
  52505. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  52506. })(BABYLON || (BABYLON = {}));
  52507. var BABYLON;
  52508. (function (BABYLON) {
  52509. var OutlineRenderer = (function () {
  52510. function OutlineRenderer(scene) {
  52511. this._scene = scene;
  52512. }
  52513. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  52514. var _this = this;
  52515. if (useOverlay === void 0) { useOverlay = false; }
  52516. var scene = this._scene;
  52517. var engine = this._scene.getEngine();
  52518. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52519. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  52520. return;
  52521. }
  52522. var mesh = subMesh.getRenderingMesh();
  52523. var material = subMesh.getMaterial();
  52524. engine.enableEffect(this._effect);
  52525. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  52526. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  52527. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52528. // Bones
  52529. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52530. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52531. }
  52532. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52533. // Alpha test
  52534. if (material && material.needAlphaTesting()) {
  52535. var alphaTexture = material.getAlphaTestTexture();
  52536. this._effect.setTexture("diffuseSampler", alphaTexture);
  52537. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52538. }
  52539. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  52540. };
  52541. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  52542. var defines = [];
  52543. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  52544. var mesh = subMesh.getMesh();
  52545. var material = subMesh.getMaterial();
  52546. // Alpha test
  52547. if (material && material.needAlphaTesting()) {
  52548. defines.push("#define ALPHATEST");
  52549. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52550. attribs.push(BABYLON.VertexBuffer.UVKind);
  52551. defines.push("#define UV1");
  52552. }
  52553. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52554. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52555. defines.push("#define UV2");
  52556. }
  52557. }
  52558. // Bones
  52559. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52560. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52561. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52562. if (mesh.numBoneInfluencers > 4) {
  52563. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52564. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52565. }
  52566. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52567. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52568. }
  52569. else {
  52570. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52571. }
  52572. // Instances
  52573. if (useInstances) {
  52574. defines.push("#define INSTANCES");
  52575. attribs.push("world0");
  52576. attribs.push("world1");
  52577. attribs.push("world2");
  52578. attribs.push("world3");
  52579. }
  52580. // Get correct effect
  52581. var join = defines.join("\n");
  52582. if (this._cachedDefines !== join) {
  52583. this._cachedDefines = join;
  52584. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  52585. }
  52586. return this._effect.isReady();
  52587. };
  52588. return OutlineRenderer;
  52589. })();
  52590. BABYLON.OutlineRenderer = OutlineRenderer;
  52591. })(BABYLON || (BABYLON = {}));
  52592. var BABYLON;
  52593. (function (BABYLON) {
  52594. var MeshAssetTask = (function () {
  52595. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  52596. this.name = name;
  52597. this.meshesNames = meshesNames;
  52598. this.rootUrl = rootUrl;
  52599. this.sceneFilename = sceneFilename;
  52600. this.isCompleted = false;
  52601. }
  52602. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52603. var _this = this;
  52604. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  52605. _this.loadedMeshes = meshes;
  52606. _this.loadedParticleSystems = particleSystems;
  52607. _this.loadedSkeletons = skeletons;
  52608. _this.isCompleted = true;
  52609. if (_this.onSuccess) {
  52610. _this.onSuccess(_this);
  52611. }
  52612. onSuccess();
  52613. }, null, function () {
  52614. if (_this.onError) {
  52615. _this.onError(_this);
  52616. }
  52617. onError();
  52618. });
  52619. };
  52620. return MeshAssetTask;
  52621. })();
  52622. BABYLON.MeshAssetTask = MeshAssetTask;
  52623. var TextFileAssetTask = (function () {
  52624. function TextFileAssetTask(name, url) {
  52625. this.name = name;
  52626. this.url = url;
  52627. this.isCompleted = false;
  52628. }
  52629. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52630. var _this = this;
  52631. BABYLON.Tools.LoadFile(this.url, function (data) {
  52632. _this.text = data;
  52633. _this.isCompleted = true;
  52634. if (_this.onSuccess) {
  52635. _this.onSuccess(_this);
  52636. }
  52637. onSuccess();
  52638. }, null, scene.database, false, function () {
  52639. if (_this.onError) {
  52640. _this.onError(_this);
  52641. }
  52642. onError();
  52643. });
  52644. };
  52645. return TextFileAssetTask;
  52646. })();
  52647. BABYLON.TextFileAssetTask = TextFileAssetTask;
  52648. var BinaryFileAssetTask = (function () {
  52649. function BinaryFileAssetTask(name, url) {
  52650. this.name = name;
  52651. this.url = url;
  52652. this.isCompleted = false;
  52653. }
  52654. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52655. var _this = this;
  52656. BABYLON.Tools.LoadFile(this.url, function (data) {
  52657. _this.data = data;
  52658. _this.isCompleted = true;
  52659. if (_this.onSuccess) {
  52660. _this.onSuccess(_this);
  52661. }
  52662. onSuccess();
  52663. }, null, scene.database, true, function () {
  52664. if (_this.onError) {
  52665. _this.onError(_this);
  52666. }
  52667. onError();
  52668. });
  52669. };
  52670. return BinaryFileAssetTask;
  52671. })();
  52672. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  52673. var ImageAssetTask = (function () {
  52674. function ImageAssetTask(name, url) {
  52675. this.name = name;
  52676. this.url = url;
  52677. this.isCompleted = false;
  52678. }
  52679. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52680. var _this = this;
  52681. var img = new Image();
  52682. BABYLON.Tools.SetCorsBehavior(this.url, img);
  52683. img.onload = function () {
  52684. _this.image = img;
  52685. _this.isCompleted = true;
  52686. if (_this.onSuccess) {
  52687. _this.onSuccess(_this);
  52688. }
  52689. onSuccess();
  52690. };
  52691. img.onerror = function () {
  52692. if (_this.onError) {
  52693. _this.onError(_this);
  52694. }
  52695. onError();
  52696. };
  52697. img.src = this.url;
  52698. };
  52699. return ImageAssetTask;
  52700. })();
  52701. BABYLON.ImageAssetTask = ImageAssetTask;
  52702. var TextureAssetTask = (function () {
  52703. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  52704. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52705. this.name = name;
  52706. this.url = url;
  52707. this.noMipmap = noMipmap;
  52708. this.invertY = invertY;
  52709. this.samplingMode = samplingMode;
  52710. this.isCompleted = false;
  52711. }
  52712. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52713. var _this = this;
  52714. var onload = function () {
  52715. _this.isCompleted = true;
  52716. if (_this.onSuccess) {
  52717. _this.onSuccess(_this);
  52718. }
  52719. onSuccess();
  52720. };
  52721. var onerror = function () {
  52722. if (_this.onError) {
  52723. _this.onError(_this);
  52724. }
  52725. onError();
  52726. };
  52727. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  52728. };
  52729. return TextureAssetTask;
  52730. })();
  52731. BABYLON.TextureAssetTask = TextureAssetTask;
  52732. var AssetsManager = (function () {
  52733. function AssetsManager(scene) {
  52734. this._tasks = new Array();
  52735. this._waitingTasksCount = 0;
  52736. this.useDefaultLoadingScreen = true;
  52737. this._scene = scene;
  52738. }
  52739. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  52740. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  52741. this._tasks.push(task);
  52742. return task;
  52743. };
  52744. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  52745. var task = new TextFileAssetTask(taskName, url);
  52746. this._tasks.push(task);
  52747. return task;
  52748. };
  52749. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  52750. var task = new BinaryFileAssetTask(taskName, url);
  52751. this._tasks.push(task);
  52752. return task;
  52753. };
  52754. AssetsManager.prototype.addImageTask = function (taskName, url) {
  52755. var task = new ImageAssetTask(taskName, url);
  52756. this._tasks.push(task);
  52757. return task;
  52758. };
  52759. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  52760. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52761. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  52762. this._tasks.push(task);
  52763. return task;
  52764. };
  52765. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  52766. this._waitingTasksCount--;
  52767. if (this._waitingTasksCount === 0) {
  52768. if (this.onFinish) {
  52769. this.onFinish(this._tasks);
  52770. }
  52771. this._scene.getEngine().hideLoadingUI();
  52772. }
  52773. };
  52774. AssetsManager.prototype._runTask = function (task) {
  52775. var _this = this;
  52776. task.run(this._scene, function () {
  52777. if (_this.onTaskSuccess) {
  52778. _this.onTaskSuccess(task);
  52779. }
  52780. _this._decreaseWaitingTasksCount();
  52781. }, function () {
  52782. if (_this.onTaskError) {
  52783. _this.onTaskError(task);
  52784. }
  52785. _this._decreaseWaitingTasksCount();
  52786. });
  52787. };
  52788. AssetsManager.prototype.reset = function () {
  52789. this._tasks = new Array();
  52790. return this;
  52791. };
  52792. AssetsManager.prototype.load = function () {
  52793. this._waitingTasksCount = this._tasks.length;
  52794. if (this._waitingTasksCount === 0) {
  52795. if (this.onFinish) {
  52796. this.onFinish(this._tasks);
  52797. }
  52798. return this;
  52799. }
  52800. if (this.useDefaultLoadingScreen) {
  52801. this._scene.getEngine().displayLoadingUI();
  52802. }
  52803. for (var index = 0; index < this._tasks.length; index++) {
  52804. var task = this._tasks[index];
  52805. this._runTask(task);
  52806. }
  52807. return this;
  52808. };
  52809. return AssetsManager;
  52810. })();
  52811. BABYLON.AssetsManager = AssetsManager;
  52812. })(BABYLON || (BABYLON = {}));
  52813. var BABYLON;
  52814. (function (BABYLON) {
  52815. var VRCameraMetrics = (function () {
  52816. function VRCameraMetrics() {
  52817. this.compensateDistortion = true;
  52818. }
  52819. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  52820. get: function () {
  52821. return this.hResolution / (2 * this.vResolution);
  52822. },
  52823. enumerable: true,
  52824. configurable: true
  52825. });
  52826. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  52827. get: function () {
  52828. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  52829. },
  52830. enumerable: true,
  52831. configurable: true
  52832. });
  52833. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  52834. get: function () {
  52835. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  52836. var h = (4 * meters) / this.hScreenSize;
  52837. return BABYLON.Matrix.Translation(h, 0, 0);
  52838. },
  52839. enumerable: true,
  52840. configurable: true
  52841. });
  52842. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  52843. get: function () {
  52844. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  52845. var h = (4 * meters) / this.hScreenSize;
  52846. return BABYLON.Matrix.Translation(-h, 0, 0);
  52847. },
  52848. enumerable: true,
  52849. configurable: true
  52850. });
  52851. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  52852. get: function () {
  52853. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  52854. },
  52855. enumerable: true,
  52856. configurable: true
  52857. });
  52858. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  52859. get: function () {
  52860. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  52861. },
  52862. enumerable: true,
  52863. configurable: true
  52864. });
  52865. VRCameraMetrics.GetDefault = function () {
  52866. var result = new VRCameraMetrics();
  52867. result.hResolution = 1280;
  52868. result.vResolution = 800;
  52869. result.hScreenSize = 0.149759993;
  52870. result.vScreenSize = 0.0935999975;
  52871. result.vScreenCenter = 0.0467999987,
  52872. result.eyeToScreenDistance = 0.0410000011;
  52873. result.lensSeparationDistance = 0.0635000020;
  52874. result.interpupillaryDistance = 0.0640000030;
  52875. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  52876. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  52877. result.postProcessScaleFactor = 1.714605507808412;
  52878. result.lensCenterOffset = 0.151976421;
  52879. return result;
  52880. };
  52881. return VRCameraMetrics;
  52882. })();
  52883. BABYLON.VRCameraMetrics = VRCameraMetrics;
  52884. })(BABYLON || (BABYLON = {}));
  52885. var BABYLON;
  52886. (function (BABYLON) {
  52887. var WebVRFreeCamera = (function (_super) {
  52888. __extends(WebVRFreeCamera, _super);
  52889. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  52890. var _this = this;
  52891. if (compensateDistortion === void 0) { compensateDistortion = false; }
  52892. if (webVROptions === void 0) { webVROptions = {}; }
  52893. _super.call(this, name, position, scene);
  52894. this.webVROptions = webVROptions;
  52895. this._vrDevice = null;
  52896. this._cacheState = null;
  52897. this._vrEnabled = false;
  52898. //enable VR
  52899. this.getEngine().initWebVR();
  52900. if (!this.getEngine().vrDisplaysPromise) {
  52901. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  52902. }
  52903. else {
  52904. //TODO get the metrics updated using the device's eye parameters!
  52905. //TODO also check that the device has the right capabilities!
  52906. this.getEngine().vrDisplaysPromise.then(function (devices) {
  52907. if (devices.length > 0) {
  52908. _this._vrEnabled = true;
  52909. if (_this.webVROptions.displayName) {
  52910. var found = devices.some(function (device) {
  52911. if (device.displayName === _this.webVROptions.displayName) {
  52912. _this._vrDevice = device;
  52913. return true;
  52914. }
  52915. else {
  52916. return false;
  52917. }
  52918. });
  52919. if (!found) {
  52920. _this._vrDevice = devices[0];
  52921. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  52922. }
  52923. }
  52924. else {
  52925. //choose the first one
  52926. _this._vrDevice = devices[0];
  52927. }
  52928. //reset the rig parameters.
  52929. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice });
  52930. }
  52931. else {
  52932. BABYLON.Tools.Error("No WebVR devices found!");
  52933. }
  52934. });
  52935. }
  52936. this.rotationQuaternion = new BABYLON.Quaternion();
  52937. this._quaternionCache = new BABYLON.Quaternion();
  52938. }
  52939. WebVRFreeCamera.prototype._checkInputs = function () {
  52940. if (this._vrEnabled) {
  52941. var currentPost = this._vrDevice.getPose();
  52942. //make sure we have data
  52943. if (currentPost && currentPost.orientation) {
  52944. this._cacheState = currentPost;
  52945. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], this._cacheState.orientation[2], this._cacheState.orientation[3]);
  52946. if (this.webVROptions.trackPosition && this._cacheState.position) {
  52947. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  52948. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  52949. }
  52950. //Flip in XY plane
  52951. this.rotationQuaternion.z *= -1;
  52952. this.rotationQuaternion.w *= -1;
  52953. }
  52954. }
  52955. _super.prototype._checkInputs.call(this);
  52956. };
  52957. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  52958. _super.prototype.attachControl.call(this, element, noPreventDefault);
  52959. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  52960. if (this._vrEnabled) {
  52961. this.getEngine().enableVR(this._vrDevice);
  52962. }
  52963. };
  52964. WebVRFreeCamera.prototype.detachControl = function (element) {
  52965. _super.prototype.detachControl.call(this, element);
  52966. this._vrEnabled = false;
  52967. this.getEngine().disableVR();
  52968. };
  52969. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  52970. //Backwards comp.
  52971. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  52972. //this.getEngine().switchFullscreen(requestPointerlock);
  52973. };
  52974. WebVRFreeCamera.prototype.getTypeName = function () {
  52975. return "WebVRFreeCamera";
  52976. };
  52977. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  52978. //uses the vrDisplay's "resetPose()".
  52979. //pitch and roll won't be affected.
  52980. this._vrDevice.resetPose();
  52981. };
  52982. return WebVRFreeCamera;
  52983. })(BABYLON.FreeCamera);
  52984. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  52985. })(BABYLON || (BABYLON = {}));
  52986. var BABYLON;
  52987. (function (BABYLON) {
  52988. // Standard optimizations
  52989. var SceneOptimization = (function () {
  52990. function SceneOptimization(priority) {
  52991. if (priority === void 0) { priority = 0; }
  52992. this.priority = priority;
  52993. this.apply = function (scene) {
  52994. return true; // Return true if everything that can be done was applied
  52995. };
  52996. }
  52997. return SceneOptimization;
  52998. })();
  52999. BABYLON.SceneOptimization = SceneOptimization;
  53000. var TextureOptimization = (function (_super) {
  53001. __extends(TextureOptimization, _super);
  53002. function TextureOptimization(priority, maximumSize) {
  53003. var _this = this;
  53004. if (priority === void 0) { priority = 0; }
  53005. if (maximumSize === void 0) { maximumSize = 1024; }
  53006. _super.call(this, priority);
  53007. this.priority = priority;
  53008. this.maximumSize = maximumSize;
  53009. this.apply = function (scene) {
  53010. var allDone = true;
  53011. for (var index = 0; index < scene.textures.length; index++) {
  53012. var texture = scene.textures[index];
  53013. if (!texture.canRescale) {
  53014. continue;
  53015. }
  53016. var currentSize = texture.getSize();
  53017. var maxDimension = Math.max(currentSize.width, currentSize.height);
  53018. if (maxDimension > _this.maximumSize) {
  53019. texture.scale(0.5);
  53020. allDone = false;
  53021. }
  53022. }
  53023. return allDone;
  53024. };
  53025. }
  53026. return TextureOptimization;
  53027. })(SceneOptimization);
  53028. BABYLON.TextureOptimization = TextureOptimization;
  53029. var HardwareScalingOptimization = (function (_super) {
  53030. __extends(HardwareScalingOptimization, _super);
  53031. function HardwareScalingOptimization(priority, maximumScale) {
  53032. var _this = this;
  53033. if (priority === void 0) { priority = 0; }
  53034. if (maximumScale === void 0) { maximumScale = 2; }
  53035. _super.call(this, priority);
  53036. this.priority = priority;
  53037. this.maximumScale = maximumScale;
  53038. this._currentScale = 1;
  53039. this.apply = function (scene) {
  53040. _this._currentScale++;
  53041. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  53042. return _this._currentScale >= _this.maximumScale;
  53043. };
  53044. }
  53045. return HardwareScalingOptimization;
  53046. })(SceneOptimization);
  53047. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  53048. var ShadowsOptimization = (function (_super) {
  53049. __extends(ShadowsOptimization, _super);
  53050. function ShadowsOptimization() {
  53051. _super.apply(this, arguments);
  53052. this.apply = function (scene) {
  53053. scene.shadowsEnabled = false;
  53054. return true;
  53055. };
  53056. }
  53057. return ShadowsOptimization;
  53058. })(SceneOptimization);
  53059. BABYLON.ShadowsOptimization = ShadowsOptimization;
  53060. var PostProcessesOptimization = (function (_super) {
  53061. __extends(PostProcessesOptimization, _super);
  53062. function PostProcessesOptimization() {
  53063. _super.apply(this, arguments);
  53064. this.apply = function (scene) {
  53065. scene.postProcessesEnabled = false;
  53066. return true;
  53067. };
  53068. }
  53069. return PostProcessesOptimization;
  53070. })(SceneOptimization);
  53071. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  53072. var LensFlaresOptimization = (function (_super) {
  53073. __extends(LensFlaresOptimization, _super);
  53074. function LensFlaresOptimization() {
  53075. _super.apply(this, arguments);
  53076. this.apply = function (scene) {
  53077. scene.lensFlaresEnabled = false;
  53078. return true;
  53079. };
  53080. }
  53081. return LensFlaresOptimization;
  53082. })(SceneOptimization);
  53083. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  53084. var ParticlesOptimization = (function (_super) {
  53085. __extends(ParticlesOptimization, _super);
  53086. function ParticlesOptimization() {
  53087. _super.apply(this, arguments);
  53088. this.apply = function (scene) {
  53089. scene.particlesEnabled = false;
  53090. return true;
  53091. };
  53092. }
  53093. return ParticlesOptimization;
  53094. })(SceneOptimization);
  53095. BABYLON.ParticlesOptimization = ParticlesOptimization;
  53096. var RenderTargetsOptimization = (function (_super) {
  53097. __extends(RenderTargetsOptimization, _super);
  53098. function RenderTargetsOptimization() {
  53099. _super.apply(this, arguments);
  53100. this.apply = function (scene) {
  53101. scene.renderTargetsEnabled = false;
  53102. return true;
  53103. };
  53104. }
  53105. return RenderTargetsOptimization;
  53106. })(SceneOptimization);
  53107. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  53108. var MergeMeshesOptimization = (function (_super) {
  53109. __extends(MergeMeshesOptimization, _super);
  53110. function MergeMeshesOptimization() {
  53111. var _this = this;
  53112. _super.apply(this, arguments);
  53113. this._canBeMerged = function (abstractMesh) {
  53114. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  53115. return false;
  53116. }
  53117. var mesh = abstractMesh;
  53118. if (!mesh.isVisible || !mesh.isEnabled()) {
  53119. return false;
  53120. }
  53121. if (mesh.instances.length > 0) {
  53122. return false;
  53123. }
  53124. if (mesh.skeleton || mesh.hasLODLevels) {
  53125. return false;
  53126. }
  53127. if (mesh.parent) {
  53128. return false;
  53129. }
  53130. return true;
  53131. };
  53132. this.apply = function (scene, updateSelectionTree) {
  53133. var globalPool = scene.meshes.slice(0);
  53134. var globalLength = globalPool.length;
  53135. for (var index = 0; index < globalLength; index++) {
  53136. var currentPool = new Array();
  53137. var current = globalPool[index];
  53138. // Checks
  53139. if (!_this._canBeMerged(current)) {
  53140. continue;
  53141. }
  53142. currentPool.push(current);
  53143. // Find compatible meshes
  53144. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  53145. var otherMesh = globalPool[subIndex];
  53146. if (!_this._canBeMerged(otherMesh)) {
  53147. continue;
  53148. }
  53149. if (otherMesh.material !== current.material) {
  53150. continue;
  53151. }
  53152. if (otherMesh.checkCollisions !== current.checkCollisions) {
  53153. continue;
  53154. }
  53155. currentPool.push(otherMesh);
  53156. globalLength--;
  53157. globalPool.splice(subIndex, 1);
  53158. subIndex--;
  53159. }
  53160. if (currentPool.length < 2) {
  53161. continue;
  53162. }
  53163. // Merge meshes
  53164. BABYLON.Mesh.MergeMeshes(currentPool);
  53165. }
  53166. if (updateSelectionTree != undefined) {
  53167. if (updateSelectionTree) {
  53168. scene.createOrUpdateSelectionOctree();
  53169. }
  53170. }
  53171. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  53172. scene.createOrUpdateSelectionOctree();
  53173. }
  53174. return true;
  53175. };
  53176. }
  53177. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  53178. get: function () {
  53179. return MergeMeshesOptimization._UpdateSelectionTree;
  53180. },
  53181. set: function (value) {
  53182. MergeMeshesOptimization._UpdateSelectionTree = value;
  53183. },
  53184. enumerable: true,
  53185. configurable: true
  53186. });
  53187. MergeMeshesOptimization._UpdateSelectionTree = false;
  53188. return MergeMeshesOptimization;
  53189. })(SceneOptimization);
  53190. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  53191. // Options
  53192. var SceneOptimizerOptions = (function () {
  53193. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  53194. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  53195. if (trackerDuration === void 0) { trackerDuration = 2000; }
  53196. this.targetFrameRate = targetFrameRate;
  53197. this.trackerDuration = trackerDuration;
  53198. this.optimizations = new Array();
  53199. }
  53200. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  53201. var result = new SceneOptimizerOptions(targetFrameRate);
  53202. var priority = 0;
  53203. result.optimizations.push(new MergeMeshesOptimization(priority));
  53204. result.optimizations.push(new ShadowsOptimization(priority));
  53205. result.optimizations.push(new LensFlaresOptimization(priority));
  53206. // Next priority
  53207. priority++;
  53208. result.optimizations.push(new PostProcessesOptimization(priority));
  53209. result.optimizations.push(new ParticlesOptimization(priority));
  53210. // Next priority
  53211. priority++;
  53212. result.optimizations.push(new TextureOptimization(priority, 1024));
  53213. return result;
  53214. };
  53215. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  53216. var result = new SceneOptimizerOptions(targetFrameRate);
  53217. var priority = 0;
  53218. result.optimizations.push(new MergeMeshesOptimization(priority));
  53219. result.optimizations.push(new ShadowsOptimization(priority));
  53220. result.optimizations.push(new LensFlaresOptimization(priority));
  53221. // Next priority
  53222. priority++;
  53223. result.optimizations.push(new PostProcessesOptimization(priority));
  53224. result.optimizations.push(new ParticlesOptimization(priority));
  53225. // Next priority
  53226. priority++;
  53227. result.optimizations.push(new TextureOptimization(priority, 512));
  53228. // Next priority
  53229. priority++;
  53230. result.optimizations.push(new RenderTargetsOptimization(priority));
  53231. // Next priority
  53232. priority++;
  53233. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  53234. return result;
  53235. };
  53236. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  53237. var result = new SceneOptimizerOptions(targetFrameRate);
  53238. var priority = 0;
  53239. result.optimizations.push(new MergeMeshesOptimization(priority));
  53240. result.optimizations.push(new ShadowsOptimization(priority));
  53241. result.optimizations.push(new LensFlaresOptimization(priority));
  53242. // Next priority
  53243. priority++;
  53244. result.optimizations.push(new PostProcessesOptimization(priority));
  53245. result.optimizations.push(new ParticlesOptimization(priority));
  53246. // Next priority
  53247. priority++;
  53248. result.optimizations.push(new TextureOptimization(priority, 256));
  53249. // Next priority
  53250. priority++;
  53251. result.optimizations.push(new RenderTargetsOptimization(priority));
  53252. // Next priority
  53253. priority++;
  53254. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  53255. return result;
  53256. };
  53257. return SceneOptimizerOptions;
  53258. })();
  53259. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  53260. // Scene optimizer tool
  53261. var SceneOptimizer = (function () {
  53262. function SceneOptimizer() {
  53263. }
  53264. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  53265. // TODO: add an epsilon
  53266. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  53267. if (onSuccess) {
  53268. onSuccess();
  53269. }
  53270. return;
  53271. }
  53272. // Apply current level of optimizations
  53273. var allDone = true;
  53274. var noOptimizationApplied = true;
  53275. for (var index = 0; index < options.optimizations.length; index++) {
  53276. var optimization = options.optimizations[index];
  53277. if (optimization.priority === currentPriorityLevel) {
  53278. noOptimizationApplied = false;
  53279. allDone = allDone && optimization.apply(scene);
  53280. }
  53281. }
  53282. // If no optimization was applied, this is a failure :(
  53283. if (noOptimizationApplied) {
  53284. if (onFailure) {
  53285. onFailure();
  53286. }
  53287. return;
  53288. }
  53289. // If all optimizations were done, move to next level
  53290. if (allDone) {
  53291. currentPriorityLevel++;
  53292. }
  53293. // Let's the system running for a specific amount of time before checking FPS
  53294. scene.executeWhenReady(function () {
  53295. setTimeout(function () {
  53296. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  53297. }, options.trackerDuration);
  53298. });
  53299. };
  53300. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  53301. if (!options) {
  53302. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  53303. }
  53304. // Let's the system running for a specific amount of time before checking FPS
  53305. scene.executeWhenReady(function () {
  53306. setTimeout(function () {
  53307. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  53308. }, options.trackerDuration);
  53309. });
  53310. };
  53311. return SceneOptimizer;
  53312. })();
  53313. BABYLON.SceneOptimizer = SceneOptimizer;
  53314. })(BABYLON || (BABYLON = {}));
  53315. var BABYLON;
  53316. (function (BABYLON) {
  53317. var Internals;
  53318. (function (Internals) {
  53319. var MeshLODLevel = (function () {
  53320. function MeshLODLevel(distance, mesh) {
  53321. this.distance = distance;
  53322. this.mesh = mesh;
  53323. }
  53324. return MeshLODLevel;
  53325. })();
  53326. Internals.MeshLODLevel = MeshLODLevel;
  53327. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53328. })(BABYLON || (BABYLON = {}));
  53329. var BABYLON;
  53330. (function (BABYLON) {
  53331. var RawTexture = (function (_super) {
  53332. __extends(RawTexture, _super);
  53333. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  53334. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53335. if (invertY === void 0) { invertY = false; }
  53336. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53337. _super.call(this, null, scene, !generateMipMaps, invertY);
  53338. this.format = format;
  53339. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  53340. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53341. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53342. }
  53343. RawTexture.prototype.update = function (data) {
  53344. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  53345. };
  53346. // Statics
  53347. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53348. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53349. if (invertY === void 0) { invertY = false; }
  53350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53351. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  53352. };
  53353. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53354. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53355. if (invertY === void 0) { invertY = false; }
  53356. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53357. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  53358. };
  53359. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53360. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53361. if (invertY === void 0) { invertY = false; }
  53362. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53363. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  53364. };
  53365. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53366. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53367. if (invertY === void 0) { invertY = false; }
  53368. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53369. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  53370. };
  53371. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53372. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53373. if (invertY === void 0) { invertY = false; }
  53374. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53375. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  53376. };
  53377. return RawTexture;
  53378. })(BABYLON.Texture);
  53379. BABYLON.RawTexture = RawTexture;
  53380. })(BABYLON || (BABYLON = {}));
  53381. var BABYLON;
  53382. (function (BABYLON) {
  53383. var IndexedVector2 = (function (_super) {
  53384. __extends(IndexedVector2, _super);
  53385. function IndexedVector2(original, index) {
  53386. _super.call(this, original.x, original.y);
  53387. this.index = index;
  53388. }
  53389. return IndexedVector2;
  53390. })(BABYLON.Vector2);
  53391. var PolygonPoints = (function () {
  53392. function PolygonPoints() {
  53393. this.elements = new Array();
  53394. }
  53395. PolygonPoints.prototype.add = function (originalPoints) {
  53396. var _this = this;
  53397. var result = new Array();
  53398. originalPoints.forEach(function (point) {
  53399. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  53400. var newPoint = new IndexedVector2(point, _this.elements.length);
  53401. result.push(newPoint);
  53402. _this.elements.push(newPoint);
  53403. }
  53404. });
  53405. return result;
  53406. };
  53407. PolygonPoints.prototype.computeBounds = function () {
  53408. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53409. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53410. this.elements.forEach(function (point) {
  53411. // x
  53412. if (point.x < lmin.x) {
  53413. lmin.x = point.x;
  53414. }
  53415. else if (point.x > lmax.x) {
  53416. lmax.x = point.x;
  53417. }
  53418. // y
  53419. if (point.y < lmin.y) {
  53420. lmin.y = point.y;
  53421. }
  53422. else if (point.y > lmax.y) {
  53423. lmax.y = point.y;
  53424. }
  53425. });
  53426. return {
  53427. min: lmin,
  53428. max: lmax,
  53429. width: lmax.x - lmin.x,
  53430. height: lmax.y - lmin.y
  53431. };
  53432. };
  53433. return PolygonPoints;
  53434. })();
  53435. var Polygon = (function () {
  53436. function Polygon() {
  53437. }
  53438. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  53439. return [
  53440. new BABYLON.Vector2(xmin, ymin),
  53441. new BABYLON.Vector2(xmax, ymin),
  53442. new BABYLON.Vector2(xmax, ymax),
  53443. new BABYLON.Vector2(xmin, ymax)
  53444. ];
  53445. };
  53446. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  53447. if (cx === void 0) { cx = 0; }
  53448. if (cy === void 0) { cy = 0; }
  53449. if (numberOfSides === void 0) { numberOfSides = 32; }
  53450. var result = new Array();
  53451. var angle = 0;
  53452. var increment = (Math.PI * 2) / numberOfSides;
  53453. for (var i = 0; i < numberOfSides; i++) {
  53454. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  53455. angle -= increment;
  53456. }
  53457. return result;
  53458. };
  53459. Polygon.Parse = function (input) {
  53460. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  53461. var i, result = [];
  53462. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  53463. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  53464. }
  53465. return result;
  53466. };
  53467. Polygon.StartingAt = function (x, y) {
  53468. return BABYLON.Path2.StartingAt(x, y);
  53469. };
  53470. return Polygon;
  53471. })();
  53472. BABYLON.Polygon = Polygon;
  53473. var PolygonMeshBuilder = (function () {
  53474. function PolygonMeshBuilder(name, contours, scene) {
  53475. this._points = new PolygonPoints();
  53476. this._outlinepoints = new PolygonPoints();
  53477. this._holes = [];
  53478. this._epoints = new Array();
  53479. this._eholes = new Array();
  53480. this._name = name;
  53481. this._scene = scene;
  53482. var points;
  53483. if (contours instanceof BABYLON.Path2) {
  53484. points = contours.getPoints();
  53485. }
  53486. else {
  53487. points = contours;
  53488. }
  53489. this._addToepoint(points);
  53490. this._points.add(points);
  53491. this._outlinepoints.add(points);
  53492. }
  53493. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  53494. for (var _i = 0; _i < points.length; _i++) {
  53495. var p = points[_i];
  53496. this._epoints.push(p.x, p.y);
  53497. }
  53498. };
  53499. PolygonMeshBuilder.prototype.addHole = function (hole) {
  53500. this._points.add(hole);
  53501. var holepoints = new PolygonPoints();
  53502. holepoints.add(hole);
  53503. this._holes.push(holepoints);
  53504. this._eholes.push(this._epoints.length / 2);
  53505. this._addToepoint(hole);
  53506. return this;
  53507. };
  53508. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  53509. var _this = this;
  53510. if (updatable === void 0) { updatable = false; }
  53511. var result = new BABYLON.Mesh(this._name, this._scene);
  53512. var normals = [];
  53513. var positions = [];
  53514. var uvs = [];
  53515. var bounds = this._points.computeBounds();
  53516. this._points.elements.forEach(function (p) {
  53517. normals.push(0, 1.0, 0);
  53518. positions.push(p.x, 0, p.y);
  53519. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  53520. });
  53521. var indices = [];
  53522. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  53523. for (var i = 0; i < res.length; i++) {
  53524. indices.push(res[i]);
  53525. }
  53526. if (depth > 0) {
  53527. var positionscount = (positions.length / 3); //get the current pointcount
  53528. this._points.elements.forEach(function (p) {
  53529. normals.push(0, -1.0, 0);
  53530. positions.push(p.x, -depth, p.y);
  53531. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  53532. });
  53533. var totalCount = indices.length;
  53534. for (var i = 0; i < totalCount; i += 3) {
  53535. var i0 = indices[i + 0];
  53536. var i1 = indices[i + 1];
  53537. var i2 = indices[i + 2];
  53538. indices.push(i2 + positionscount);
  53539. indices.push(i1 + positionscount);
  53540. indices.push(i0 + positionscount);
  53541. }
  53542. //Add the sides
  53543. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  53544. this._holes.forEach(function (hole) {
  53545. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  53546. });
  53547. }
  53548. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  53549. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  53550. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  53551. result.setIndices(indices);
  53552. return result;
  53553. };
  53554. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  53555. var StartIndex = positions.length / 3;
  53556. var ulength = 0;
  53557. for (var i = 0; i < points.elements.length; i++) {
  53558. var p = points.elements[i];
  53559. var p1;
  53560. if ((i + 1) > points.elements.length - 1) {
  53561. p1 = points.elements[0];
  53562. }
  53563. else {
  53564. p1 = points.elements[i + 1];
  53565. }
  53566. positions.push(p.x, 0, p.y);
  53567. positions.push(p.x, -depth, p.y);
  53568. positions.push(p1.x, 0, p1.y);
  53569. positions.push(p1.x, -depth, p1.y);
  53570. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  53571. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  53572. var v3 = v2.subtract(v1);
  53573. var v4 = new BABYLON.Vector3(0, 1, 0);
  53574. var vn = BABYLON.Vector3.Cross(v3, v4);
  53575. vn = vn.normalize();
  53576. uvs.push(ulength / bounds.width, 0);
  53577. uvs.push(ulength / bounds.width, 1);
  53578. ulength += v3.length();
  53579. uvs.push((ulength / bounds.width), 0);
  53580. uvs.push((ulength / bounds.width), 1);
  53581. if (!flip) {
  53582. normals.push(-vn.x, -vn.y, -vn.z);
  53583. normals.push(-vn.x, -vn.y, -vn.z);
  53584. normals.push(-vn.x, -vn.y, -vn.z);
  53585. normals.push(-vn.x, -vn.y, -vn.z);
  53586. indices.push(StartIndex);
  53587. indices.push(StartIndex + 1);
  53588. indices.push(StartIndex + 2);
  53589. indices.push(StartIndex + 1);
  53590. indices.push(StartIndex + 3);
  53591. indices.push(StartIndex + 2);
  53592. }
  53593. else {
  53594. normals.push(vn.x, vn.y, vn.z);
  53595. normals.push(vn.x, vn.y, vn.z);
  53596. normals.push(vn.x, vn.y, vn.z);
  53597. normals.push(vn.x, vn.y, vn.z);
  53598. indices.push(StartIndex);
  53599. indices.push(StartIndex + 2);
  53600. indices.push(StartIndex + 1);
  53601. indices.push(StartIndex + 1);
  53602. indices.push(StartIndex + 2);
  53603. indices.push(StartIndex + 3);
  53604. }
  53605. StartIndex += 4;
  53606. }
  53607. ;
  53608. };
  53609. return PolygonMeshBuilder;
  53610. })();
  53611. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  53612. })(BABYLON || (BABYLON = {}));
  53613. var BABYLON;
  53614. (function (BABYLON) {
  53615. var Octree = (function () {
  53616. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  53617. if (maxDepth === void 0) { maxDepth = 2; }
  53618. this.maxDepth = maxDepth;
  53619. this.dynamicContent = new Array();
  53620. this._maxBlockCapacity = maxBlockCapacity || 64;
  53621. this._selectionContent = new BABYLON.SmartArray(1024);
  53622. this._creationFunc = creationFunc;
  53623. }
  53624. // Methods
  53625. Octree.prototype.update = function (worldMin, worldMax, entries) {
  53626. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  53627. };
  53628. Octree.prototype.addMesh = function (entry) {
  53629. for (var index = 0; index < this.blocks.length; index++) {
  53630. var block = this.blocks[index];
  53631. block.addEntry(entry);
  53632. }
  53633. };
  53634. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  53635. this._selectionContent.reset();
  53636. for (var index = 0; index < this.blocks.length; index++) {
  53637. var block = this.blocks[index];
  53638. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  53639. }
  53640. if (allowDuplicate) {
  53641. this._selectionContent.concat(this.dynamicContent);
  53642. }
  53643. else {
  53644. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53645. }
  53646. return this._selectionContent;
  53647. };
  53648. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  53649. this._selectionContent.reset();
  53650. for (var index = 0; index < this.blocks.length; index++) {
  53651. var block = this.blocks[index];
  53652. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  53653. }
  53654. if (allowDuplicate) {
  53655. this._selectionContent.concat(this.dynamicContent);
  53656. }
  53657. else {
  53658. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53659. }
  53660. return this._selectionContent;
  53661. };
  53662. Octree.prototype.intersectsRay = function (ray) {
  53663. this._selectionContent.reset();
  53664. for (var index = 0; index < this.blocks.length; index++) {
  53665. var block = this.blocks[index];
  53666. block.intersectsRay(ray, this._selectionContent);
  53667. }
  53668. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53669. return this._selectionContent;
  53670. };
  53671. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  53672. target.blocks = new Array();
  53673. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  53674. // Segmenting space
  53675. for (var x = 0; x < 2; x++) {
  53676. for (var y = 0; y < 2; y++) {
  53677. for (var z = 0; z < 2; z++) {
  53678. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  53679. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  53680. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  53681. block.addEntries(entries);
  53682. target.blocks.push(block);
  53683. }
  53684. }
  53685. }
  53686. };
  53687. Octree.CreationFuncForMeshes = function (entry, block) {
  53688. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  53689. block.entries.push(entry);
  53690. }
  53691. };
  53692. Octree.CreationFuncForSubMeshes = function (entry, block) {
  53693. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  53694. block.entries.push(entry);
  53695. }
  53696. };
  53697. return Octree;
  53698. })();
  53699. BABYLON.Octree = Octree;
  53700. })(BABYLON || (BABYLON = {}));
  53701. var BABYLON;
  53702. (function (BABYLON) {
  53703. var OctreeBlock = (function () {
  53704. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  53705. this.entries = new Array();
  53706. this._boundingVectors = new Array();
  53707. this._capacity = capacity;
  53708. this._depth = depth;
  53709. this._maxDepth = maxDepth;
  53710. this._creationFunc = creationFunc;
  53711. this._minPoint = minPoint;
  53712. this._maxPoint = maxPoint;
  53713. this._boundingVectors.push(minPoint.clone());
  53714. this._boundingVectors.push(maxPoint.clone());
  53715. this._boundingVectors.push(minPoint.clone());
  53716. this._boundingVectors[2].x = maxPoint.x;
  53717. this._boundingVectors.push(minPoint.clone());
  53718. this._boundingVectors[3].y = maxPoint.y;
  53719. this._boundingVectors.push(minPoint.clone());
  53720. this._boundingVectors[4].z = maxPoint.z;
  53721. this._boundingVectors.push(maxPoint.clone());
  53722. this._boundingVectors[5].z = minPoint.z;
  53723. this._boundingVectors.push(maxPoint.clone());
  53724. this._boundingVectors[6].x = minPoint.x;
  53725. this._boundingVectors.push(maxPoint.clone());
  53726. this._boundingVectors[7].y = minPoint.y;
  53727. }
  53728. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  53729. // Property
  53730. get: function () {
  53731. return this._capacity;
  53732. },
  53733. enumerable: true,
  53734. configurable: true
  53735. });
  53736. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  53737. get: function () {
  53738. return this._minPoint;
  53739. },
  53740. enumerable: true,
  53741. configurable: true
  53742. });
  53743. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  53744. get: function () {
  53745. return this._maxPoint;
  53746. },
  53747. enumerable: true,
  53748. configurable: true
  53749. });
  53750. // Methods
  53751. OctreeBlock.prototype.addEntry = function (entry) {
  53752. if (this.blocks) {
  53753. for (var index = 0; index < this.blocks.length; index++) {
  53754. var block = this.blocks[index];
  53755. block.addEntry(entry);
  53756. }
  53757. return;
  53758. }
  53759. this._creationFunc(entry, this);
  53760. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  53761. this.createInnerBlocks();
  53762. }
  53763. };
  53764. OctreeBlock.prototype.addEntries = function (entries) {
  53765. for (var index = 0; index < entries.length; index++) {
  53766. var mesh = entries[index];
  53767. this.addEntry(mesh);
  53768. }
  53769. };
  53770. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  53771. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  53772. if (this.blocks) {
  53773. for (var index = 0; index < this.blocks.length; index++) {
  53774. var block = this.blocks[index];
  53775. block.select(frustumPlanes, selection, allowDuplicate);
  53776. }
  53777. return;
  53778. }
  53779. if (allowDuplicate) {
  53780. selection.concat(this.entries);
  53781. }
  53782. else {
  53783. selection.concatWithNoDuplicate(this.entries);
  53784. }
  53785. }
  53786. };
  53787. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  53788. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  53789. if (this.blocks) {
  53790. for (var index = 0; index < this.blocks.length; index++) {
  53791. var block = this.blocks[index];
  53792. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  53793. }
  53794. return;
  53795. }
  53796. if (allowDuplicate) {
  53797. selection.concat(this.entries);
  53798. }
  53799. else {
  53800. selection.concatWithNoDuplicate(this.entries);
  53801. }
  53802. }
  53803. };
  53804. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  53805. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  53806. if (this.blocks) {
  53807. for (var index = 0; index < this.blocks.length; index++) {
  53808. var block = this.blocks[index];
  53809. block.intersectsRay(ray, selection);
  53810. }
  53811. return;
  53812. }
  53813. selection.concatWithNoDuplicate(this.entries);
  53814. }
  53815. };
  53816. OctreeBlock.prototype.createInnerBlocks = function () {
  53817. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  53818. };
  53819. return OctreeBlock;
  53820. })();
  53821. BABYLON.OctreeBlock = OctreeBlock;
  53822. })(BABYLON || (BABYLON = {}));
  53823. var BABYLON;
  53824. (function (BABYLON) {
  53825. var BlurPostProcess = (function (_super) {
  53826. __extends(BlurPostProcess, _super);
  53827. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  53828. var _this = this;
  53829. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53830. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  53831. this.direction = direction;
  53832. this.blurWidth = blurWidth;
  53833. this.onApplyObservable.add(function (effect) {
  53834. effect.setFloat2("screenSize", _this.width, _this.height);
  53835. effect.setVector2("direction", _this.direction);
  53836. effect.setFloat("blurWidth", _this.blurWidth);
  53837. });
  53838. }
  53839. return BlurPostProcess;
  53840. })(BABYLON.PostProcess);
  53841. BABYLON.BlurPostProcess = BlurPostProcess;
  53842. })(BABYLON || (BABYLON = {}));
  53843. var BABYLON;
  53844. (function (BABYLON) {
  53845. var RefractionPostProcess = (function (_super) {
  53846. __extends(RefractionPostProcess, _super);
  53847. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  53848. var _this = this;
  53849. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  53850. this.color = color;
  53851. this.depth = depth;
  53852. this.colorLevel = colorLevel;
  53853. this.onActivateObservable.add(function (cam) {
  53854. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  53855. });
  53856. this.onApplyObservable.add(function (effect) {
  53857. effect.setColor3("baseColor", _this.color);
  53858. effect.setFloat("depth", _this.depth);
  53859. effect.setFloat("colorLevel", _this.colorLevel);
  53860. effect.setTexture("refractionSampler", _this._refRexture);
  53861. });
  53862. }
  53863. // Methods
  53864. RefractionPostProcess.prototype.dispose = function (camera) {
  53865. if (this._refRexture) {
  53866. this._refRexture.dispose();
  53867. }
  53868. _super.prototype.dispose.call(this, camera);
  53869. };
  53870. return RefractionPostProcess;
  53871. })(BABYLON.PostProcess);
  53872. BABYLON.RefractionPostProcess = RefractionPostProcess;
  53873. })(BABYLON || (BABYLON = {}));
  53874. var BABYLON;
  53875. (function (BABYLON) {
  53876. var BlackAndWhitePostProcess = (function (_super) {
  53877. __extends(BlackAndWhitePostProcess, _super);
  53878. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  53879. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  53880. }
  53881. return BlackAndWhitePostProcess;
  53882. })(BABYLON.PostProcess);
  53883. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  53884. })(BABYLON || (BABYLON = {}));
  53885. var BABYLON;
  53886. (function (BABYLON) {
  53887. var ConvolutionPostProcess = (function (_super) {
  53888. __extends(ConvolutionPostProcess, _super);
  53889. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  53890. var _this = this;
  53891. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  53892. this.kernel = kernel;
  53893. this.onApply = function (effect) {
  53894. effect.setFloat2("screenSize", _this.width, _this.height);
  53895. effect.setArray("kernel", _this.kernel);
  53896. };
  53897. }
  53898. // Statics
  53899. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  53900. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  53901. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  53902. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  53903. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  53904. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  53905. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  53906. return ConvolutionPostProcess;
  53907. })(BABYLON.PostProcess);
  53908. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  53909. })(BABYLON || (BABYLON = {}));
  53910. var BABYLON;
  53911. (function (BABYLON) {
  53912. var FilterPostProcess = (function (_super) {
  53913. __extends(FilterPostProcess, _super);
  53914. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  53915. var _this = this;
  53916. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  53917. this.kernelMatrix = kernelMatrix;
  53918. this.onApply = function (effect) {
  53919. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  53920. };
  53921. }
  53922. return FilterPostProcess;
  53923. })(BABYLON.PostProcess);
  53924. BABYLON.FilterPostProcess = FilterPostProcess;
  53925. })(BABYLON || (BABYLON = {}));
  53926. var BABYLON;
  53927. (function (BABYLON) {
  53928. var FxaaPostProcess = (function (_super) {
  53929. __extends(FxaaPostProcess, _super);
  53930. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  53931. var _this = this;
  53932. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  53933. this.onSizeChangedObservable.add(function () {
  53934. _this.texelWidth = 1.0 / _this.width;
  53935. _this.texelHeight = 1.0 / _this.height;
  53936. });
  53937. this.onApplyObservable.add(function (effect) {
  53938. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  53939. });
  53940. }
  53941. return FxaaPostProcess;
  53942. })(BABYLON.PostProcess);
  53943. BABYLON.FxaaPostProcess = FxaaPostProcess;
  53944. })(BABYLON || (BABYLON = {}));
  53945. var BABYLON;
  53946. (function (BABYLON) {
  53947. var StereoscopicInterlacePostProcess = (function (_super) {
  53948. __extends(StereoscopicInterlacePostProcess, _super);
  53949. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  53950. var _this = this;
  53951. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  53952. this._passedProcess = rigCameras[0]._rigPostProcess;
  53953. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  53954. this.onSizeChangedObservable.add(function () {
  53955. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  53956. });
  53957. this.onApplyObservable.add(function (effect) {
  53958. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  53959. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  53960. });
  53961. }
  53962. return StereoscopicInterlacePostProcess;
  53963. })(BABYLON.PostProcess);
  53964. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  53965. })(BABYLON || (BABYLON = {}));
  53966. var BABYLON;
  53967. (function (BABYLON) {
  53968. var LensFlare = (function () {
  53969. function LensFlare(size, position, color, imgUrl, system) {
  53970. this.size = size;
  53971. this.position = position;
  53972. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  53973. this.dispose = function () {
  53974. if (this.texture) {
  53975. this.texture.dispose();
  53976. }
  53977. // Remove from scene
  53978. var index = this._system.lensFlares.indexOf(this);
  53979. this._system.lensFlares.splice(index, 1);
  53980. };
  53981. this.color = color || new BABYLON.Color3(1, 1, 1);
  53982. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  53983. this._system = system;
  53984. system.lensFlares.push(this);
  53985. }
  53986. return LensFlare;
  53987. })();
  53988. BABYLON.LensFlare = LensFlare;
  53989. })(BABYLON || (BABYLON = {}));
  53990. var BABYLON;
  53991. (function (BABYLON) {
  53992. var LensFlareSystem = (function () {
  53993. function LensFlareSystem(name, emitter, scene) {
  53994. this.name = name;
  53995. this.lensFlares = new Array();
  53996. this.borderLimit = 300;
  53997. this.layerMask = 0x0FFFFFFF;
  53998. this._vertexBuffers = {};
  53999. this._isEnabled = true;
  54000. this._scene = scene;
  54001. this._emitter = emitter;
  54002. this.id = name;
  54003. scene.lensFlareSystems.push(this);
  54004. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  54005. var engine = scene.getEngine();
  54006. // VBO
  54007. var vertices = [];
  54008. vertices.push(1, 1);
  54009. vertices.push(-1, 1);
  54010. vertices.push(-1, -1);
  54011. vertices.push(1, -1);
  54012. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54013. // Indices
  54014. var indices = [];
  54015. indices.push(0);
  54016. indices.push(1);
  54017. indices.push(2);
  54018. indices.push(0);
  54019. indices.push(2);
  54020. indices.push(3);
  54021. this._indexBuffer = engine.createIndexBuffer(indices);
  54022. // Effects
  54023. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  54024. }
  54025. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  54026. get: function () {
  54027. return this._isEnabled;
  54028. },
  54029. set: function (value) {
  54030. this._isEnabled = value;
  54031. },
  54032. enumerable: true,
  54033. configurable: true
  54034. });
  54035. LensFlareSystem.prototype.getScene = function () {
  54036. return this._scene;
  54037. };
  54038. LensFlareSystem.prototype.getEmitter = function () {
  54039. return this._emitter;
  54040. };
  54041. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  54042. this._emitter = newEmitter;
  54043. };
  54044. LensFlareSystem.prototype.getEmitterPosition = function () {
  54045. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  54046. };
  54047. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  54048. var position = this.getEmitterPosition();
  54049. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  54050. this._positionX = position.x;
  54051. this._positionY = position.y;
  54052. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  54053. if (position.z > 0) {
  54054. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  54055. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  54056. return true;
  54057. }
  54058. }
  54059. return false;
  54060. };
  54061. LensFlareSystem.prototype._isVisible = function () {
  54062. if (!this._isEnabled) {
  54063. return false;
  54064. }
  54065. var emitterPosition = this.getEmitterPosition();
  54066. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  54067. var distance = direction.length();
  54068. direction.normalize();
  54069. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  54070. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  54071. return !pickInfo.hit || pickInfo.distance > distance;
  54072. };
  54073. LensFlareSystem.prototype.render = function () {
  54074. if (!this._effect.isReady())
  54075. return false;
  54076. var engine = this._scene.getEngine();
  54077. var viewport = this._scene.activeCamera.viewport;
  54078. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  54079. // Position
  54080. if (!this.computeEffectivePosition(globalViewport)) {
  54081. return false;
  54082. }
  54083. // Visibility
  54084. if (!this._isVisible()) {
  54085. return false;
  54086. }
  54087. // Intensity
  54088. var awayX;
  54089. var awayY;
  54090. if (this._positionX < this.borderLimit + globalViewport.x) {
  54091. awayX = this.borderLimit + globalViewport.x - this._positionX;
  54092. }
  54093. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  54094. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  54095. }
  54096. else {
  54097. awayX = 0;
  54098. }
  54099. if (this._positionY < this.borderLimit + globalViewport.y) {
  54100. awayY = this.borderLimit + globalViewport.y - this._positionY;
  54101. }
  54102. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  54103. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  54104. }
  54105. else {
  54106. awayY = 0;
  54107. }
  54108. var away = (awayX > awayY) ? awayX : awayY;
  54109. if (away > this.borderLimit) {
  54110. away = this.borderLimit;
  54111. }
  54112. var intensity = 1.0 - (away / this.borderLimit);
  54113. if (intensity < 0) {
  54114. return false;
  54115. }
  54116. if (intensity > 1.0) {
  54117. intensity = 1.0;
  54118. }
  54119. // Position
  54120. var centerX = globalViewport.x + globalViewport.width / 2;
  54121. var centerY = globalViewport.y + globalViewport.height / 2;
  54122. var distX = centerX - this._positionX;
  54123. var distY = centerY - this._positionY;
  54124. // Effects
  54125. engine.enableEffect(this._effect);
  54126. engine.setState(false);
  54127. engine.setDepthBuffer(false);
  54128. // VBOs
  54129. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54130. // Flares
  54131. for (var index = 0; index < this.lensFlares.length; index++) {
  54132. var flare = this.lensFlares[index];
  54133. engine.setAlphaMode(flare.alphaMode);
  54134. var x = centerX - (distX * flare.position);
  54135. var y = centerY - (distY * flare.position);
  54136. var cw = flare.size;
  54137. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  54138. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  54139. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  54140. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  54141. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  54142. // Texture
  54143. this._effect.setTexture("textureSampler", flare.texture);
  54144. // Color
  54145. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  54146. // Draw order
  54147. engine.draw(true, 0, 6);
  54148. }
  54149. engine.setDepthBuffer(true);
  54150. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54151. return true;
  54152. };
  54153. LensFlareSystem.prototype.dispose = function () {
  54154. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54155. if (vertexBuffer) {
  54156. vertexBuffer.dispose();
  54157. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54158. }
  54159. if (this._indexBuffer) {
  54160. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54161. this._indexBuffer = null;
  54162. }
  54163. while (this.lensFlares.length) {
  54164. this.lensFlares[0].dispose();
  54165. }
  54166. // Remove from scene
  54167. var index = this._scene.lensFlareSystems.indexOf(this);
  54168. this._scene.lensFlareSystems.splice(index, 1);
  54169. };
  54170. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  54171. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  54172. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  54173. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  54174. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  54175. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  54176. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  54177. var parsedFlare = parsedLensFlareSystem.flares[index];
  54178. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  54179. }
  54180. return lensFlareSystem;
  54181. };
  54182. LensFlareSystem.prototype.serialize = function () {
  54183. var serializationObject = {};
  54184. serializationObject.id = this.id;
  54185. serializationObject.name = this.name;
  54186. serializationObject.emitterId = this.getEmitter().id;
  54187. serializationObject.borderLimit = this.borderLimit;
  54188. serializationObject.flares = [];
  54189. for (var index = 0; index < this.lensFlares.length; index++) {
  54190. var flare = this.lensFlares[index];
  54191. serializationObject.flares.push({
  54192. size: flare.size,
  54193. position: flare.position,
  54194. color: flare.color.asArray(),
  54195. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  54196. });
  54197. }
  54198. return serializationObject;
  54199. };
  54200. return LensFlareSystem;
  54201. })();
  54202. BABYLON.LensFlareSystem = LensFlareSystem;
  54203. })(BABYLON || (BABYLON = {}));
  54204. var BABYLON;
  54205. (function (BABYLON) {
  54206. // We're mainly based on the logic defined into the FreeCamera code
  54207. var DeviceOrientationCamera = (function (_super) {
  54208. __extends(DeviceOrientationCamera, _super);
  54209. function DeviceOrientationCamera(name, position, scene) {
  54210. _super.call(this, name, position, scene);
  54211. this.inputs.addDeviceOrientation();
  54212. }
  54213. DeviceOrientationCamera.prototype.getTypeName = function () {
  54214. return "DeviceOrientationCamera";
  54215. };
  54216. DeviceOrientationCamera.prototype._checkInputs = function () {
  54217. _super.prototype._checkInputs.call(this);
  54218. if (this._initialQuaternion) {
  54219. this._quaternionCache.copyFrom(this.rotationQuaternion);
  54220. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  54221. }
  54222. };
  54223. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  54224. var _this = this;
  54225. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  54226. //can only work if this camera has a rotation quaternion already.
  54227. if (!this.rotationQuaternion)
  54228. return;
  54229. if (!this._initialQuaternion) {
  54230. this._initialQuaternion = new BABYLON.Quaternion();
  54231. }
  54232. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  54233. ['x', 'y', 'z'].forEach(function (axisName) {
  54234. if (!axis[axisName]) {
  54235. _this._initialQuaternion[axisName] = 0;
  54236. }
  54237. else {
  54238. _this._initialQuaternion[axisName] *= -1;
  54239. }
  54240. });
  54241. this._initialQuaternion.normalize();
  54242. };
  54243. return DeviceOrientationCamera;
  54244. })(BABYLON.FreeCamera);
  54245. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  54246. })(BABYLON || (BABYLON = {}));
  54247. var BABYLON;
  54248. (function (BABYLON) {
  54249. var VRDeviceOrientationFreeCamera = (function (_super) {
  54250. __extends(VRDeviceOrientationFreeCamera, _super);
  54251. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  54252. if (compensateDistortion === void 0) { compensateDistortion = true; }
  54253. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  54254. _super.call(this, name, position, scene);
  54255. vrCameraMetrics.compensateDistortion = compensateDistortion;
  54256. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  54257. }
  54258. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  54259. return "VRDeviceOrientationFreeCamera";
  54260. };
  54261. return VRDeviceOrientationFreeCamera;
  54262. })(BABYLON.DeviceOrientationCamera);
  54263. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  54264. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  54265. __extends(VRDeviceOrientationArcRotateCamera, _super);
  54266. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  54267. if (compensateDistortion === void 0) { compensateDistortion = true; }
  54268. _super.call(this, name, alpha, beta, radius, target, scene);
  54269. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  54270. metrics.compensateDistortion = compensateDistortion;
  54271. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  54272. this.inputs.addVRDeviceOrientation();
  54273. }
  54274. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  54275. return "VRDeviceOrientationArcRotateCamera";
  54276. };
  54277. return VRDeviceOrientationArcRotateCamera;
  54278. })(BABYLON.ArcRotateCamera);
  54279. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  54280. })(BABYLON || (BABYLON = {}));
  54281. var BABYLON;
  54282. (function (BABYLON) {
  54283. // We're mainly based on the logic defined into the FreeCamera code
  54284. var UniversalCamera = (function (_super) {
  54285. __extends(UniversalCamera, _super);
  54286. //-- end properties for backward compatibility for inputs
  54287. function UniversalCamera(name, position, scene) {
  54288. _super.call(this, name, position, scene);
  54289. this.inputs.addGamepad();
  54290. }
  54291. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  54292. //-- Begin properties for backward compatibility for inputs
  54293. get: function () {
  54294. var gamepad = this.inputs.attached["gamepad"];
  54295. if (gamepad)
  54296. return gamepad.gamepadAngularSensibility;
  54297. },
  54298. set: function (value) {
  54299. var gamepad = this.inputs.attached["gamepad"];
  54300. if (gamepad)
  54301. gamepad.gamepadAngularSensibility = value;
  54302. },
  54303. enumerable: true,
  54304. configurable: true
  54305. });
  54306. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  54307. get: function () {
  54308. var gamepad = this.inputs.attached["gamepad"];
  54309. if (gamepad)
  54310. return gamepad.gamepadMoveSensibility;
  54311. },
  54312. set: function (value) {
  54313. var gamepad = this.inputs.attached["gamepad"];
  54314. if (gamepad)
  54315. gamepad.gamepadMoveSensibility = value;
  54316. },
  54317. enumerable: true,
  54318. configurable: true
  54319. });
  54320. UniversalCamera.prototype.getTypeName = function () {
  54321. return "UniversalCamera";
  54322. };
  54323. return UniversalCamera;
  54324. })(BABYLON.TouchCamera);
  54325. BABYLON.UniversalCamera = UniversalCamera;
  54326. })(BABYLON || (BABYLON = {}));
  54327. var BABYLON;
  54328. (function (BABYLON) {
  54329. var Gamepads = (function () {
  54330. function Gamepads(ongamedpadconnected) {
  54331. var _this = this;
  54332. this.babylonGamepads = [];
  54333. this.oneGamepadConnected = false;
  54334. this.isMonitoring = false;
  54335. this.gamepadEventSupported = 'GamepadEvent' in window;
  54336. this.gamepadSupportAvailable = (navigator.getGamepads ||
  54337. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  54338. this._callbackGamepadConnected = ongamedpadconnected;
  54339. if (this.gamepadSupportAvailable) {
  54340. // Checking if the gamepad connected event is supported (like in Firefox)
  54341. if (this.gamepadEventSupported) {
  54342. this._onGamepadConnectedEvent = function (evt) {
  54343. _this._onGamepadConnected(evt);
  54344. };
  54345. this._onGamepadDisonnectedEvent = function (evt) {
  54346. _this._onGamepadDisconnected(evt);
  54347. };
  54348. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54349. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  54350. }
  54351. else {
  54352. this._startMonitoringGamepads();
  54353. }
  54354. }
  54355. }
  54356. Gamepads.prototype.dispose = function () {
  54357. if (Gamepads.gamepadDOMInfo) {
  54358. document.body.removeChild(Gamepads.gamepadDOMInfo);
  54359. }
  54360. if (this._onGamepadConnectedEvent) {
  54361. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54362. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  54363. this._onGamepadConnectedEvent = null;
  54364. this._onGamepadDisonnectedEvent = null;
  54365. }
  54366. };
  54367. Gamepads.prototype._onGamepadConnected = function (evt) {
  54368. var newGamepad = this._addNewGamepad(evt.gamepad);
  54369. if (this._callbackGamepadConnected)
  54370. this._callbackGamepadConnected(newGamepad);
  54371. this._startMonitoringGamepads();
  54372. };
  54373. Gamepads.prototype._addNewGamepad = function (gamepad) {
  54374. if (!this.oneGamepadConnected) {
  54375. this.oneGamepadConnected = true;
  54376. if (Gamepads.gamepadDOMInfo) {
  54377. document.body.removeChild(Gamepads.gamepadDOMInfo);
  54378. Gamepads.gamepadDOMInfo = null;
  54379. }
  54380. }
  54381. var newGamepad;
  54382. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54383. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  54384. }
  54385. else {
  54386. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  54387. }
  54388. this.babylonGamepads.push(newGamepad);
  54389. return newGamepad;
  54390. };
  54391. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  54392. // Remove the gamepad from the list of gamepads to monitor.
  54393. for (var i in this.babylonGamepads) {
  54394. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  54395. this.babylonGamepads.splice(+i, 1);
  54396. break;
  54397. }
  54398. }
  54399. // If no gamepads are left, stop the polling loop.
  54400. if (this.babylonGamepads.length == 0) {
  54401. this._stopMonitoringGamepads();
  54402. }
  54403. };
  54404. Gamepads.prototype._startMonitoringGamepads = function () {
  54405. if (!this.isMonitoring) {
  54406. this.isMonitoring = true;
  54407. this._checkGamepadsStatus();
  54408. }
  54409. };
  54410. Gamepads.prototype._stopMonitoringGamepads = function () {
  54411. this.isMonitoring = false;
  54412. };
  54413. Gamepads.prototype._checkGamepadsStatus = function () {
  54414. var _this = this;
  54415. // updating gamepad objects
  54416. this._updateGamepadObjects();
  54417. for (var i in this.babylonGamepads) {
  54418. this.babylonGamepads[i].update();
  54419. }
  54420. if (this.isMonitoring) {
  54421. if (window.requestAnimationFrame) {
  54422. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54423. }
  54424. else if (window.mozRequestAnimationFrame) {
  54425. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54426. }
  54427. else if (window.webkitRequestAnimationFrame) {
  54428. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54429. }
  54430. }
  54431. };
  54432. // This function is called only on Chrome, which does not yet support
  54433. // connection/disconnection events, but requires you to monitor
  54434. // an array for changes.
  54435. Gamepads.prototype._updateGamepadObjects = function () {
  54436. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54437. for (var i = 0; i < gamepads.length; i++) {
  54438. if (gamepads[i]) {
  54439. if (!(gamepads[i].index in this.babylonGamepads)) {
  54440. var newGamepad = this._addNewGamepad(gamepads[i]);
  54441. if (this._callbackGamepadConnected) {
  54442. this._callbackGamepadConnected(newGamepad);
  54443. }
  54444. }
  54445. else {
  54446. this.babylonGamepads[i].browserGamepad = gamepads[i];
  54447. }
  54448. }
  54449. }
  54450. };
  54451. return Gamepads;
  54452. })();
  54453. BABYLON.Gamepads = Gamepads;
  54454. var StickValues = (function () {
  54455. function StickValues(x, y) {
  54456. this.x = x;
  54457. this.y = y;
  54458. }
  54459. return StickValues;
  54460. })();
  54461. BABYLON.StickValues = StickValues;
  54462. var Gamepad = (function () {
  54463. function Gamepad(id, index, browserGamepad) {
  54464. this.id = id;
  54465. this.index = index;
  54466. this.browserGamepad = browserGamepad;
  54467. if (this.browserGamepad.axes.length >= 2) {
  54468. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  54469. }
  54470. if (this.browserGamepad.axes.length >= 4) {
  54471. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  54472. }
  54473. }
  54474. Gamepad.prototype.onleftstickchanged = function (callback) {
  54475. this._onleftstickchanged = callback;
  54476. };
  54477. Gamepad.prototype.onrightstickchanged = function (callback) {
  54478. this._onrightstickchanged = callback;
  54479. };
  54480. Object.defineProperty(Gamepad.prototype, "leftStick", {
  54481. get: function () {
  54482. return this._leftStick;
  54483. },
  54484. set: function (newValues) {
  54485. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  54486. this._onleftstickchanged(newValues);
  54487. }
  54488. this._leftStick = newValues;
  54489. },
  54490. enumerable: true,
  54491. configurable: true
  54492. });
  54493. Object.defineProperty(Gamepad.prototype, "rightStick", {
  54494. get: function () {
  54495. return this._rightStick;
  54496. },
  54497. set: function (newValues) {
  54498. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  54499. this._onrightstickchanged(newValues);
  54500. }
  54501. this._rightStick = newValues;
  54502. },
  54503. enumerable: true,
  54504. configurable: true
  54505. });
  54506. Gamepad.prototype.update = function () {
  54507. if (this._leftStick) {
  54508. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  54509. }
  54510. if (this._rightStick) {
  54511. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  54512. }
  54513. };
  54514. return Gamepad;
  54515. })();
  54516. BABYLON.Gamepad = Gamepad;
  54517. var GenericPad = (function (_super) {
  54518. __extends(GenericPad, _super);
  54519. function GenericPad(id, index, gamepad) {
  54520. _super.call(this, id, index, gamepad);
  54521. this.id = id;
  54522. this.index = index;
  54523. this.gamepad = gamepad;
  54524. this._buttons = new Array(gamepad.buttons.length);
  54525. }
  54526. GenericPad.prototype.onbuttondown = function (callback) {
  54527. this._onbuttondown = callback;
  54528. };
  54529. GenericPad.prototype.onbuttonup = function (callback) {
  54530. this._onbuttonup = callback;
  54531. };
  54532. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  54533. if (newValue !== currentValue) {
  54534. if (this._onbuttondown && newValue === 1) {
  54535. this._onbuttondown(buttonIndex);
  54536. }
  54537. if (this._onbuttonup && newValue === 0) {
  54538. this._onbuttonup(buttonIndex);
  54539. }
  54540. }
  54541. return newValue;
  54542. };
  54543. GenericPad.prototype.update = function () {
  54544. _super.prototype.update.call(this);
  54545. for (var index = 0; index < this._buttons.length; index++) {
  54546. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  54547. }
  54548. };
  54549. return GenericPad;
  54550. })(Gamepad);
  54551. BABYLON.GenericPad = GenericPad;
  54552. (function (Xbox360Button) {
  54553. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  54554. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  54555. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  54556. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  54557. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  54558. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  54559. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  54560. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  54561. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  54562. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  54563. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  54564. var Xbox360Button = BABYLON.Xbox360Button;
  54565. (function (Xbox360Dpad) {
  54566. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  54567. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  54568. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  54569. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  54570. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  54571. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  54572. var Xbox360Pad = (function (_super) {
  54573. __extends(Xbox360Pad, _super);
  54574. function Xbox360Pad() {
  54575. _super.apply(this, arguments);
  54576. this._leftTrigger = 0;
  54577. this._rightTrigger = 0;
  54578. this._buttonA = 0;
  54579. this._buttonB = 0;
  54580. this._buttonX = 0;
  54581. this._buttonY = 0;
  54582. this._buttonBack = 0;
  54583. this._buttonStart = 0;
  54584. this._buttonLB = 0;
  54585. this._buttonRB = 0;
  54586. this._buttonLeftStick = 0;
  54587. this._buttonRightStick = 0;
  54588. this._dPadUp = 0;
  54589. this._dPadDown = 0;
  54590. this._dPadLeft = 0;
  54591. this._dPadRight = 0;
  54592. }
  54593. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  54594. this._onlefttriggerchanged = callback;
  54595. };
  54596. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  54597. this._onrighttriggerchanged = callback;
  54598. };
  54599. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  54600. get: function () {
  54601. return this._leftTrigger;
  54602. },
  54603. set: function (newValue) {
  54604. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  54605. this._onlefttriggerchanged(newValue);
  54606. }
  54607. this._leftTrigger = newValue;
  54608. },
  54609. enumerable: true,
  54610. configurable: true
  54611. });
  54612. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  54613. get: function () {
  54614. return this._rightTrigger;
  54615. },
  54616. set: function (newValue) {
  54617. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  54618. this._onrighttriggerchanged(newValue);
  54619. }
  54620. this._rightTrigger = newValue;
  54621. },
  54622. enumerable: true,
  54623. configurable: true
  54624. });
  54625. Xbox360Pad.prototype.onbuttondown = function (callback) {
  54626. this._onbuttondown = callback;
  54627. };
  54628. Xbox360Pad.prototype.onbuttonup = function (callback) {
  54629. this._onbuttonup = callback;
  54630. };
  54631. Xbox360Pad.prototype.ondpaddown = function (callback) {
  54632. this._ondpaddown = callback;
  54633. };
  54634. Xbox360Pad.prototype.ondpadup = function (callback) {
  54635. this._ondpadup = callback;
  54636. };
  54637. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  54638. if (newValue !== currentValue) {
  54639. if (this._onbuttondown && newValue === 1) {
  54640. this._onbuttondown(buttonType);
  54641. }
  54642. if (this._onbuttonup && newValue === 0) {
  54643. this._onbuttonup(buttonType);
  54644. }
  54645. }
  54646. return newValue;
  54647. };
  54648. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  54649. if (newValue !== currentValue) {
  54650. if (this._ondpaddown && newValue === 1) {
  54651. this._ondpaddown(buttonType);
  54652. }
  54653. if (this._ondpadup && newValue === 0) {
  54654. this._ondpadup(buttonType);
  54655. }
  54656. }
  54657. return newValue;
  54658. };
  54659. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  54660. get: function () {
  54661. return this._buttonA;
  54662. },
  54663. set: function (value) {
  54664. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  54665. },
  54666. enumerable: true,
  54667. configurable: true
  54668. });
  54669. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  54670. get: function () {
  54671. return this._buttonB;
  54672. },
  54673. set: function (value) {
  54674. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  54675. },
  54676. enumerable: true,
  54677. configurable: true
  54678. });
  54679. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  54680. get: function () {
  54681. return this._buttonX;
  54682. },
  54683. set: function (value) {
  54684. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  54685. },
  54686. enumerable: true,
  54687. configurable: true
  54688. });
  54689. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  54690. get: function () {
  54691. return this._buttonY;
  54692. },
  54693. set: function (value) {
  54694. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  54695. },
  54696. enumerable: true,
  54697. configurable: true
  54698. });
  54699. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  54700. get: function () {
  54701. return this._buttonStart;
  54702. },
  54703. set: function (value) {
  54704. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  54705. },
  54706. enumerable: true,
  54707. configurable: true
  54708. });
  54709. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  54710. get: function () {
  54711. return this._buttonBack;
  54712. },
  54713. set: function (value) {
  54714. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  54715. },
  54716. enumerable: true,
  54717. configurable: true
  54718. });
  54719. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  54720. get: function () {
  54721. return this._buttonLB;
  54722. },
  54723. set: function (value) {
  54724. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  54725. },
  54726. enumerable: true,
  54727. configurable: true
  54728. });
  54729. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  54730. get: function () {
  54731. return this._buttonRB;
  54732. },
  54733. set: function (value) {
  54734. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  54735. },
  54736. enumerable: true,
  54737. configurable: true
  54738. });
  54739. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  54740. get: function () {
  54741. return this._buttonLeftStick;
  54742. },
  54743. set: function (value) {
  54744. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  54745. },
  54746. enumerable: true,
  54747. configurable: true
  54748. });
  54749. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  54750. get: function () {
  54751. return this._buttonRightStick;
  54752. },
  54753. set: function (value) {
  54754. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  54755. },
  54756. enumerable: true,
  54757. configurable: true
  54758. });
  54759. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  54760. get: function () {
  54761. return this._dPadUp;
  54762. },
  54763. set: function (value) {
  54764. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  54765. },
  54766. enumerable: true,
  54767. configurable: true
  54768. });
  54769. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  54770. get: function () {
  54771. return this._dPadDown;
  54772. },
  54773. set: function (value) {
  54774. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  54775. },
  54776. enumerable: true,
  54777. configurable: true
  54778. });
  54779. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  54780. get: function () {
  54781. return this._dPadLeft;
  54782. },
  54783. set: function (value) {
  54784. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  54785. },
  54786. enumerable: true,
  54787. configurable: true
  54788. });
  54789. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  54790. get: function () {
  54791. return this._dPadRight;
  54792. },
  54793. set: function (value) {
  54794. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  54795. },
  54796. enumerable: true,
  54797. configurable: true
  54798. });
  54799. Xbox360Pad.prototype.update = function () {
  54800. _super.prototype.update.call(this);
  54801. this.buttonA = this.browserGamepad.buttons[0].value;
  54802. this.buttonB = this.browserGamepad.buttons[1].value;
  54803. this.buttonX = this.browserGamepad.buttons[2].value;
  54804. this.buttonY = this.browserGamepad.buttons[3].value;
  54805. this.buttonLB = this.browserGamepad.buttons[4].value;
  54806. this.buttonRB = this.browserGamepad.buttons[5].value;
  54807. this.leftTrigger = this.browserGamepad.buttons[6].value;
  54808. this.rightTrigger = this.browserGamepad.buttons[7].value;
  54809. this.buttonBack = this.browserGamepad.buttons[8].value;
  54810. this.buttonStart = this.browserGamepad.buttons[9].value;
  54811. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  54812. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  54813. this.dPadUp = this.browserGamepad.buttons[12].value;
  54814. this.dPadDown = this.browserGamepad.buttons[13].value;
  54815. this.dPadLeft = this.browserGamepad.buttons[14].value;
  54816. this.dPadRight = this.browserGamepad.buttons[15].value;
  54817. };
  54818. return Xbox360Pad;
  54819. })(Gamepad);
  54820. BABYLON.Xbox360Pad = Xbox360Pad;
  54821. })(BABYLON || (BABYLON = {}));
  54822. var BABYLON;
  54823. (function (BABYLON) {
  54824. // We're mainly based on the logic defined into the FreeCamera code
  54825. var GamepadCamera = (function (_super) {
  54826. __extends(GamepadCamera, _super);
  54827. //-- end properties for backward compatibility for inputs
  54828. function GamepadCamera(name, position, scene) {
  54829. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  54830. _super.call(this, name, position, scene);
  54831. }
  54832. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  54833. //-- Begin properties for backward compatibility for inputs
  54834. get: function () {
  54835. var gamepad = this.inputs.attached["gamepad"];
  54836. if (gamepad)
  54837. return gamepad.gamepadAngularSensibility;
  54838. },
  54839. set: function (value) {
  54840. var gamepad = this.inputs.attached["gamepad"];
  54841. if (gamepad)
  54842. gamepad.gamepadAngularSensibility = value;
  54843. },
  54844. enumerable: true,
  54845. configurable: true
  54846. });
  54847. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  54848. get: function () {
  54849. var gamepad = this.inputs.attached["gamepad"];
  54850. if (gamepad)
  54851. return gamepad.gamepadMoveSensibility;
  54852. },
  54853. set: function (value) {
  54854. var gamepad = this.inputs.attached["gamepad"];
  54855. if (gamepad)
  54856. gamepad.gamepadMoveSensibility = value;
  54857. },
  54858. enumerable: true,
  54859. configurable: true
  54860. });
  54861. GamepadCamera.prototype.getTypeName = function () {
  54862. return "GamepadCamera";
  54863. };
  54864. return GamepadCamera;
  54865. })(BABYLON.UniversalCamera);
  54866. BABYLON.GamepadCamera = GamepadCamera;
  54867. })(BABYLON || (BABYLON = {}));
  54868. var BABYLON;
  54869. (function (BABYLON) {
  54870. var Analyser = (function () {
  54871. function Analyser(scene) {
  54872. this.SMOOTHING = 0.75;
  54873. this.FFT_SIZE = 512;
  54874. this.BARGRAPHAMPLITUDE = 256;
  54875. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  54876. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  54877. this._scene = scene;
  54878. this._audioEngine = BABYLON.Engine.audioEngine;
  54879. if (this._audioEngine.canUseWebAudio) {
  54880. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  54881. this._webAudioAnalyser.minDecibels = -140;
  54882. this._webAudioAnalyser.maxDecibels = 0;
  54883. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54884. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54885. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  54886. }
  54887. }
  54888. Analyser.prototype.getFrequencyBinCount = function () {
  54889. if (this._audioEngine.canUseWebAudio) {
  54890. return this._webAudioAnalyser.frequencyBinCount;
  54891. }
  54892. else {
  54893. return 0;
  54894. }
  54895. };
  54896. Analyser.prototype.getByteFrequencyData = function () {
  54897. if (this._audioEngine.canUseWebAudio) {
  54898. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54899. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54900. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  54901. }
  54902. return this._byteFreqs;
  54903. };
  54904. Analyser.prototype.getByteTimeDomainData = function () {
  54905. if (this._audioEngine.canUseWebAudio) {
  54906. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54907. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54908. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  54909. }
  54910. return this._byteTime;
  54911. };
  54912. Analyser.prototype.getFloatFrequencyData = function () {
  54913. if (this._audioEngine.canUseWebAudio) {
  54914. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54915. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54916. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  54917. }
  54918. return this._floatFreqs;
  54919. };
  54920. Analyser.prototype.drawDebugCanvas = function () {
  54921. var _this = this;
  54922. if (this._audioEngine.canUseWebAudio) {
  54923. if (!this._debugCanvas) {
  54924. this._debugCanvas = document.createElement("canvas");
  54925. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  54926. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  54927. this._debugCanvas.style.position = "absolute";
  54928. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  54929. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  54930. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  54931. document.body.appendChild(this._debugCanvas);
  54932. this._registerFunc = function () {
  54933. _this.drawDebugCanvas();
  54934. };
  54935. this._scene.registerBeforeRender(this._registerFunc);
  54936. }
  54937. if (this._registerFunc) {
  54938. var workingArray = this.getByteFrequencyData();
  54939. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  54940. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  54941. // Draw the frequency domain chart.
  54942. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  54943. var value = workingArray[i];
  54944. var percent = value / this.BARGRAPHAMPLITUDE;
  54945. var height = this.DEBUGCANVASSIZE.height * percent;
  54946. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  54947. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  54948. var hue = i / this.getFrequencyBinCount() * 360;
  54949. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  54950. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  54951. }
  54952. }
  54953. }
  54954. };
  54955. Analyser.prototype.stopDebugCanvas = function () {
  54956. if (this._debugCanvas) {
  54957. this._scene.unregisterBeforeRender(this._registerFunc);
  54958. this._registerFunc = null;
  54959. document.body.removeChild(this._debugCanvas);
  54960. this._debugCanvas = null;
  54961. this._debugCanvasContext = null;
  54962. }
  54963. };
  54964. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  54965. if (this._audioEngine.canUseWebAudio) {
  54966. inputAudioNode.connect(this._webAudioAnalyser);
  54967. this._webAudioAnalyser.connect(outputAudioNode);
  54968. }
  54969. };
  54970. Analyser.prototype.dispose = function () {
  54971. if (this._audioEngine.canUseWebAudio) {
  54972. this._webAudioAnalyser.disconnect();
  54973. }
  54974. };
  54975. return Analyser;
  54976. })();
  54977. BABYLON.Analyser = Analyser;
  54978. })(BABYLON || (BABYLON = {}));
  54979. var BABYLON;
  54980. (function (BABYLON) {
  54981. var DepthRenderer = (function () {
  54982. function DepthRenderer(scene, type) {
  54983. var _this = this;
  54984. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  54985. this._viewMatrix = BABYLON.Matrix.Zero();
  54986. this._projectionMatrix = BABYLON.Matrix.Zero();
  54987. this._transformMatrix = BABYLON.Matrix.Zero();
  54988. this._worldViewProjection = BABYLON.Matrix.Zero();
  54989. this._scene = scene;
  54990. var engine = scene.getEngine();
  54991. // Render target
  54992. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  54993. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54994. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54995. this._depthMap.refreshRate = 1;
  54996. this._depthMap.renderParticles = false;
  54997. this._depthMap.renderList = null;
  54998. // set default depth value to 1.0 (far away)
  54999. this._depthMap.onClearObservable.add(function (engine) {
  55000. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55001. });
  55002. // Custom render function
  55003. var renderSubMesh = function (subMesh) {
  55004. var mesh = subMesh.getRenderingMesh();
  55005. var scene = _this._scene;
  55006. var engine = scene.getEngine();
  55007. // Culling
  55008. engine.setState(subMesh.getMaterial().backFaceCulling);
  55009. // Managing instances
  55010. var batch = mesh._getInstancesRenderList(subMesh._id);
  55011. if (batch.mustReturn) {
  55012. return;
  55013. }
  55014. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  55015. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55016. engine.enableEffect(_this._effect);
  55017. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  55018. var material = subMesh.getMaterial();
  55019. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  55020. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  55021. // Alpha test
  55022. if (material && material.needAlphaTesting()) {
  55023. var alphaTexture = material.getAlphaTestTexture();
  55024. _this._effect.setTexture("diffuseSampler", alphaTexture);
  55025. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55026. }
  55027. // Bones
  55028. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55029. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55030. }
  55031. // Draw
  55032. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55033. }
  55034. };
  55035. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  55036. var index;
  55037. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55038. renderSubMesh(opaqueSubMeshes.data[index]);
  55039. }
  55040. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55041. renderSubMesh(alphaTestSubMeshes.data[index]);
  55042. }
  55043. };
  55044. }
  55045. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  55046. var material = subMesh.getMaterial();
  55047. if (material.disableDepthWrite) {
  55048. return false;
  55049. }
  55050. var defines = [];
  55051. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55052. var mesh = subMesh.getMesh();
  55053. var scene = mesh.getScene();
  55054. // Alpha test
  55055. if (material && material.needAlphaTesting()) {
  55056. defines.push("#define ALPHATEST");
  55057. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55058. attribs.push(BABYLON.VertexBuffer.UVKind);
  55059. defines.push("#define UV1");
  55060. }
  55061. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55062. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55063. defines.push("#define UV2");
  55064. }
  55065. }
  55066. // Bones
  55067. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55068. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55069. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55070. if (mesh.numBoneInfluencers > 4) {
  55071. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55072. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55073. }
  55074. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55075. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55076. }
  55077. else {
  55078. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55079. }
  55080. // Instances
  55081. if (useInstances) {
  55082. defines.push("#define INSTANCES");
  55083. attribs.push("world0");
  55084. attribs.push("world1");
  55085. attribs.push("world2");
  55086. attribs.push("world3");
  55087. }
  55088. // Get correct effect
  55089. var join = defines.join("\n");
  55090. if (this._cachedDefines !== join) {
  55091. this._cachedDefines = join;
  55092. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  55093. }
  55094. return this._effect.isReady();
  55095. };
  55096. DepthRenderer.prototype.getDepthMap = function () {
  55097. return this._depthMap;
  55098. };
  55099. // Methods
  55100. DepthRenderer.prototype.dispose = function () {
  55101. this._depthMap.dispose();
  55102. };
  55103. return DepthRenderer;
  55104. })();
  55105. BABYLON.DepthRenderer = DepthRenderer;
  55106. })(BABYLON || (BABYLON = {}));
  55107. var BABYLON;
  55108. (function (BABYLON) {
  55109. var SSAORenderingPipeline = (function (_super) {
  55110. __extends(SSAORenderingPipeline, _super);
  55111. /**
  55112. * @constructor
  55113. * @param {string} name - The rendering pipeline name
  55114. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55115. * @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 }
  55116. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55117. */
  55118. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  55119. var _this = this;
  55120. _super.call(this, scene.getEngine(), name);
  55121. // Members
  55122. /**
  55123. * The PassPostProcess id in the pipeline that contains the original scene color
  55124. * @type {string}
  55125. */
  55126. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  55127. /**
  55128. * The SSAO PostProcess id in the pipeline
  55129. * @type {string}
  55130. */
  55131. this.SSAORenderEffect = "SSAORenderEffect";
  55132. /**
  55133. * The horizontal blur PostProcess id in the pipeline
  55134. * @type {string}
  55135. */
  55136. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  55137. /**
  55138. * The vertical blur PostProcess id in the pipeline
  55139. * @type {string}
  55140. */
  55141. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  55142. /**
  55143. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  55144. * @type {string}
  55145. */
  55146. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  55147. /**
  55148. * The output strength of the SSAO post-process. Default value is 1.0.
  55149. * @type {number}
  55150. */
  55151. this.totalStrength = 1.0;
  55152. /**
  55153. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  55154. * @type {number}
  55155. */
  55156. this.radius = 0.0001;
  55157. /**
  55158. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  55159. * Must not be equal to fallOff and superior to fallOff.
  55160. * Default value is 0.975
  55161. * @type {number}
  55162. */
  55163. this.area = 0.0075;
  55164. /**
  55165. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  55166. * Must not be equal to area and inferior to area.
  55167. * Default value is 0.0
  55168. * @type {number}
  55169. */
  55170. this.fallOff = 0.000001;
  55171. /**
  55172. * The base color of the SSAO post-process
  55173. * The final result is "base + ssao" between [0, 1]
  55174. * @type {number}
  55175. */
  55176. this.base = 0.5;
  55177. this._firstUpdate = true;
  55178. this._scene = scene;
  55179. // Set up assets
  55180. this._createRandomTexture();
  55181. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55182. var ssaoRatio = ratio.ssaoRatio || ratio;
  55183. var combineRatio = ratio.combineRatio || ratio;
  55184. this._ratio = {
  55185. ssaoRatio: ssaoRatio,
  55186. combineRatio: combineRatio
  55187. };
  55188. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55189. this._createSSAOPostProcess(ssaoRatio);
  55190. this._createBlurPostProcess(ssaoRatio);
  55191. this._createSSAOCombinePostProcess(combineRatio);
  55192. // Set up pipeline
  55193. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  55194. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  55195. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  55196. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  55197. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  55198. // Finish
  55199. scene.postProcessRenderPipelineManager.addPipeline(this);
  55200. if (cameras)
  55201. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55202. }
  55203. // Public Methods
  55204. /**
  55205. * Returns the horizontal blur PostProcess
  55206. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  55207. */
  55208. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  55209. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  55210. return null;
  55211. };
  55212. /**
  55213. * Returns the vertical blur PostProcess
  55214. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  55215. */
  55216. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  55217. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  55218. return null;
  55219. };
  55220. /**
  55221. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  55222. */
  55223. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55224. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55225. for (var i = 0; i < this._scene.cameras.length; i++) {
  55226. var camera = this._scene.cameras[i];
  55227. this._originalColorPostProcess.dispose(camera);
  55228. this._ssaoPostProcess.dispose(camera);
  55229. this._blurHPostProcess.dispose(camera);
  55230. this._blurVPostProcess.dispose(camera);
  55231. this._ssaoCombinePostProcess.dispose(camera);
  55232. }
  55233. this._randomTexture.dispose();
  55234. if (disableDepthRender)
  55235. this._scene.disableDepthRenderer();
  55236. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55237. };
  55238. // Private Methods
  55239. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  55240. var _this = this;
  55241. /*
  55242. var samplerOffsets = [
  55243. -8.0, -6.0, -4.0, -2.0,
  55244. 0.0,
  55245. 2.0, 4.0, 6.0, 8.0
  55246. ];
  55247. */
  55248. var samples = 16;
  55249. var samplerOffsets = [];
  55250. for (var i = -8; i < 8; i++) {
  55251. samplerOffsets.push(i * 2);
  55252. }
  55253. 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");
  55254. this._blurHPostProcess.onApply = function (effect) {
  55255. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  55256. effect.setTexture("depthSampler", _this._depthTexture);
  55257. if (_this._firstUpdate) {
  55258. effect.setArray("samplerOffsets", samplerOffsets);
  55259. }
  55260. };
  55261. 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");
  55262. this._blurVPostProcess.onApply = function (effect) {
  55263. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  55264. effect.setTexture("depthSampler", _this._depthTexture);
  55265. if (_this._firstUpdate) {
  55266. effect.setArray("samplerOffsets", samplerOffsets);
  55267. _this._firstUpdate = false;
  55268. }
  55269. };
  55270. };
  55271. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  55272. var _this = this;
  55273. var numSamples = 16;
  55274. var sampleSphere = [
  55275. 0.5381, 0.1856, -0.4319,
  55276. 0.1379, 0.2486, 0.4430,
  55277. 0.3371, 0.5679, -0.0057,
  55278. -0.6999, -0.0451, -0.0019,
  55279. 0.0689, -0.1598, -0.8547,
  55280. 0.0560, 0.0069, -0.1843,
  55281. -0.0146, 0.1402, 0.0762,
  55282. 0.0100, -0.1924, -0.0344,
  55283. -0.3577, -0.5301, -0.4358,
  55284. -0.3169, 0.1063, 0.0158,
  55285. 0.0103, -0.5869, 0.0046,
  55286. -0.0897, -0.4940, 0.3287,
  55287. 0.7119, -0.0154, -0.0918,
  55288. -0.0533, 0.0596, -0.5411,
  55289. 0.0352, -0.0631, 0.5460,
  55290. -0.4776, 0.2847, -0.0271
  55291. ];
  55292. var samplesFactor = 1.0 / numSamples;
  55293. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  55294. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  55295. "area", "fallOff", "base", "range", "viewport"
  55296. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  55297. var viewport = new BABYLON.Vector2(0, 0);
  55298. this._ssaoPostProcess.onApply = function (effect) {
  55299. if (_this._firstUpdate) {
  55300. effect.setArray3("sampleSphere", sampleSphere);
  55301. effect.setFloat("samplesFactor", samplesFactor);
  55302. effect.setFloat("randTextureTiles", 4.0);
  55303. }
  55304. effect.setFloat("totalStrength", _this.totalStrength);
  55305. effect.setFloat("radius", _this.radius);
  55306. effect.setFloat("area", _this.area);
  55307. effect.setFloat("fallOff", _this.fallOff);
  55308. effect.setFloat("base", _this.base);
  55309. effect.setTexture("textureSampler", _this._depthTexture);
  55310. effect.setTexture("randomSampler", _this._randomTexture);
  55311. };
  55312. };
  55313. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  55314. var _this = this;
  55315. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55316. this._ssaoCombinePostProcess.onApply = function (effect) {
  55317. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  55318. };
  55319. };
  55320. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  55321. var size = 512;
  55322. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55323. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55324. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55325. var context = this._randomTexture.getContext();
  55326. var rand = function (min, max) {
  55327. return Math.random() * (max - min) + min;
  55328. };
  55329. var randVector = BABYLON.Vector3.Zero();
  55330. for (var x = 0; x < size; x++) {
  55331. for (var y = 0; y < size; y++) {
  55332. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  55333. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  55334. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  55335. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  55336. context.fillRect(x, y, 1, 1);
  55337. }
  55338. }
  55339. this._randomTexture.update(false);
  55340. };
  55341. __decorate([
  55342. BABYLON.serialize()
  55343. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  55344. __decorate([
  55345. BABYLON.serialize()
  55346. ], SSAORenderingPipeline.prototype, "radius", void 0);
  55347. __decorate([
  55348. BABYLON.serialize()
  55349. ], SSAORenderingPipeline.prototype, "area", void 0);
  55350. __decorate([
  55351. BABYLON.serialize()
  55352. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  55353. __decorate([
  55354. BABYLON.serialize()
  55355. ], SSAORenderingPipeline.prototype, "base", void 0);
  55356. __decorate([
  55357. BABYLON.serialize()
  55358. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  55359. return SSAORenderingPipeline;
  55360. })(BABYLON.PostProcessRenderPipeline);
  55361. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  55362. })(BABYLON || (BABYLON = {}));
  55363. var BABYLON;
  55364. (function (BABYLON) {
  55365. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  55366. var VolumetricLightScatteringPostProcess = (function (_super) {
  55367. __extends(VolumetricLightScatteringPostProcess, _super);
  55368. /**
  55369. * @constructor
  55370. * @param {string} name - The post-process name
  55371. * @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)
  55372. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  55373. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  55374. * @param {number} samples - The post-process quality, default 100
  55375. * @param {number} samplingMode - The post-process filtering mode
  55376. * @param {BABYLON.Engine} engine - The babylon engine
  55377. * @param {boolean} reusable - If the post-process is reusable
  55378. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  55379. */
  55380. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  55381. var _this = this;
  55382. if (samples === void 0) { samples = 100; }
  55383. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55384. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  55385. this._screenCoordinates = BABYLON.Vector2.Zero();
  55386. /**
  55387. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  55388. * @type {Vector3}
  55389. */
  55390. this.customMeshPosition = BABYLON.Vector3.Zero();
  55391. /**
  55392. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  55393. * @type {boolean}
  55394. */
  55395. this.useCustomMeshPosition = false;
  55396. /**
  55397. * If the post-process should inverse the light scattering direction
  55398. * @type {boolean}
  55399. */
  55400. this.invert = true;
  55401. /**
  55402. * Array containing the excluded meshes not rendered in the internal pass
  55403. */
  55404. this.excludedMeshes = new Array();
  55405. /**
  55406. * Controls the overall intensity of the post-process
  55407. * @type {number}
  55408. */
  55409. this.exposure = 0.3;
  55410. /**
  55411. * Dissipates each sample's contribution in range [0, 1]
  55412. * @type {number}
  55413. */
  55414. this.decay = 0.96815;
  55415. /**
  55416. * Controls the overall intensity of each sample
  55417. * @type {number}
  55418. */
  55419. this.weight = 0.58767;
  55420. /**
  55421. * Controls the density of each sample
  55422. * @type {number}
  55423. */
  55424. this.density = 0.926;
  55425. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  55426. var engine = scene.getEngine();
  55427. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  55428. // Configure mesh
  55429. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  55430. // Configure
  55431. this._createPass(scene, ratio.passRatio || ratio);
  55432. this.onActivate = function (camera) {
  55433. if (!_this.isSupported) {
  55434. _this.dispose(camera);
  55435. }
  55436. _this.onActivate = null;
  55437. };
  55438. this.onApplyObservable.add(function (effect) {
  55439. _this._updateMeshScreenCoordinates(scene);
  55440. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  55441. effect.setFloat("exposure", _this.exposure);
  55442. effect.setFloat("decay", _this.decay);
  55443. effect.setFloat("weight", _this.weight);
  55444. effect.setFloat("density", _this.density);
  55445. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  55446. });
  55447. }
  55448. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  55449. get: function () {
  55450. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55451. return false;
  55452. },
  55453. set: function (useDiffuseColor) {
  55454. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55455. },
  55456. enumerable: true,
  55457. configurable: true
  55458. });
  55459. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  55460. var mesh = subMesh.getMesh();
  55461. // Render this.mesh as default
  55462. if (mesh === this.mesh) {
  55463. return mesh.material.isReady(mesh);
  55464. }
  55465. var defines = [];
  55466. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55467. var material = subMesh.getMaterial();
  55468. var needUV = false;
  55469. // Alpha test
  55470. if (material) {
  55471. if (material.needAlphaTesting()) {
  55472. defines.push("#define ALPHATEST");
  55473. }
  55474. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55475. attribs.push(BABYLON.VertexBuffer.UVKind);
  55476. defines.push("#define UV1");
  55477. }
  55478. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55479. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55480. defines.push("#define UV2");
  55481. }
  55482. }
  55483. // Bones
  55484. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55485. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55486. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55487. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55488. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55489. }
  55490. else {
  55491. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55492. }
  55493. // Instances
  55494. if (useInstances) {
  55495. defines.push("#define INSTANCES");
  55496. attribs.push("world0");
  55497. attribs.push("world1");
  55498. attribs.push("world2");
  55499. attribs.push("world3");
  55500. }
  55501. // Get correct effect
  55502. var join = defines.join("\n");
  55503. if (this._cachedDefines !== join) {
  55504. this._cachedDefines = join;
  55505. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  55506. }
  55507. return this._volumetricLightScatteringPass.isReady();
  55508. };
  55509. /**
  55510. * Sets the new light position for light scattering effect
  55511. * @param {BABYLON.Vector3} The new custom light position
  55512. */
  55513. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  55514. this.customMeshPosition = position;
  55515. };
  55516. /**
  55517. * Returns the light position for light scattering effect
  55518. * @return {BABYLON.Vector3} The custom light position
  55519. */
  55520. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  55521. return this.customMeshPosition;
  55522. };
  55523. /**
  55524. * Disposes the internal assets and detaches the post-process from the camera
  55525. */
  55526. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  55527. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  55528. if (rttIndex !== -1) {
  55529. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  55530. }
  55531. this._volumetricLightScatteringRTT.dispose();
  55532. _super.prototype.dispose.call(this, camera);
  55533. };
  55534. /**
  55535. * Returns the render target texture used by the post-process
  55536. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  55537. */
  55538. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  55539. return this._volumetricLightScatteringRTT;
  55540. };
  55541. // Private methods
  55542. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  55543. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  55544. return true;
  55545. }
  55546. return false;
  55547. };
  55548. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  55549. var _this = this;
  55550. var engine = scene.getEngine();
  55551. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55552. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55553. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55554. this._volumetricLightScatteringRTT.renderList = null;
  55555. this._volumetricLightScatteringRTT.renderParticles = false;
  55556. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  55557. // Custom render function for submeshes
  55558. var renderSubMesh = function (subMesh) {
  55559. var mesh = subMesh.getRenderingMesh();
  55560. if (_this._meshExcluded(mesh)) {
  55561. return;
  55562. }
  55563. var scene = mesh.getScene();
  55564. var engine = scene.getEngine();
  55565. // Culling
  55566. engine.setState(subMesh.getMaterial().backFaceCulling);
  55567. // Managing instances
  55568. var batch = mesh._getInstancesRenderList(subMesh._id);
  55569. if (batch.mustReturn) {
  55570. return;
  55571. }
  55572. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  55573. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55574. var effect = _this._volumetricLightScatteringPass;
  55575. if (mesh === _this.mesh) {
  55576. effect = subMesh.getMaterial().getEffect();
  55577. }
  55578. engine.enableEffect(effect);
  55579. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  55580. if (mesh === _this.mesh) {
  55581. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  55582. }
  55583. else {
  55584. var material = subMesh.getMaterial();
  55585. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  55586. // Alpha test
  55587. if (material && material.needAlphaTesting()) {
  55588. var alphaTexture = material.getAlphaTestTexture();
  55589. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  55590. if (alphaTexture) {
  55591. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55592. }
  55593. }
  55594. // Bones
  55595. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55596. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55597. }
  55598. }
  55599. // Draw
  55600. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  55601. }
  55602. };
  55603. // Render target texture callbacks
  55604. var savedSceneClearColor;
  55605. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  55606. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  55607. savedSceneClearColor = scene.clearColor;
  55608. scene.clearColor = sceneClearColor;
  55609. });
  55610. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  55611. scene.clearColor = savedSceneClearColor;
  55612. });
  55613. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  55614. var engine = scene.getEngine();
  55615. var index;
  55616. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55617. renderSubMesh(opaqueSubMeshes.data[index]);
  55618. }
  55619. engine.setAlphaTesting(true);
  55620. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55621. renderSubMesh(alphaTestSubMeshes.data[index]);
  55622. }
  55623. engine.setAlphaTesting(false);
  55624. if (transparentSubMeshes.length) {
  55625. // Sort sub meshes
  55626. for (index = 0; index < transparentSubMeshes.length; index++) {
  55627. var submesh = transparentSubMeshes.data[index];
  55628. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  55629. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  55630. }
  55631. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  55632. sortedArray.sort(function (a, b) {
  55633. // Alpha index first
  55634. if (a._alphaIndex > b._alphaIndex) {
  55635. return 1;
  55636. }
  55637. if (a._alphaIndex < b._alphaIndex) {
  55638. return -1;
  55639. }
  55640. // Then distance to camera
  55641. if (a._distanceToCamera < b._distanceToCamera) {
  55642. return 1;
  55643. }
  55644. if (a._distanceToCamera > b._distanceToCamera) {
  55645. return -1;
  55646. }
  55647. return 0;
  55648. });
  55649. // Render sub meshes
  55650. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55651. for (index = 0; index < sortedArray.length; index++) {
  55652. renderSubMesh(sortedArray[index]);
  55653. }
  55654. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55655. }
  55656. };
  55657. };
  55658. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  55659. var transform = scene.getTransformMatrix();
  55660. var meshPosition;
  55661. if (this.useCustomMeshPosition) {
  55662. meshPosition = this.customMeshPosition;
  55663. }
  55664. else if (this.attachedNode) {
  55665. meshPosition = this.attachedNode.position;
  55666. }
  55667. else {
  55668. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  55669. }
  55670. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  55671. this._screenCoordinates.x = pos.x / this._viewPort.width;
  55672. this._screenCoordinates.y = pos.y / this._viewPort.height;
  55673. if (this.invert)
  55674. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  55675. };
  55676. // Static methods
  55677. /**
  55678. * Creates a default mesh for the Volumeric Light Scattering post-process
  55679. * @param {string} The mesh name
  55680. * @param {BABYLON.Scene} The scene where to create the mesh
  55681. * @return {BABYLON.Mesh} the default mesh
  55682. */
  55683. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  55684. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  55685. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55686. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  55687. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  55688. mesh.material = material;
  55689. return mesh;
  55690. };
  55691. __decorate([
  55692. BABYLON.serializeAsVector3()
  55693. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  55694. __decorate([
  55695. BABYLON.serialize()
  55696. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  55697. __decorate([
  55698. BABYLON.serialize()
  55699. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  55700. __decorate([
  55701. BABYLON.serializeAsMeshReference()
  55702. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  55703. __decorate([
  55704. BABYLON.serialize()
  55705. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  55706. __decorate([
  55707. BABYLON.serialize()
  55708. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  55709. __decorate([
  55710. BABYLON.serialize()
  55711. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  55712. __decorate([
  55713. BABYLON.serialize()
  55714. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  55715. __decorate([
  55716. BABYLON.serialize()
  55717. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  55718. return VolumetricLightScatteringPostProcess;
  55719. })(BABYLON.PostProcess);
  55720. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  55721. })(BABYLON || (BABYLON = {}));
  55722. // BABYLON.JS Chromatic Aberration GLSL Shader
  55723. // Author: Olivier Guyot
  55724. // Separates very slightly R, G and B colors on the edges of the screen
  55725. // Inspired by Francois Tarlier & Martins Upitis
  55726. var BABYLON;
  55727. (function (BABYLON) {
  55728. var LensRenderingPipeline = (function (_super) {
  55729. __extends(LensRenderingPipeline, _super);
  55730. /**
  55731. * @constructor
  55732. *
  55733. * Effect parameters are as follow:
  55734. * {
  55735. * chromatic_aberration: number; // from 0 to x (1 for realism)
  55736. * edge_blur: number; // from 0 to x (1 for realism)
  55737. * distortion: number; // from 0 to x (1 for realism)
  55738. * grain_amount: number; // from 0 to 1
  55739. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  55740. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  55741. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  55742. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  55743. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  55744. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  55745. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  55746. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  55747. * }
  55748. * Note: if an effect parameter is unset, effect is disabled
  55749. *
  55750. * @param {string} name - The rendering pipeline name
  55751. * @param {object} parameters - An object containing all parameters (see above)
  55752. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55753. * @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)
  55754. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55755. */
  55756. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  55757. var _this = this;
  55758. if (ratio === void 0) { ratio = 1.0; }
  55759. _super.call(this, scene.getEngine(), name);
  55760. // Lens effects can be of the following:
  55761. // - chromatic aberration (slight shift of RGB colors)
  55762. // - blur on the edge of the lens
  55763. // - lens distortion
  55764. // - depth-of-field blur & highlights enhancing
  55765. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  55766. // - grain effect (noise or custom texture)
  55767. // Two additional texture samplers are needed:
  55768. // - depth map (for depth-of-field)
  55769. // - grain texture
  55770. /**
  55771. * The chromatic aberration PostProcess id in the pipeline
  55772. * @type {string}
  55773. */
  55774. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  55775. /**
  55776. * The highlights enhancing PostProcess id in the pipeline
  55777. * @type {string}
  55778. */
  55779. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  55780. /**
  55781. * The depth-of-field PostProcess id in the pipeline
  55782. * @type {string}
  55783. */
  55784. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  55785. this._scene = scene;
  55786. // Fetch texture samplers
  55787. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55788. if (parameters.grain_texture) {
  55789. this._grainTexture = parameters.grain_texture;
  55790. }
  55791. else {
  55792. this._createGrainTexture();
  55793. }
  55794. // save parameters
  55795. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  55796. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  55797. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  55798. this._distortion = parameters.distortion ? parameters.distortion : 0;
  55799. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  55800. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  55801. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  55802. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  55803. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  55804. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  55805. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  55806. // Create effects
  55807. this._createChromaticAberrationPostProcess(ratio);
  55808. this._createHighlightsPostProcess(ratio);
  55809. this._createDepthOfFieldPostProcess(ratio / 4);
  55810. // Set up pipeline
  55811. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  55812. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  55813. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  55814. if (this._highlightsGain === -1) {
  55815. this._disableEffect(this.HighlightsEnhancingEffect, null);
  55816. }
  55817. // Finish
  55818. scene.postProcessRenderPipelineManager.addPipeline(this);
  55819. if (cameras) {
  55820. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55821. }
  55822. }
  55823. // public methods (self explanatory)
  55824. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  55825. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  55826. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  55827. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  55828. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  55829. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  55830. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  55831. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  55832. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  55833. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  55834. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  55835. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  55836. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  55837. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  55838. };
  55839. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  55840. this._highlightsPostProcess.updateEffect();
  55841. };
  55842. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  55843. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  55844. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  55845. this._highlightsGain = amount;
  55846. };
  55847. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  55848. if (this._highlightsGain === -1) {
  55849. this._highlightsGain = 1.0;
  55850. }
  55851. this._highlightsThreshold = amount;
  55852. };
  55853. LensRenderingPipeline.prototype.disableHighlights = function () {
  55854. this._highlightsGain = -1;
  55855. };
  55856. /**
  55857. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  55858. */
  55859. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55860. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55861. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55862. this._chromaticAberrationPostProcess = undefined;
  55863. this._highlightsPostProcess = undefined;
  55864. this._depthOfFieldPostProcess = undefined;
  55865. this._grainTexture.dispose();
  55866. if (disableDepthRender)
  55867. this._scene.disableDepthRenderer();
  55868. };
  55869. // colors shifting and distortion
  55870. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  55871. var _this = this;
  55872. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  55873. [], // samplers
  55874. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55875. this._chromaticAberrationPostProcess.onApply = function (effect) {
  55876. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  55877. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55878. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55879. };
  55880. };
  55881. // highlights enhancing
  55882. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  55883. var _this = this;
  55884. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  55885. [], // samplers
  55886. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  55887. this._highlightsPostProcess.onApply = function (effect) {
  55888. effect.setFloat('gain', _this._highlightsGain);
  55889. effect.setFloat('threshold', _this._highlightsThreshold);
  55890. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  55891. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55892. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55893. };
  55894. };
  55895. // colors shifting and distortion
  55896. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  55897. var _this = this;
  55898. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  55899. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  55900. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  55901. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55902. this._depthOfFieldPostProcess.onApply = function (effect) {
  55903. effect.setTexture("depthSampler", _this._depthTexture);
  55904. effect.setTexture("grainSampler", _this._grainTexture);
  55905. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  55906. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  55907. effect.setFloat('grain_amount', _this._grainAmount);
  55908. effect.setBool('blur_noise', _this._blurNoise);
  55909. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55910. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55911. effect.setFloat('distortion', _this._distortion);
  55912. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  55913. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  55914. effect.setFloat('aperture', _this._dofAperture);
  55915. effect.setFloat('darken', _this._dofDarken);
  55916. effect.setFloat('edge_blur', _this._edgeBlur);
  55917. effect.setBool('highlights', (_this._highlightsGain !== -1));
  55918. effect.setFloat('near', _this._scene.activeCamera.minZ);
  55919. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  55920. };
  55921. };
  55922. // creates a black and white random noise texture, 512x512
  55923. LensRenderingPipeline.prototype._createGrainTexture = function () {
  55924. var size = 512;
  55925. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55926. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55927. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55928. var context = this._grainTexture.getContext();
  55929. var rand = function (min, max) {
  55930. return Math.random() * (max - min) + min;
  55931. };
  55932. var value;
  55933. for (var x = 0; x < size; x++) {
  55934. for (var y = 0; y < size; y++) {
  55935. value = Math.floor(rand(0.42, 0.58) * 255);
  55936. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  55937. context.fillRect(x, y, 1, 1);
  55938. }
  55939. }
  55940. this._grainTexture.update(false);
  55941. };
  55942. return LensRenderingPipeline;
  55943. })(BABYLON.PostProcessRenderPipeline);
  55944. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  55945. })(BABYLON || (BABYLON = {}));
  55946. //
  55947. // This post-process allows the modification of rendered colors by using
  55948. // a 'look-up table' (LUT). This effect is also called Color Grading.
  55949. //
  55950. // The object needs to be provided an url to a texture containing the color
  55951. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  55952. // Use an image editing software to tweak the LUT to match your needs.
  55953. //
  55954. // For an example of a color LUT, see here:
  55955. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  55956. // For explanations on color grading, see here:
  55957. // http://udn.epicgames.com/Three/ColorGrading.html
  55958. //
  55959. var BABYLON;
  55960. (function (BABYLON) {
  55961. var ColorCorrectionPostProcess = (function (_super) {
  55962. __extends(ColorCorrectionPostProcess, _super);
  55963. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  55964. var _this = this;
  55965. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  55966. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55967. this._colorTableTexture.anisotropicFilteringLevel = 1;
  55968. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55969. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55970. this.onApply = function (effect) {
  55971. effect.setTexture("colorTable", _this._colorTableTexture);
  55972. };
  55973. }
  55974. return ColorCorrectionPostProcess;
  55975. })(BABYLON.PostProcess);
  55976. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  55977. })(BABYLON || (BABYLON = {}));
  55978. var BABYLON;
  55979. (function (BABYLON) {
  55980. var AnaglyphFreeCamera = (function (_super) {
  55981. __extends(AnaglyphFreeCamera, _super);
  55982. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  55983. _super.call(this, name, position, scene);
  55984. this.interaxialDistance = interaxialDistance;
  55985. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55986. }
  55987. AnaglyphFreeCamera.prototype.getTypeName = function () {
  55988. return "AnaglyphFreeCamera";
  55989. };
  55990. return AnaglyphFreeCamera;
  55991. })(BABYLON.FreeCamera);
  55992. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  55993. var AnaglyphArcRotateCamera = (function (_super) {
  55994. __extends(AnaglyphArcRotateCamera, _super);
  55995. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  55996. _super.call(this, name, alpha, beta, radius, target, scene);
  55997. this.interaxialDistance = interaxialDistance;
  55998. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55999. }
  56000. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  56001. return "AnaglyphArcRotateCamera";
  56002. };
  56003. return AnaglyphArcRotateCamera;
  56004. })(BABYLON.ArcRotateCamera);
  56005. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  56006. var AnaglyphGamepadCamera = (function (_super) {
  56007. __extends(AnaglyphGamepadCamera, _super);
  56008. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  56009. _super.call(this, name, position, scene);
  56010. this.interaxialDistance = interaxialDistance;
  56011. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56012. }
  56013. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  56014. return "AnaglyphGamepadCamera";
  56015. };
  56016. return AnaglyphGamepadCamera;
  56017. })(BABYLON.GamepadCamera);
  56018. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  56019. var AnaglyphUniversalCamera = (function (_super) {
  56020. __extends(AnaglyphUniversalCamera, _super);
  56021. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  56022. _super.call(this, name, position, scene);
  56023. this.interaxialDistance = interaxialDistance;
  56024. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56025. }
  56026. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  56027. return "AnaglyphUniversalCamera";
  56028. };
  56029. return AnaglyphUniversalCamera;
  56030. })(BABYLON.UniversalCamera);
  56031. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  56032. var StereoscopicFreeCamera = (function (_super) {
  56033. __extends(StereoscopicFreeCamera, _super);
  56034. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56035. _super.call(this, name, position, scene);
  56036. this.interaxialDistance = interaxialDistance;
  56037. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56038. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56039. }
  56040. StereoscopicFreeCamera.prototype.getTypeName = function () {
  56041. return "StereoscopicFreeCamera";
  56042. };
  56043. return StereoscopicFreeCamera;
  56044. })(BABYLON.FreeCamera);
  56045. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  56046. var StereoscopicArcRotateCamera = (function (_super) {
  56047. __extends(StereoscopicArcRotateCamera, _super);
  56048. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  56049. _super.call(this, name, alpha, beta, radius, target, scene);
  56050. this.interaxialDistance = interaxialDistance;
  56051. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56052. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56053. }
  56054. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  56055. return "StereoscopicArcRotateCamera";
  56056. };
  56057. return StereoscopicArcRotateCamera;
  56058. })(BABYLON.ArcRotateCamera);
  56059. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  56060. var StereoscopicGamepadCamera = (function (_super) {
  56061. __extends(StereoscopicGamepadCamera, _super);
  56062. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56063. _super.call(this, name, position, scene);
  56064. this.interaxialDistance = interaxialDistance;
  56065. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56066. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56067. }
  56068. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  56069. return "StereoscopicGamepadCamera";
  56070. };
  56071. return StereoscopicGamepadCamera;
  56072. })(BABYLON.GamepadCamera);
  56073. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  56074. var StereoscopicUniversalCamera = (function (_super) {
  56075. __extends(StereoscopicUniversalCamera, _super);
  56076. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56077. _super.call(this, name, position, scene);
  56078. this.interaxialDistance = interaxialDistance;
  56079. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56080. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56081. }
  56082. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  56083. return "StereoscopicUniversalCamera";
  56084. };
  56085. return StereoscopicUniversalCamera;
  56086. })(BABYLON.UniversalCamera);
  56087. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  56088. })(BABYLON || (BABYLON = {}));
  56089. var BABYLON;
  56090. (function (BABYLON) {
  56091. var HDRRenderingPipeline = (function (_super) {
  56092. __extends(HDRRenderingPipeline, _super);
  56093. /**
  56094. * @constructor
  56095. * @param {string} name - The rendering pipeline name
  56096. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56097. * @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)
  56098. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  56099. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56100. */
  56101. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  56102. var _this = this;
  56103. if (originalPostProcess === void 0) { originalPostProcess = null; }
  56104. _super.call(this, scene.getEngine(), name);
  56105. /**
  56106. * Public members
  56107. */
  56108. // Gaussian Blur
  56109. /**
  56110. * Gaussian blur coefficient
  56111. * @type {number}
  56112. */
  56113. this.gaussCoeff = 0.3;
  56114. /**
  56115. * Gaussian blur mean
  56116. * @type {number}
  56117. */
  56118. this.gaussMean = 1.0;
  56119. /**
  56120. * Gaussian blur standard deviation
  56121. * @type {number}
  56122. */
  56123. this.gaussStandDev = 0.8;
  56124. /**
  56125. * Gaussian blur multiplier. Multiplies the blur effect
  56126. * @type {number}
  56127. */
  56128. this.gaussMultiplier = 4.0;
  56129. // HDR
  56130. /**
  56131. * Exposure, controls the overall intensity of the pipeline
  56132. * @type {number}
  56133. */
  56134. this.exposure = 1.0;
  56135. /**
  56136. * Minimum luminance that the post-process can output. Luminance is >= 0
  56137. * @type {number}
  56138. */
  56139. this.minimumLuminance = 1.0;
  56140. /**
  56141. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  56142. * @type {number}
  56143. */
  56144. this.maximumLuminance = 1e20;
  56145. /**
  56146. * Increase rate for luminance: eye adaptation speed to dark
  56147. * @type {number}
  56148. */
  56149. this.luminanceIncreaserate = 0.5;
  56150. /**
  56151. * Decrease rate for luminance: eye adaptation speed to bright
  56152. * @type {number}
  56153. */
  56154. this.luminanceDecreaseRate = 0.5;
  56155. // Bright pass
  56156. /**
  56157. * Minimum luminance needed to compute HDR
  56158. * @type {number}
  56159. */
  56160. this.brightThreshold = 0.8;
  56161. this._needUpdate = true;
  56162. this._scene = scene;
  56163. // Bright pass
  56164. this._createBrightPassPostProcess(scene, ratio);
  56165. // Down sample X4
  56166. this._createDownSampleX4PostProcess(scene, ratio);
  56167. // Create gaussian blur post-processes
  56168. this._createGaussianBlurPostProcess(scene, ratio);
  56169. // Texture adder
  56170. this._createTextureAdderPostProcess(scene, ratio);
  56171. // Luminance generator
  56172. this._createLuminanceGeneratorPostProcess(scene);
  56173. // HDR
  56174. this._createHDRPostProcess(scene, ratio);
  56175. // Pass postprocess
  56176. if (originalPostProcess === null) {
  56177. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  56178. }
  56179. else {
  56180. this._originalPostProcess = originalPostProcess;
  56181. }
  56182. // Configure pipeline
  56183. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  56184. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  56185. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  56186. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  56187. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  56188. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  56189. var addDownSamplerPostProcess = function (id) {
  56190. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  56191. };
  56192. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  56193. addDownSamplerPostProcess(i);
  56194. }
  56195. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  56196. // Finish
  56197. scene.postProcessRenderPipelineManager.addPipeline(this);
  56198. if (cameras !== null) {
  56199. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56200. }
  56201. this.update();
  56202. }
  56203. /**
  56204. * Tells the pipeline to update its post-processes
  56205. */
  56206. HDRRenderingPipeline.prototype.update = function () {
  56207. this._needUpdate = true;
  56208. };
  56209. /**
  56210. * Returns the current calculated luminance
  56211. */
  56212. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  56213. return this._hdrCurrentLuminance;
  56214. };
  56215. /**
  56216. * Returns the currently drawn luminance
  56217. */
  56218. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  56219. return this._hdrOutputLuminance;
  56220. };
  56221. /**
  56222. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  56223. */
  56224. HDRRenderingPipeline.prototype.dispose = function () {
  56225. this._originalPostProcess = undefined;
  56226. this._brightPassPostProcess = undefined;
  56227. this._downSampleX4PostProcess = undefined;
  56228. this._guassianBlurHPostProcess = undefined;
  56229. this._guassianBlurVPostProcess = undefined;
  56230. this._textureAdderPostProcess = undefined;
  56231. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  56232. this._downSamplePostProcesses[i] = undefined;
  56233. }
  56234. this._hdrPostProcess = undefined;
  56235. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56236. };
  56237. /**
  56238. * Creates the HDR post-process and computes the luminance adaptation
  56239. */
  56240. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  56241. var _this = this;
  56242. var hdrLastLuminance = 0.0;
  56243. this._hdrOutputLuminance = -1.0;
  56244. this._hdrCurrentLuminance = 1.0;
  56245. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  56246. this._hdrPostProcess.onApply = function (effect) {
  56247. if (_this._hdrOutputLuminance < 0.0) {
  56248. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  56249. }
  56250. else {
  56251. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  56252. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  56253. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  56254. }
  56255. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  56256. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  56257. }
  56258. else {
  56259. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  56260. }
  56261. }
  56262. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  56263. hdrLastLuminance += scene.getEngine().getDeltaTime();
  56264. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  56265. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  56266. effect.setFloat("exposure", _this.exposure);
  56267. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  56268. _this._needUpdate = false;
  56269. };
  56270. };
  56271. /**
  56272. * Texture Adder post-process
  56273. */
  56274. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  56275. var _this = this;
  56276. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  56277. this._textureAdderPostProcess.onApply = function (effect) {
  56278. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  56279. };
  56280. };
  56281. /**
  56282. * Down sample X4 post-process
  56283. */
  56284. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  56285. var _this = this;
  56286. var downSampleX4Offsets = new Array(32);
  56287. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  56288. this._downSampleX4PostProcess.onApply = function (effect) {
  56289. if (_this._needUpdate) {
  56290. var id = 0;
  56291. for (var i = -2; i < 2; i++) {
  56292. for (var j = -2; j < 2; j++) {
  56293. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  56294. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  56295. id += 2;
  56296. }
  56297. }
  56298. }
  56299. effect.setArray2("dsOffsets", downSampleX4Offsets);
  56300. };
  56301. };
  56302. /**
  56303. * Bright pass post-process
  56304. */
  56305. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  56306. var _this = this;
  56307. var brightOffsets = new Array(8);
  56308. var brightPassCallback = function (effect) {
  56309. if (_this._needUpdate) {
  56310. var sU = (1.0 / _this._brightPassPostProcess.width);
  56311. var sV = (1.0 / _this._brightPassPostProcess.height);
  56312. brightOffsets[0] = -0.5 * sU;
  56313. brightOffsets[1] = 0.5 * sV;
  56314. brightOffsets[2] = 0.5 * sU;
  56315. brightOffsets[3] = 0.5 * sV;
  56316. brightOffsets[4] = -0.5 * sU;
  56317. brightOffsets[5] = -0.5 * sV;
  56318. brightOffsets[6] = 0.5 * sU;
  56319. brightOffsets[7] = -0.5 * sV;
  56320. }
  56321. effect.setArray2("dsOffsets", brightOffsets);
  56322. effect.setFloat("brightThreshold", _this.brightThreshold);
  56323. };
  56324. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  56325. this._brightPassPostProcess.onApply = brightPassCallback;
  56326. };
  56327. /**
  56328. * Luminance generator. Creates the luminance post-process and down sample post-processes
  56329. */
  56330. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  56331. var _this = this;
  56332. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  56333. var luminanceOffsets = new Array(8);
  56334. var downSampleOffsets = new Array(18);
  56335. var halfDestPixelSize;
  56336. this._downSamplePostProcesses = new Array(lumSteps);
  56337. // Utils for luminance
  56338. var luminanceUpdateSourceOffsets = function (width, height) {
  56339. var sU = (1.0 / width);
  56340. var sV = (1.0 / height);
  56341. luminanceOffsets[0] = -0.5 * sU;
  56342. luminanceOffsets[1] = 0.5 * sV;
  56343. luminanceOffsets[2] = 0.5 * sU;
  56344. luminanceOffsets[3] = 0.5 * sV;
  56345. luminanceOffsets[4] = -0.5 * sU;
  56346. luminanceOffsets[5] = -0.5 * sV;
  56347. luminanceOffsets[6] = 0.5 * sU;
  56348. luminanceOffsets[7] = -0.5 * sV;
  56349. };
  56350. var luminanceUpdateDestOffsets = function (width, height) {
  56351. var id = 0;
  56352. for (var x = -1; x < 2; x++) {
  56353. for (var y = -1; y < 2; y++) {
  56354. downSampleOffsets[id] = (x) / width;
  56355. downSampleOffsets[id + 1] = (y) / height;
  56356. id += 2;
  56357. }
  56358. }
  56359. };
  56360. // Luminance callback
  56361. var luminanceCallback = function (effect) {
  56362. if (_this._needUpdate) {
  56363. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  56364. }
  56365. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  56366. effect.setArray2("lumOffsets", luminanceOffsets);
  56367. };
  56368. // Down sample callbacks
  56369. var downSampleCallback = function (indice) {
  56370. var i = indice;
  56371. return function (effect) {
  56372. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  56373. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  56374. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  56375. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  56376. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  56377. effect.setArray2("dsOffsets", downSampleOffsets);
  56378. };
  56379. };
  56380. var downSampleAfterRenderCallback = function (effect) {
  56381. // Unpack result
  56382. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  56383. 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);
  56384. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  56385. };
  56386. // Create luminance post-process
  56387. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  56388. 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);
  56389. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  56390. // Create down sample post-processes
  56391. for (var i = lumSteps - 2; i >= 0; i--) {
  56392. var length = Math.pow(3, i);
  56393. ratio = { width: length, height: length };
  56394. var defines = "#define DOWN_SAMPLE\n";
  56395. if (i === 0) {
  56396. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  56397. }
  56398. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  56399. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  56400. if (i === 0) {
  56401. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  56402. }
  56403. }
  56404. };
  56405. /**
  56406. * Gaussian blur post-processes. Horizontal and Vertical
  56407. */
  56408. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  56409. var _this = this;
  56410. var blurOffsetsW = new Array(9);
  56411. var blurOffsetsH = new Array(9);
  56412. var blurWeights = new Array(9);
  56413. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  56414. // Utils for gaussian blur
  56415. var calculateBlurOffsets = function (height) {
  56416. var lastOutputDimensions = {
  56417. width: scene.getEngine().getRenderWidth(),
  56418. height: scene.getEngine().getRenderHeight()
  56419. };
  56420. for (var i = 0; i < 9; i++) {
  56421. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  56422. if (height) {
  56423. blurOffsetsH[i] = value;
  56424. }
  56425. else {
  56426. blurOffsetsW[i] = value;
  56427. }
  56428. }
  56429. };
  56430. var calculateWeights = function () {
  56431. var x = 0.0;
  56432. for (var i = 0; i < 9; i++) {
  56433. x = (i - 4.0) / 4.0;
  56434. 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));
  56435. }
  56436. };
  56437. // Callback
  56438. var gaussianBlurCallback = function (height) {
  56439. return function (effect) {
  56440. if (_this._needUpdate) {
  56441. calculateWeights();
  56442. calculateBlurOffsets(height);
  56443. }
  56444. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  56445. effect.setArray("blurWeights", blurWeights);
  56446. effect.setFloat("multiplier", _this.gaussMultiplier);
  56447. };
  56448. };
  56449. // Create horizontal gaussian blur post-processes
  56450. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  56451. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  56452. // Create vertical gaussian blur post-process
  56453. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  56454. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  56455. };
  56456. // Luminance generator
  56457. HDRRenderingPipeline.LUM_STEPS = 6;
  56458. return HDRRenderingPipeline;
  56459. })(BABYLON.PostProcessRenderPipeline);
  56460. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  56461. })(BABYLON || (BABYLON = {}));
  56462. var BABYLON;
  56463. (function (BABYLON) {
  56464. var FaceAdjacencies = (function () {
  56465. function FaceAdjacencies() {
  56466. this.edges = new Array();
  56467. this.edgesConnectedCount = 0;
  56468. }
  56469. return FaceAdjacencies;
  56470. })();
  56471. var EdgesRenderer = (function () {
  56472. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  56473. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  56474. if (epsilon === void 0) { epsilon = 0.95; }
  56475. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  56476. this.edgesWidthScalerForOrthographic = 1000.0;
  56477. this.edgesWidthScalerForPerspective = 50.0;
  56478. this._linesPositions = new Array();
  56479. this._linesNormals = new Array();
  56480. this._linesIndices = new Array();
  56481. this._buffers = {};
  56482. this._checkVerticesInsteadOfIndices = false;
  56483. this._source = source;
  56484. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  56485. this._epsilon = epsilon;
  56486. this._prepareRessources();
  56487. this._generateEdgesLines();
  56488. }
  56489. EdgesRenderer.prototype._prepareRessources = function () {
  56490. if (this._lineShader) {
  56491. return;
  56492. }
  56493. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  56494. attributes: ["position", "normal"],
  56495. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  56496. });
  56497. this._lineShader.disableDepthWrite = true;
  56498. this._lineShader.backFaceCulling = false;
  56499. };
  56500. EdgesRenderer.prototype.dispose = function () {
  56501. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  56502. if (buffer) {
  56503. buffer.dispose();
  56504. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  56505. }
  56506. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  56507. if (buffer) {
  56508. buffer.dispose();
  56509. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  56510. }
  56511. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  56512. this._lineShader.dispose();
  56513. };
  56514. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  56515. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  56516. return 0;
  56517. }
  56518. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  56519. return 1;
  56520. }
  56521. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  56522. return 2;
  56523. }
  56524. return -1;
  56525. };
  56526. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  56527. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  56528. return 0;
  56529. }
  56530. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  56531. return 1;
  56532. }
  56533. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  56534. return 2;
  56535. }
  56536. return -1;
  56537. };
  56538. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  56539. var needToCreateLine;
  56540. if (edge === undefined) {
  56541. needToCreateLine = true;
  56542. }
  56543. else {
  56544. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  56545. needToCreateLine = dotProduct < this._epsilon;
  56546. }
  56547. if (needToCreateLine) {
  56548. var offset = this._linesPositions.length / 3;
  56549. var normal = p0.subtract(p1);
  56550. normal.normalize();
  56551. // Positions
  56552. this._linesPositions.push(p0.x);
  56553. this._linesPositions.push(p0.y);
  56554. this._linesPositions.push(p0.z);
  56555. this._linesPositions.push(p0.x);
  56556. this._linesPositions.push(p0.y);
  56557. this._linesPositions.push(p0.z);
  56558. this._linesPositions.push(p1.x);
  56559. this._linesPositions.push(p1.y);
  56560. this._linesPositions.push(p1.z);
  56561. this._linesPositions.push(p1.x);
  56562. this._linesPositions.push(p1.y);
  56563. this._linesPositions.push(p1.z);
  56564. // Normals
  56565. this._linesNormals.push(p1.x);
  56566. this._linesNormals.push(p1.y);
  56567. this._linesNormals.push(p1.z);
  56568. this._linesNormals.push(-1);
  56569. this._linesNormals.push(p1.x);
  56570. this._linesNormals.push(p1.y);
  56571. this._linesNormals.push(p1.z);
  56572. this._linesNormals.push(1);
  56573. this._linesNormals.push(p0.x);
  56574. this._linesNormals.push(p0.y);
  56575. this._linesNormals.push(p0.z);
  56576. this._linesNormals.push(-1);
  56577. this._linesNormals.push(p0.x);
  56578. this._linesNormals.push(p0.y);
  56579. this._linesNormals.push(p0.z);
  56580. this._linesNormals.push(1);
  56581. // Indices
  56582. this._linesIndices.push(offset);
  56583. this._linesIndices.push(offset + 1);
  56584. this._linesIndices.push(offset + 2);
  56585. this._linesIndices.push(offset);
  56586. this._linesIndices.push(offset + 2);
  56587. this._linesIndices.push(offset + 3);
  56588. }
  56589. };
  56590. EdgesRenderer.prototype._generateEdgesLines = function () {
  56591. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56592. var indices = this._source.getIndices();
  56593. // First let's find adjacencies
  56594. var adjacencies = new Array();
  56595. var faceNormals = new Array();
  56596. var index;
  56597. var faceAdjacencies;
  56598. // Prepare faces
  56599. for (index = 0; index < indices.length; index += 3) {
  56600. faceAdjacencies = new FaceAdjacencies();
  56601. var p0Index = indices[index];
  56602. var p1Index = indices[index + 1];
  56603. var p2Index = indices[index + 2];
  56604. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  56605. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  56606. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  56607. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  56608. faceNormal.normalize();
  56609. faceNormals.push(faceNormal);
  56610. adjacencies.push(faceAdjacencies);
  56611. }
  56612. // Scan
  56613. for (index = 0; index < adjacencies.length; index++) {
  56614. faceAdjacencies = adjacencies[index];
  56615. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  56616. var otherFaceAdjacencies = adjacencies[otherIndex];
  56617. if (faceAdjacencies.edgesConnectedCount === 3) {
  56618. break;
  56619. }
  56620. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  56621. continue;
  56622. }
  56623. var otherP0 = indices[otherIndex * 3];
  56624. var otherP1 = indices[otherIndex * 3 + 1];
  56625. var otherP2 = indices[otherIndex * 3 + 2];
  56626. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  56627. var otherEdgeIndex;
  56628. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  56629. continue;
  56630. }
  56631. switch (edgeIndex) {
  56632. case 0:
  56633. if (this._checkVerticesInsteadOfIndices) {
  56634. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56635. }
  56636. else {
  56637. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  56638. }
  56639. break;
  56640. case 1:
  56641. if (this._checkVerticesInsteadOfIndices) {
  56642. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56643. }
  56644. else {
  56645. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  56646. }
  56647. break;
  56648. case 2:
  56649. if (this._checkVerticesInsteadOfIndices) {
  56650. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56651. }
  56652. else {
  56653. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  56654. }
  56655. break;
  56656. }
  56657. if (otherEdgeIndex === -1) {
  56658. continue;
  56659. }
  56660. faceAdjacencies.edges[edgeIndex] = otherIndex;
  56661. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  56662. faceAdjacencies.edgesConnectedCount++;
  56663. otherFaceAdjacencies.edgesConnectedCount++;
  56664. if (faceAdjacencies.edgesConnectedCount === 3) {
  56665. break;
  56666. }
  56667. }
  56668. }
  56669. }
  56670. // Create lines
  56671. for (index = 0; index < adjacencies.length; index++) {
  56672. // 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
  56673. var current = adjacencies[index];
  56674. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  56675. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  56676. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  56677. }
  56678. // Merge into a single mesh
  56679. var engine = this._source.getScene().getEngine();
  56680. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  56681. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  56682. this._ib = engine.createIndexBuffer(this._linesIndices);
  56683. this._indicesCount = this._linesIndices.length;
  56684. };
  56685. EdgesRenderer.prototype.render = function () {
  56686. if (!this._lineShader.isReady()) {
  56687. return;
  56688. }
  56689. var scene = this._source.getScene();
  56690. var engine = scene.getEngine();
  56691. this._lineShader._preBind();
  56692. // VBOs
  56693. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  56694. scene.resetCachedMaterial();
  56695. this._lineShader.setColor4("color", this._source.edgesColor);
  56696. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  56697. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  56698. }
  56699. else {
  56700. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  56701. }
  56702. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  56703. this._lineShader.bind(this._source.getWorldMatrix());
  56704. // Draw order
  56705. engine.draw(true, 0, this._indicesCount);
  56706. this._lineShader.unbind();
  56707. engine.setDepthWrite(true);
  56708. };
  56709. return EdgesRenderer;
  56710. })();
  56711. BABYLON.EdgesRenderer = EdgesRenderer;
  56712. })(BABYLON || (BABYLON = {}));
  56713. var BABYLON;
  56714. (function (BABYLON) {
  56715. (function (TonemappingOperator) {
  56716. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  56717. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  56718. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  56719. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  56720. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  56721. var TonemappingOperator = BABYLON.TonemappingOperator;
  56722. ;
  56723. var TonemapPostProcess = (function (_super) {
  56724. __extends(TonemapPostProcess, _super);
  56725. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  56726. var _this = this;
  56727. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56728. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56729. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  56730. this._operator = _operator;
  56731. this.exposureAdjustment = exposureAdjustment;
  56732. var defines = "#define ";
  56733. if (this._operator === TonemappingOperator.Hable)
  56734. defines += "HABLE_TONEMAPPING";
  56735. else if (this._operator === TonemappingOperator.Reinhard)
  56736. defines += "REINHARD_TONEMAPPING";
  56737. else if (this._operator === TonemappingOperator.HejiDawson)
  56738. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  56739. else if (this._operator === TonemappingOperator.Photographic)
  56740. defines += "PHOTOGRAPHIC_TONEMAPPING";
  56741. //sadly a second call to create the effect.
  56742. this.updateEffect(defines);
  56743. this.onApply = function (effect) {
  56744. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  56745. };
  56746. }
  56747. return TonemapPostProcess;
  56748. })(BABYLON.PostProcess);
  56749. BABYLON.TonemapPostProcess = TonemapPostProcess;
  56750. })(BABYLON || (BABYLON = {}));
  56751. var BABYLON;
  56752. (function (BABYLON) {
  56753. var ReflectionProbe = (function () {
  56754. function ReflectionProbe(name, size, scene, generateMipMaps) {
  56755. var _this = this;
  56756. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56757. this.name = name;
  56758. this._viewMatrix = BABYLON.Matrix.Identity();
  56759. this._target = BABYLON.Vector3.Zero();
  56760. this._add = BABYLON.Vector3.Zero();
  56761. this.invertYAxis = false;
  56762. this.position = BABYLON.Vector3.Zero();
  56763. this._scene = scene;
  56764. this._scene.reflectionProbes.push(this);
  56765. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  56766. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  56767. switch (faceIndex) {
  56768. case 0:
  56769. _this._add.copyFromFloats(1, 0, 0);
  56770. break;
  56771. case 1:
  56772. _this._add.copyFromFloats(-1, 0, 0);
  56773. break;
  56774. case 2:
  56775. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  56776. break;
  56777. case 3:
  56778. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  56779. break;
  56780. case 4:
  56781. _this._add.copyFromFloats(0, 0, 1);
  56782. break;
  56783. case 5:
  56784. _this._add.copyFromFloats(0, 0, -1);
  56785. break;
  56786. }
  56787. if (_this._attachedMesh) {
  56788. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  56789. }
  56790. _this.position.addToRef(_this._add, _this._target);
  56791. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  56792. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  56793. });
  56794. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  56795. scene.updateTransformMatrix(true);
  56796. });
  56797. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  56798. }
  56799. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  56800. get: function () {
  56801. return this._renderTargetTexture.refreshRate;
  56802. },
  56803. set: function (value) {
  56804. this._renderTargetTexture.refreshRate = value;
  56805. },
  56806. enumerable: true,
  56807. configurable: true
  56808. });
  56809. ReflectionProbe.prototype.getScene = function () {
  56810. return this._scene;
  56811. };
  56812. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  56813. get: function () {
  56814. return this._renderTargetTexture;
  56815. },
  56816. enumerable: true,
  56817. configurable: true
  56818. });
  56819. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  56820. get: function () {
  56821. return this._renderTargetTexture.renderList;
  56822. },
  56823. enumerable: true,
  56824. configurable: true
  56825. });
  56826. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  56827. this._attachedMesh = mesh;
  56828. };
  56829. ReflectionProbe.prototype.dispose = function () {
  56830. var index = this._scene.reflectionProbes.indexOf(this);
  56831. if (index !== -1) {
  56832. // Remove from the scene if found
  56833. this._scene.reflectionProbes.splice(index, 1);
  56834. }
  56835. if (this._renderTargetTexture) {
  56836. this._renderTargetTexture.dispose();
  56837. this._renderTargetTexture = null;
  56838. }
  56839. };
  56840. return ReflectionProbe;
  56841. })();
  56842. BABYLON.ReflectionProbe = ReflectionProbe;
  56843. })(BABYLON || (BABYLON = {}));
  56844. var BABYLON;
  56845. (function (BABYLON) {
  56846. var SolidParticle = (function () {
  56847. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  56848. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  56849. this.position = BABYLON.Vector3.Zero(); // position
  56850. this.rotation = BABYLON.Vector3.Zero(); // rotation
  56851. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  56852. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  56853. this.velocity = BABYLON.Vector3.Zero(); // velocity
  56854. this.alive = true; // alive
  56855. this.isVisible = true; // visibility
  56856. this.idx = particleIndex;
  56857. this._pos = positionIndex;
  56858. this._model = model;
  56859. this.shapeId = shapeId;
  56860. this.idxInShape = idxInShape;
  56861. }
  56862. Object.defineProperty(SolidParticle.prototype, "scale", {
  56863. //legacy support, changed scale to scaling
  56864. get: function () {
  56865. return this.scaling;
  56866. },
  56867. set: function (scale) {
  56868. this.scaling = scale;
  56869. },
  56870. enumerable: true,
  56871. configurable: true
  56872. });
  56873. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56874. //legacy support, changed quaternion to rotationQuaternion
  56875. get: function () {
  56876. return this.rotationQuaternion;
  56877. },
  56878. set: function (q) {
  56879. this.rotationQuaternion = q;
  56880. },
  56881. enumerable: true,
  56882. configurable: true
  56883. });
  56884. return SolidParticle;
  56885. })();
  56886. BABYLON.SolidParticle = SolidParticle;
  56887. var ModelShape = (function () {
  56888. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  56889. this.shapeID = id;
  56890. this._shape = shape;
  56891. this._shapeUV = shapeUV;
  56892. this._positionFunction = posFunction;
  56893. this._vertexFunction = vtxFunction;
  56894. }
  56895. return ModelShape;
  56896. })();
  56897. BABYLON.ModelShape = ModelShape;
  56898. })(BABYLON || (BABYLON = {}));
  56899. var BABYLON;
  56900. (function (BABYLON) {
  56901. /**
  56902. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  56903. */
  56904. var SolidParticleSystem = (function () {
  56905. /**
  56906. * Creates a SPS (Solid Particle System) object.
  56907. * `name` (String) is the SPS name, this will be the underlying mesh name.
  56908. * `scene` (Scene) is the scene in which the SPS is added.
  56909. * `updatable` (default true) : if the SPS must be updatable or immutable.
  56910. * `isPickable` (default false) : if the solid particles must be pickable.
  56911. */
  56912. function SolidParticleSystem(name, scene, options) {
  56913. // public members
  56914. /**
  56915. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  56916. * Example : var p = SPS.particles[i];
  56917. */
  56918. this.particles = new Array();
  56919. /**
  56920. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  56921. */
  56922. this.nbParticles = 0;
  56923. /**
  56924. * If the particles must ever face the camera (default false). Useful for planar particles.
  56925. */
  56926. this.billboard = false;
  56927. /**
  56928. * This a counter ofr your own usage. It's not set by any SPS functions.
  56929. */
  56930. this.counter = 0;
  56931. /**
  56932. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  56933. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  56934. */
  56935. this.vars = {};
  56936. this._positions = new Array();
  56937. this._indices = new Array();
  56938. this._normals = new Array();
  56939. this._colors = new Array();
  56940. this._uvs = new Array();
  56941. this._index = 0; // indices index
  56942. this._updatable = true;
  56943. this._pickable = false;
  56944. this._isVisibilityBoxLocked = false;
  56945. this._alwaysVisible = false;
  56946. this._shapeCounter = 0;
  56947. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  56948. this._color = new BABYLON.Color4(0, 0, 0, 0);
  56949. this._computeParticleColor = true;
  56950. this._computeParticleTexture = true;
  56951. this._computeParticleRotation = true;
  56952. this._computeParticleVertex = false;
  56953. this._computeBoundingBox = false;
  56954. this._cam_axisZ = BABYLON.Vector3.Zero();
  56955. this._cam_axisY = BABYLON.Vector3.Zero();
  56956. this._cam_axisX = BABYLON.Vector3.Zero();
  56957. this._axisX = BABYLON.Axis.X;
  56958. this._axisY = BABYLON.Axis.Y;
  56959. this._axisZ = BABYLON.Axis.Z;
  56960. this._camDir = BABYLON.Vector3.Zero();
  56961. this._rotMatrix = new BABYLON.Matrix();
  56962. this._invertMatrix = new BABYLON.Matrix();
  56963. this._rotated = BABYLON.Vector3.Zero();
  56964. this._quaternion = new BABYLON.Quaternion();
  56965. this._vertex = BABYLON.Vector3.Zero();
  56966. this._normal = BABYLON.Vector3.Zero();
  56967. this._yaw = 0.0;
  56968. this._pitch = 0.0;
  56969. this._roll = 0.0;
  56970. this._halfroll = 0.0;
  56971. this._halfpitch = 0.0;
  56972. this._halfyaw = 0.0;
  56973. this._sinRoll = 0.0;
  56974. this._cosRoll = 0.0;
  56975. this._sinPitch = 0.0;
  56976. this._cosPitch = 0.0;
  56977. this._sinYaw = 0.0;
  56978. this._cosYaw = 0.0;
  56979. this._w = 0.0;
  56980. this._minimum = BABYLON.Tmp.Vector3[0];
  56981. this._maximum = BABYLON.Tmp.Vector3[1];
  56982. this.name = name;
  56983. this._scene = scene;
  56984. this._camera = scene.activeCamera;
  56985. this._pickable = options ? options.isPickable : false;
  56986. if (options && options.updatable) {
  56987. this._updatable = options.updatable;
  56988. }
  56989. else {
  56990. this._updatable = true;
  56991. }
  56992. if (this._pickable) {
  56993. this.pickedParticles = [];
  56994. }
  56995. }
  56996. /**
  56997. * Builds the SPS underlying mesh. Returns a standard Mesh.
  56998. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  56999. */
  57000. SolidParticleSystem.prototype.buildMesh = function () {
  57001. if (this.nbParticles === 0) {
  57002. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57003. this.addShape(triangle, 1);
  57004. triangle.dispose();
  57005. }
  57006. this._positions32 = new Float32Array(this._positions);
  57007. this._uvs32 = new Float32Array(this._uvs);
  57008. this._colors32 = new Float32Array(this._colors);
  57009. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  57010. this._normals32 = new Float32Array(this._normals);
  57011. this._fixedNormal32 = new Float32Array(this._normals);
  57012. var vertexData = new BABYLON.VertexData();
  57013. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57014. vertexData.indices = this._indices;
  57015. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57016. if (this._uvs32) {
  57017. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57018. ;
  57019. }
  57020. if (this._colors32) {
  57021. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57022. }
  57023. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57024. vertexData.applyToMesh(mesh, this._updatable);
  57025. this.mesh = mesh;
  57026. this.mesh.isPickable = this._pickable;
  57027. // free memory
  57028. this._positions = null;
  57029. this._normals = null;
  57030. this._uvs = null;
  57031. this._colors = null;
  57032. if (!this._updatable) {
  57033. this.particles.length = 0;
  57034. }
  57035. return mesh;
  57036. };
  57037. /**
  57038. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57039. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57040. * Thus the particles generated from `digest()` have their property `position` set yet.
  57041. * `mesh` ( Mesh ) is the mesh to be digested
  57042. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  57043. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57044. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57045. */
  57046. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57047. var size = (options && options.facetNb) || 1;
  57048. var number = (options && options.number);
  57049. var delta = (options && options.delta) || 0;
  57050. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57051. var meshInd = mesh.getIndices();
  57052. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57053. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57054. var f = 0; // facet counter
  57055. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57056. // compute size from number
  57057. if (number) {
  57058. number = (number > totalFacets) ? totalFacets : number;
  57059. size = Math.round(totalFacets / number);
  57060. delta = 0;
  57061. }
  57062. else {
  57063. size = (size > totalFacets) ? totalFacets : size;
  57064. }
  57065. var facetPos = []; // submesh positions
  57066. var facetInd = []; // submesh indices
  57067. var facetUV = []; // submesh UV
  57068. var facetCol = []; // submesh colors
  57069. var barycenter = BABYLON.Tmp.Vector3[0];
  57070. var rand;
  57071. var sizeO = size;
  57072. while (f < totalFacets) {
  57073. size = sizeO + Math.floor((1 + delta) * Math.random());
  57074. if (f > totalFacets - size) {
  57075. size = totalFacets - f;
  57076. }
  57077. // reset temp arrays
  57078. facetPos.length = 0;
  57079. facetInd.length = 0;
  57080. facetUV.length = 0;
  57081. facetCol.length = 0;
  57082. // iterate over "size" facets
  57083. var fi = 0;
  57084. for (var j = f * 3; j < (f + size) * 3; j++) {
  57085. facetInd.push(fi);
  57086. var i = meshInd[j];
  57087. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57088. if (meshUV) {
  57089. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57090. }
  57091. if (meshCol) {
  57092. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57093. }
  57094. fi++;
  57095. }
  57096. // create a model shape for each single particle
  57097. var idx = this.nbParticles;
  57098. var shape = this._posToShape(facetPos);
  57099. var shapeUV = this._uvsToShapeUV(facetUV);
  57100. // compute the barycenter of the shape
  57101. var v;
  57102. for (v = 0; v < shape.length; v++) {
  57103. barycenter.addInPlace(shape[v]);
  57104. }
  57105. barycenter.scaleInPlace(1 / shape.length);
  57106. // shift the shape from its barycenter to the origin
  57107. for (v = 0; v < shape.length; v++) {
  57108. shape[v].subtractInPlace(barycenter);
  57109. }
  57110. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  57111. // add the particle in the SPS
  57112. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  57113. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  57114. // initialize the particle position
  57115. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57116. this._index += shape.length;
  57117. idx++;
  57118. this.nbParticles++;
  57119. this._shapeCounter++;
  57120. f += size;
  57121. }
  57122. return this;
  57123. };
  57124. //reset copy
  57125. SolidParticleSystem.prototype._resetCopy = function () {
  57126. this._copy.position.x = 0;
  57127. this._copy.position.y = 0;
  57128. this._copy.position.z = 0;
  57129. this._copy.rotation.x = 0;
  57130. this._copy.rotation.y = 0;
  57131. this._copy.rotation.z = 0;
  57132. this._copy.rotationQuaternion = null;
  57133. this._copy.scaling.x = 1;
  57134. this._copy.scaling.y = 1;
  57135. this._copy.scaling.z = 1;
  57136. this._copy.uvs.x = 0;
  57137. this._copy.uvs.y = 0;
  57138. this._copy.uvs.z = 1;
  57139. this._copy.uvs.w = 1;
  57140. this._copy.color = null;
  57141. };
  57142. // _meshBuilder : inserts the shape model in the global SPS mesh
  57143. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  57144. var i;
  57145. var u = 0;
  57146. var c = 0;
  57147. this._resetCopy();
  57148. if (options && options.positionFunction) {
  57149. options.positionFunction(this._copy, idx, idxInShape);
  57150. }
  57151. if (this._copy.rotationQuaternion) {
  57152. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57153. }
  57154. else {
  57155. this._yaw = this._copy.rotation.y;
  57156. this._pitch = this._copy.rotation.x;
  57157. this._roll = this._copy.rotation.z;
  57158. this._quaternionRotationYPR();
  57159. }
  57160. this._quaternionToRotationMatrix();
  57161. for (i = 0; i < shape.length; i++) {
  57162. this._vertex.x = shape[i].x;
  57163. this._vertex.y = shape[i].y;
  57164. this._vertex.z = shape[i].z;
  57165. if (options && options.vertexFunction) {
  57166. options.vertexFunction(this._copy, this._vertex, i);
  57167. }
  57168. this._vertex.x *= this._copy.scaling.x;
  57169. this._vertex.y *= this._copy.scaling.y;
  57170. this._vertex.z *= this._copy.scaling.z;
  57171. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57172. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57173. if (meshUV) {
  57174. 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);
  57175. u += 2;
  57176. }
  57177. if (this._copy.color) {
  57178. this._color = this._copy.color;
  57179. }
  57180. else if (meshCol && meshCol[c] !== undefined) {
  57181. this._color.r = meshCol[c];
  57182. this._color.g = meshCol[c + 1];
  57183. this._color.b = meshCol[c + 2];
  57184. this._color.a = meshCol[c + 3];
  57185. }
  57186. else {
  57187. this._color.r = 1;
  57188. this._color.g = 1;
  57189. this._color.b = 1;
  57190. this._color.a = 1;
  57191. }
  57192. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57193. c += 4;
  57194. }
  57195. for (i = 0; i < meshInd.length; i++) {
  57196. indices.push(p + meshInd[i]);
  57197. }
  57198. if (this._pickable) {
  57199. var nbfaces = meshInd.length / 3;
  57200. for (i = 0; i < nbfaces; i++) {
  57201. this.pickedParticles.push({ idx: idx, faceId: i });
  57202. }
  57203. }
  57204. };
  57205. // returns a shape array from positions array
  57206. SolidParticleSystem.prototype._posToShape = function (positions) {
  57207. var shape = [];
  57208. for (var i = 0; i < positions.length; i += 3) {
  57209. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57210. }
  57211. return shape;
  57212. };
  57213. // returns a shapeUV array from a Vector4 uvs
  57214. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57215. var shapeUV = [];
  57216. if (uvs) {
  57217. for (var i = 0; i < uvs.length; i++)
  57218. shapeUV.push(uvs[i]);
  57219. }
  57220. return shapeUV;
  57221. };
  57222. // adds a new particle object in the particles array
  57223. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  57224. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  57225. };
  57226. /**
  57227. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57228. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57229. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  57230. * `nb` (positive integer) the number of particles to be created from this model
  57231. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  57232. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  57233. */
  57234. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57235. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57236. var meshInd = mesh.getIndices();
  57237. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57238. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57239. var shape = this._posToShape(meshPos);
  57240. var shapeUV = this._uvsToShapeUV(meshUV);
  57241. var posfunc = options ? options.positionFunction : null;
  57242. var vtxfunc = options ? options.vertexFunction : null;
  57243. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  57244. // particles
  57245. var idx = this.nbParticles;
  57246. for (var i = 0; i < nb; i++) {
  57247. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  57248. if (this._updatable) {
  57249. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  57250. }
  57251. this._index += shape.length;
  57252. idx++;
  57253. }
  57254. this.nbParticles += nb;
  57255. this._shapeCounter++;
  57256. return this._shapeCounter - 1;
  57257. };
  57258. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57259. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57260. this._resetCopy();
  57261. if (particle._model._positionFunction) {
  57262. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57263. }
  57264. if (this._copy.rotationQuaternion) {
  57265. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57266. }
  57267. else {
  57268. this._yaw = this._copy.rotation.y;
  57269. this._pitch = this._copy.rotation.x;
  57270. this._roll = this._copy.rotation.z;
  57271. this._quaternionRotationYPR();
  57272. }
  57273. this._quaternionToRotationMatrix();
  57274. this._shape = particle._model._shape;
  57275. for (var pt = 0; pt < this._shape.length; pt++) {
  57276. this._vertex.x = this._shape[pt].x;
  57277. this._vertex.y = this._shape[pt].y;
  57278. this._vertex.z = this._shape[pt].z;
  57279. if (particle._model._vertexFunction) {
  57280. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57281. }
  57282. this._vertex.x *= this._copy.scaling.x;
  57283. this._vertex.y *= this._copy.scaling.y;
  57284. this._vertex.z *= this._copy.scaling.z;
  57285. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57286. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57287. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57288. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57289. }
  57290. particle.position.x = 0;
  57291. particle.position.y = 0;
  57292. particle.position.z = 0;
  57293. particle.rotation.x = 0;
  57294. particle.rotation.y = 0;
  57295. particle.rotation.z = 0;
  57296. particle.rotationQuaternion = null;
  57297. particle.scaling.x = 1;
  57298. particle.scaling.y = 1;
  57299. particle.scaling.z = 1;
  57300. };
  57301. /**
  57302. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57303. */
  57304. SolidParticleSystem.prototype.rebuildMesh = function () {
  57305. for (var p = 0; p < this.particles.length; p++) {
  57306. this._rebuildParticle(this.particles[p]);
  57307. }
  57308. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57309. };
  57310. /**
  57311. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57312. * This method calls `updateParticle()` for each particle of the SPS.
  57313. * For an animated SPS, it is usually called within the render loop.
  57314. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57315. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57316. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57317. */
  57318. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57319. if (start === void 0) { start = 0; }
  57320. if (end === void 0) { end = this.nbParticles - 1; }
  57321. if (update === void 0) { update = true; }
  57322. if (!this._updatable) {
  57323. return;
  57324. }
  57325. // custom beforeUpdate
  57326. this.beforeUpdateParticles(start, end, update);
  57327. this._cam_axisX.x = 1.0;
  57328. this._cam_axisX.y = 0.0;
  57329. this._cam_axisX.z = 0.0;
  57330. this._cam_axisY.x = 0.0;
  57331. this._cam_axisY.y = 1.0;
  57332. this._cam_axisY.z = 0.0;
  57333. this._cam_axisZ.x = 0.0;
  57334. this._cam_axisZ.y = 0.0;
  57335. this._cam_axisZ.z = 1.0;
  57336. // if the particles will always face the camera
  57337. if (this.billboard) {
  57338. // compute the camera position and un-rotate it by the current mesh rotation
  57339. this._yaw = this.mesh.rotation.y;
  57340. this._pitch = this.mesh.rotation.x;
  57341. this._roll = this.mesh.rotation.z;
  57342. this._quaternionRotationYPR();
  57343. this._quaternionToRotationMatrix();
  57344. this._rotMatrix.invertToRef(this._invertMatrix);
  57345. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  57346. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57347. this._cam_axisZ.normalize();
  57348. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  57349. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  57350. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57351. this._cam_axisY.normalize();
  57352. this._cam_axisX.normalize();
  57353. }
  57354. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57355. var idx = 0;
  57356. var index = 0;
  57357. var colidx = 0;
  57358. var colorIndex = 0;
  57359. var uvidx = 0;
  57360. var uvIndex = 0;
  57361. var pt = 0;
  57362. if (this._computeBoundingBox) {
  57363. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57364. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57365. }
  57366. // particle loop
  57367. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  57368. for (var p = start; p <= end; p++) {
  57369. this._particle = this.particles[p];
  57370. this._shape = this._particle._model._shape;
  57371. this._shapeUV = this._particle._model._shapeUV;
  57372. // call to custom user function to update the particle properties
  57373. this.updateParticle(this._particle);
  57374. if (this._particle.isVisible) {
  57375. // particle rotation matrix
  57376. if (this.billboard) {
  57377. this._particle.rotation.x = 0.0;
  57378. this._particle.rotation.y = 0.0;
  57379. }
  57380. if (this._computeParticleRotation || this.billboard) {
  57381. if (this._particle.rotationQuaternion) {
  57382. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57383. }
  57384. else {
  57385. this._yaw = this._particle.rotation.y;
  57386. this._pitch = this._particle.rotation.x;
  57387. this._roll = this._particle.rotation.z;
  57388. this._quaternionRotationYPR();
  57389. }
  57390. this._quaternionToRotationMatrix();
  57391. }
  57392. // particle vertex loop
  57393. for (pt = 0; pt < this._shape.length; pt++) {
  57394. idx = index + pt * 3;
  57395. colidx = colorIndex + pt * 4;
  57396. uvidx = uvIndex + pt * 2;
  57397. this._vertex.x = this._shape[pt].x;
  57398. this._vertex.y = this._shape[pt].y;
  57399. this._vertex.z = this._shape[pt].z;
  57400. if (this._computeParticleVertex) {
  57401. this.updateParticleVertex(this._particle, this._vertex, pt);
  57402. }
  57403. // positions
  57404. this._vertex.x *= this._particle.scaling.x;
  57405. this._vertex.y *= this._particle.scaling.y;
  57406. this._vertex.z *= this._particle.scaling.z;
  57407. 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];
  57408. 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;
  57409. 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;
  57410. 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;
  57411. 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;
  57412. 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;
  57413. 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;
  57414. if (this._computeBoundingBox) {
  57415. if (this._positions32[idx] < this._minimum.x) {
  57416. this._minimum.x = this._positions32[idx];
  57417. }
  57418. if (this._positions32[idx] > this._maximum.x) {
  57419. this._maximum.x = this._positions32[idx];
  57420. }
  57421. if (this._positions32[idx + 1] < this._minimum.y) {
  57422. this._minimum.y = this._positions32[idx + 1];
  57423. }
  57424. if (this._positions32[idx + 1] > this._maximum.y) {
  57425. this._maximum.y = this._positions32[idx + 1];
  57426. }
  57427. if (this._positions32[idx + 2] < this._minimum.z) {
  57428. this._minimum.z = this._positions32[idx + 2];
  57429. }
  57430. if (this._positions32[idx + 2] > this._maximum.z) {
  57431. this._maximum.z = this._positions32[idx + 2];
  57432. }
  57433. }
  57434. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  57435. if (!this._computeParticleVertex) {
  57436. this._normal.x = this._fixedNormal32[idx];
  57437. this._normal.y = this._fixedNormal32[idx + 1];
  57438. this._normal.z = this._fixedNormal32[idx + 2];
  57439. 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];
  57440. 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;
  57441. 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;
  57442. 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;
  57443. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  57444. 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;
  57445. 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;
  57446. }
  57447. if (this._computeParticleColor) {
  57448. this._colors32[colidx] = this._particle.color.r;
  57449. this._colors32[colidx + 1] = this._particle.color.g;
  57450. this._colors32[colidx + 2] = this._particle.color.b;
  57451. this._colors32[colidx + 3] = this._particle.color.a;
  57452. }
  57453. if (this._computeParticleTexture) {
  57454. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57455. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57456. }
  57457. }
  57458. }
  57459. else {
  57460. for (pt = 0; pt < this._shape.length; pt++) {
  57461. idx = index + pt * 3;
  57462. colidx = colorIndex + pt * 4;
  57463. uvidx = uvIndex + pt * 2;
  57464. this._positions32[idx] = this._camera.position.x;
  57465. this._positions32[idx + 1] = this._camera.position.y;
  57466. this._positions32[idx + 2] = this._camera.position.z;
  57467. this._normals32[idx] = 0.0;
  57468. this._normals32[idx + 1] = 0.0;
  57469. this._normals32[idx + 2] = 0.0;
  57470. if (this._computeParticleColor) {
  57471. this._colors32[colidx] = this._particle.color.r;
  57472. this._colors32[colidx + 1] = this._particle.color.g;
  57473. this._colors32[colidx + 2] = this._particle.color.b;
  57474. this._colors32[colidx + 3] = this._particle.color.a;
  57475. }
  57476. if (this._computeParticleTexture) {
  57477. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57478. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57479. }
  57480. }
  57481. }
  57482. // increment indexes for the next particle
  57483. index = idx + 3;
  57484. colorIndex = colidx + 4;
  57485. uvIndex = uvidx + 2;
  57486. }
  57487. // if the VBO must be updated
  57488. if (update) {
  57489. if (this._computeParticleColor) {
  57490. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57491. }
  57492. if (this._computeParticleTexture) {
  57493. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57494. }
  57495. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57496. if (!this.mesh.areNormalsFrozen) {
  57497. if (this._computeParticleVertex) {
  57498. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57499. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  57500. for (var i = 0; i < this._normals32.length; i++) {
  57501. this._fixedNormal32[i] = this._normals32[i];
  57502. }
  57503. }
  57504. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57505. }
  57506. }
  57507. if (this._computeBoundingBox) {
  57508. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57509. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57510. }
  57511. this.afterUpdateParticles(start, end, update);
  57512. };
  57513. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57514. this._halfroll = this._roll * 0.5;
  57515. this._halfpitch = this._pitch * 0.5;
  57516. this._halfyaw = this._yaw * 0.5;
  57517. this._sinRoll = Math.sin(this._halfroll);
  57518. this._cosRoll = Math.cos(this._halfroll);
  57519. this._sinPitch = Math.sin(this._halfpitch);
  57520. this._cosPitch = Math.cos(this._halfpitch);
  57521. this._sinYaw = Math.sin(this._halfyaw);
  57522. this._cosYaw = Math.cos(this._halfyaw);
  57523. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  57524. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  57525. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  57526. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  57527. };
  57528. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  57529. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  57530. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  57531. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  57532. this._rotMatrix.m[3] = 0;
  57533. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  57534. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  57535. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  57536. this._rotMatrix.m[7] = 0;
  57537. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  57538. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  57539. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  57540. this._rotMatrix.m[11] = 0;
  57541. this._rotMatrix.m[12] = 0;
  57542. this._rotMatrix.m[13] = 0;
  57543. this._rotMatrix.m[14] = 0;
  57544. this._rotMatrix.m[15] = 1.0;
  57545. };
  57546. /**
  57547. * Disposes the SPS
  57548. */
  57549. SolidParticleSystem.prototype.dispose = function () {
  57550. this.mesh.dispose();
  57551. this.vars = null;
  57552. // drop references to internal big arrays for the GC
  57553. this._positions = null;
  57554. this._indices = null;
  57555. this._normals = null;
  57556. this._uvs = null;
  57557. this._colors = null;
  57558. this._positions32 = null;
  57559. this._normals32 = null;
  57560. this._fixedNormal32 = null;
  57561. this._uvs32 = null;
  57562. this._colors32 = null;
  57563. this.pickedParticles = null;
  57564. };
  57565. /**
  57566. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  57567. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57568. */
  57569. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  57570. if (!this._isVisibilityBoxLocked) {
  57571. this.mesh.refreshBoundingInfo();
  57572. }
  57573. };
  57574. /**
  57575. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  57576. * @param size the size (float) of the visibility box
  57577. * note : this doesn't lock the SPS mesh bounding box.
  57578. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57579. */
  57580. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  57581. var vis = size / 2;
  57582. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  57583. };
  57584. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  57585. // getter and setter
  57586. get: function () {
  57587. return this._alwaysVisible;
  57588. },
  57589. /**
  57590. * Sets the SPS as always visible or not
  57591. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57592. */
  57593. set: function (val) {
  57594. this._alwaysVisible = val;
  57595. this.mesh.alwaysSelectAsActiveMesh = val;
  57596. },
  57597. enumerable: true,
  57598. configurable: true
  57599. });
  57600. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  57601. get: function () {
  57602. return this._isVisibilityBoxLocked;
  57603. },
  57604. /**
  57605. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57606. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57607. */
  57608. set: function (val) {
  57609. this._isVisibilityBoxLocked = val;
  57610. this.mesh.getBoundingInfo().isLocked = val;
  57611. },
  57612. enumerable: true,
  57613. configurable: true
  57614. });
  57615. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  57616. // getters
  57617. get: function () {
  57618. return this._computeParticleRotation;
  57619. },
  57620. // Optimizer setters
  57621. /**
  57622. * Tells to `setParticles()` to compute the particle rotations or not.
  57623. * Default value : true. The SPS is faster when it's set to false.
  57624. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57625. */
  57626. set: function (val) {
  57627. this._computeParticleRotation = val;
  57628. },
  57629. enumerable: true,
  57630. configurable: true
  57631. });
  57632. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  57633. get: function () {
  57634. return this._computeParticleColor;
  57635. },
  57636. /**
  57637. * Tells to `setParticles()` to compute the particle colors or not.
  57638. * Default value : true. The SPS is faster when it's set to false.
  57639. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57640. */
  57641. set: function (val) {
  57642. this._computeParticleColor = val;
  57643. },
  57644. enumerable: true,
  57645. configurable: true
  57646. });
  57647. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  57648. get: function () {
  57649. return this._computeParticleTexture;
  57650. },
  57651. /**
  57652. * Tells to `setParticles()` to compute the particle textures or not.
  57653. * Default value : true. The SPS is faster when it's set to false.
  57654. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  57655. */
  57656. set: function (val) {
  57657. this._computeParticleTexture = val;
  57658. },
  57659. enumerable: true,
  57660. configurable: true
  57661. });
  57662. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  57663. get: function () {
  57664. return this._computeParticleVertex;
  57665. },
  57666. /**
  57667. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  57668. * Default value : false. The SPS is faster when it's set to false.
  57669. * Note : the particle custom vertex positions aren't stored values.
  57670. */
  57671. set: function (val) {
  57672. this._computeParticleVertex = val;
  57673. },
  57674. enumerable: true,
  57675. configurable: true
  57676. });
  57677. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  57678. get: function () {
  57679. return this._computeBoundingBox;
  57680. },
  57681. /**
  57682. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  57683. */
  57684. set: function (val) {
  57685. this._computeBoundingBox = val;
  57686. },
  57687. enumerable: true,
  57688. configurable: true
  57689. });
  57690. // =======================================================================
  57691. // Particle behavior logic
  57692. // these following methods may be overwritten by the user to fit his needs
  57693. /**
  57694. * This function does nothing. It may be overwritten to set all the particle first values.
  57695. * The SPS doesn't call this function, you may have to call it by your own.
  57696. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57697. */
  57698. SolidParticleSystem.prototype.initParticles = function () {
  57699. };
  57700. /**
  57701. * This function does nothing. It may be overwritten to recycle a particle.
  57702. * The SPS doesn't call this function, you may have to call it by your own.
  57703. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57704. */
  57705. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  57706. return particle;
  57707. };
  57708. /**
  57709. * Updates a particle : this function should be overwritten by the user.
  57710. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  57711. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57712. * ex : just set a particle position or velocity and recycle conditions
  57713. */
  57714. SolidParticleSystem.prototype.updateParticle = function (particle) {
  57715. return particle;
  57716. };
  57717. /**
  57718. * Updates a vertex of a particle : it can be overwritten by the user.
  57719. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  57720. * @param particle the current particle
  57721. * @param vertex the current index of the current particle
  57722. * @param pt the index of the current vertex in the particle shape
  57723. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  57724. * ex : just set a vertex particle position
  57725. */
  57726. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  57727. return vertex;
  57728. };
  57729. /**
  57730. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  57731. * This does nothing and may be overwritten by the user.
  57732. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57733. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57734. * @param update the boolean update value actually passed to setParticles()
  57735. */
  57736. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  57737. };
  57738. /**
  57739. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  57740. * This will be passed three parameters.
  57741. * This does nothing and may be overwritten by the user.
  57742. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57743. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57744. * @param update the boolean update value actually passed to setParticles()
  57745. */
  57746. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  57747. };
  57748. return SolidParticleSystem;
  57749. })();
  57750. BABYLON.SolidParticleSystem = SolidParticleSystem;
  57751. })(BABYLON || (BABYLON = {}));
  57752. var BABYLON;
  57753. (function (BABYLON) {
  57754. var Internals;
  57755. (function (Internals) {
  57756. var FileFaceOrientation = (function () {
  57757. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  57758. this.name = name;
  57759. this.worldAxisForNormal = worldAxisForNormal;
  57760. this.worldAxisForFileX = worldAxisForFileX;
  57761. this.worldAxisForFileY = worldAxisForFileY;
  57762. }
  57763. return FileFaceOrientation;
  57764. })();
  57765. ;
  57766. /**
  57767. * Helper class dealing with the extraction of spherical polynomial dataArray
  57768. * from a cube map.
  57769. */
  57770. var CubeMapToSphericalPolynomialTools = (function () {
  57771. function CubeMapToSphericalPolynomialTools() {
  57772. }
  57773. /**
  57774. * Converts a cubemap to the according Spherical Polynomial data.
  57775. * This extracts the first 3 orders only as they are the only one used in the lighting.
  57776. *
  57777. * @param cubeInfo The Cube map to extract the information from.
  57778. * @return The Spherical Polynomial data.
  57779. */
  57780. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  57781. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  57782. var totalSolidAngle = 0.0;
  57783. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  57784. var du = 2.0 / cubeInfo.size;
  57785. var dv = du;
  57786. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  57787. var minUV = du * 0.5 - 1.0;
  57788. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57789. var fileFace = this.FileFaces[faceIndex];
  57790. var dataArray = cubeInfo[fileFace.name];
  57791. var v = minUV;
  57792. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  57793. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  57794. // Because SP is still linear, so summation is fine in that basis.
  57795. for (var y = 0; y < cubeInfo.size; y++) {
  57796. var u = minUV;
  57797. for (var x = 0; x < cubeInfo.size; x++) {
  57798. // World direction (not normalised)
  57799. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  57800. worldDirection.normalize();
  57801. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  57802. if (1) {
  57803. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  57804. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  57805. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  57806. var color = new BABYLON.Color3(r, g, b);
  57807. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  57808. }
  57809. else {
  57810. if (faceIndex == 0) {
  57811. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57812. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57813. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57814. }
  57815. else if (faceIndex == 1) {
  57816. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57817. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57818. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57819. }
  57820. else if (faceIndex == 2) {
  57821. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57822. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57823. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57824. }
  57825. else if (faceIndex == 3) {
  57826. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57827. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57828. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57829. }
  57830. else if (faceIndex == 4) {
  57831. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57832. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57833. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57834. }
  57835. else if (faceIndex == 5) {
  57836. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57837. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57838. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57839. }
  57840. 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]);
  57841. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  57842. }
  57843. totalSolidAngle += deltaSolidAngle;
  57844. u += du;
  57845. }
  57846. v += dv;
  57847. }
  57848. }
  57849. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  57850. var correction = correctSolidAngle / totalSolidAngle;
  57851. sphericalHarmonics.scale(correction);
  57852. // Additionally scale by pi -- audit needed
  57853. sphericalHarmonics.scale(1.0 / Math.PI);
  57854. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  57855. };
  57856. CubeMapToSphericalPolynomialTools.FileFaces = [
  57857. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  57858. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  57859. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  57860. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  57861. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  57862. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  57863. ];
  57864. return CubeMapToSphericalPolynomialTools;
  57865. })();
  57866. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  57867. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57868. })(BABYLON || (BABYLON = {}));
  57869. var BABYLON;
  57870. (function (BABYLON) {
  57871. var Internals;
  57872. (function (Internals) {
  57873. /**
  57874. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  57875. */
  57876. var PanoramaToCubeMapTools = (function () {
  57877. function PanoramaToCubeMapTools() {
  57878. }
  57879. /**
  57880. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  57881. *
  57882. * @param float32Array The source data.
  57883. * @param inputWidth The width of the input panorama.
  57884. * @param inputhHeight The height of the input panorama.
  57885. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  57886. * @return The cubemap data
  57887. */
  57888. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  57889. if (!float32Array) {
  57890. throw "ConvertPanoramaToCubemap: input cannot be null";
  57891. }
  57892. if (float32Array.length != inputWidth * inputHeight * 3) {
  57893. throw "ConvertPanoramaToCubemap: input size is wrong";
  57894. }
  57895. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  57896. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  57897. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  57898. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  57899. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  57900. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  57901. return {
  57902. front: textureFront,
  57903. back: textureBack,
  57904. left: textureLeft,
  57905. right: textureRight,
  57906. up: textureUp,
  57907. down: textureDown,
  57908. size: size
  57909. };
  57910. };
  57911. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  57912. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  57913. var textureArray = new Float32Array(buffer);
  57914. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  57915. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  57916. var dy = 1 / texSize;
  57917. var fy = 0;
  57918. for (var y = 0; y < texSize; y++) {
  57919. var xv1 = faceData[0];
  57920. var xv2 = faceData[2];
  57921. for (var x = 0; x < texSize; x++) {
  57922. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  57923. v.normalize();
  57924. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  57925. // 3 channels per pixels
  57926. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  57927. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  57928. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  57929. xv1 = xv1.add(rotDX1);
  57930. xv2 = xv2.add(rotDX2);
  57931. }
  57932. fy += dy;
  57933. }
  57934. return textureArray;
  57935. };
  57936. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  57937. var theta = Math.atan2(vDir.z, vDir.x);
  57938. var phi = Math.acos(vDir.y);
  57939. while (theta < -Math.PI)
  57940. theta += 2 * Math.PI;
  57941. while (theta > Math.PI)
  57942. theta -= 2 * Math.PI;
  57943. var dx = theta / Math.PI;
  57944. var dy = phi / Math.PI;
  57945. // recenter.
  57946. dx = dx * 0.5 + 0.5;
  57947. var px = Math.round(dx * inputWidth);
  57948. if (px < 0)
  57949. px = 0;
  57950. else if (px >= inputWidth)
  57951. px = inputWidth - 1;
  57952. var py = Math.round(dy * inputHeight);
  57953. if (py < 0)
  57954. py = 0;
  57955. else if (py >= inputHeight)
  57956. py = inputHeight - 1;
  57957. var inputY = (inputHeight - py - 1);
  57958. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  57959. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  57960. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  57961. return {
  57962. r: r,
  57963. g: g,
  57964. b: b
  57965. };
  57966. };
  57967. PanoramaToCubeMapTools.FACE_FRONT = [
  57968. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57969. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57970. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57971. new BABYLON.Vector3(1.0, 1.0, -1.0)
  57972. ];
  57973. PanoramaToCubeMapTools.FACE_BACK = [
  57974. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57975. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57976. new BABYLON.Vector3(1.0, 1.0, 1.0),
  57977. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  57978. ];
  57979. PanoramaToCubeMapTools.FACE_RIGHT = [
  57980. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57981. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57982. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57983. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57984. ];
  57985. PanoramaToCubeMapTools.FACE_LEFT = [
  57986. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57987. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57988. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57989. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  57990. ];
  57991. PanoramaToCubeMapTools.FACE_DOWN = [
  57992. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57993. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57994. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57995. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57996. ];
  57997. PanoramaToCubeMapTools.FACE_UP = [
  57998. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57999. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58000. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58001. new BABYLON.Vector3(1.0, -1.0, -1.0)
  58002. ];
  58003. return PanoramaToCubeMapTools;
  58004. })();
  58005. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  58006. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58007. })(BABYLON || (BABYLON = {}));
  58008. var BABYLON;
  58009. (function (BABYLON) {
  58010. var Internals;
  58011. (function (Internals) {
  58012. ;
  58013. /**
  58014. * This groups tools to convert HDR texture to native colors array.
  58015. */
  58016. var HDRTools = (function () {
  58017. function HDRTools() {
  58018. }
  58019. HDRTools.Ldexp = function (mantissa, exponent) {
  58020. if (exponent > 1023) {
  58021. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  58022. }
  58023. if (exponent < -1074) {
  58024. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  58025. }
  58026. return mantissa * Math.pow(2, exponent);
  58027. };
  58028. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  58029. if (exponent > 0) {
  58030. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  58031. float32array[index + 0] = red * exponent;
  58032. float32array[index + 1] = green * exponent;
  58033. float32array[index + 2] = blue * exponent;
  58034. }
  58035. else {
  58036. float32array[index + 0] = 0;
  58037. float32array[index + 1] = 0;
  58038. float32array[index + 2] = 0;
  58039. }
  58040. };
  58041. HDRTools.readStringLine = function (uint8array, startIndex) {
  58042. var line = "";
  58043. var character = "";
  58044. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  58045. character = String.fromCharCode(uint8array[i]);
  58046. if (character == "\n") {
  58047. break;
  58048. }
  58049. line += character;
  58050. }
  58051. return line;
  58052. };
  58053. /**
  58054. * Reads header information from an RGBE texture stored in a native array.
  58055. * More information on this format are available here:
  58056. * https://en.wikipedia.org/wiki/RGBE_image_format
  58057. *
  58058. * @param uint8array The binary file stored in native array.
  58059. * @return The header information.
  58060. */
  58061. HDRTools.RGBE_ReadHeader = function (uint8array) {
  58062. var height = 0;
  58063. var width = 0;
  58064. var line = this.readStringLine(uint8array, 0);
  58065. if (line[0] != '#' || line[1] != '?') {
  58066. throw "Bad HDR Format.";
  58067. }
  58068. var endOfHeader = false;
  58069. var findFormat = false;
  58070. var lineIndex = 0;
  58071. do {
  58072. lineIndex += (line.length + 1);
  58073. line = this.readStringLine(uint8array, lineIndex);
  58074. if (line == "FORMAT=32-bit_rle_rgbe") {
  58075. findFormat = true;
  58076. }
  58077. else if (line.length == 0) {
  58078. endOfHeader = true;
  58079. }
  58080. } while (!endOfHeader);
  58081. if (!findFormat) {
  58082. throw "HDR Bad header format, unsupported FORMAT";
  58083. }
  58084. lineIndex += (line.length + 1);
  58085. line = this.readStringLine(uint8array, lineIndex);
  58086. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  58087. var match = sizeRegexp.exec(line);
  58088. // TODO. Support +Y and -X if needed.
  58089. if (match.length < 3) {
  58090. throw "HDR Bad header format, no size";
  58091. }
  58092. width = parseInt(match[2]);
  58093. height = parseInt(match[1]);
  58094. if (width < 8 || width > 0x7fff) {
  58095. throw "HDR Bad header format, unsupported size";
  58096. }
  58097. lineIndex += (line.length + 1);
  58098. return {
  58099. height: height,
  58100. width: width,
  58101. dataPosition: lineIndex
  58102. };
  58103. };
  58104. /**
  58105. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  58106. * This RGBE texture needs to store the information as a panorama.
  58107. *
  58108. * More information on this format are available here:
  58109. * https://en.wikipedia.org/wiki/RGBE_image_format
  58110. *
  58111. * @param buffer The binary file stored in an array buffer.
  58112. * @param size The expected size of the extracted cubemap.
  58113. * @return The Cube Map information.
  58114. */
  58115. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  58116. var uint8array = new Uint8Array(buffer);
  58117. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  58118. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58119. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  58120. return cubeMapData;
  58121. };
  58122. /**
  58123. * Returns the pixels data extracted from an RGBE texture.
  58124. * This pixels will be stored left to right up to down in the R G B order in one array.
  58125. *
  58126. * More information on this format are available here:
  58127. * https://en.wikipedia.org/wiki/RGBE_image_format
  58128. *
  58129. * @param uint8array The binary file stored in an array buffer.
  58130. * @param hdrInfo The header information of the file.
  58131. * @return The pixels data in RGB right to left up to down order.
  58132. */
  58133. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  58134. // Keep for multi format supports.
  58135. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58136. };
  58137. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  58138. var num_scanlines = hdrInfo.height;
  58139. var scanline_width = hdrInfo.width;
  58140. var a, b, c, d, count;
  58141. var dataIndex = hdrInfo.dataPosition;
  58142. var index = 0, endIndex = 0, i = 0;
  58143. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  58144. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  58145. // 3 channels of 4 bytes per pixel in float.
  58146. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  58147. var resultArray = new Float32Array(resultBuffer);
  58148. // read in each successive scanline
  58149. while (num_scanlines > 0) {
  58150. a = uint8array[dataIndex++];
  58151. b = uint8array[dataIndex++];
  58152. c = uint8array[dataIndex++];
  58153. d = uint8array[dataIndex++];
  58154. if (a != 2 || b != 2 || (c & 0x80)) {
  58155. // this file is not run length encoded
  58156. throw "HDR Bad header format, not RLE";
  58157. }
  58158. if (((c << 8) | d) != scanline_width) {
  58159. throw "HDR Bad header format, wrong scan line width";
  58160. }
  58161. index = 0;
  58162. // read each of the four channels for the scanline into the buffer
  58163. for (i = 0; i < 4; i++) {
  58164. endIndex = (i + 1) * scanline_width;
  58165. while (index < endIndex) {
  58166. a = uint8array[dataIndex++];
  58167. b = uint8array[dataIndex++];
  58168. if (a > 128) {
  58169. // a run of the same value
  58170. count = a - 128;
  58171. if ((count == 0) || (count > endIndex - index)) {
  58172. throw "HDR Bad Format, bad scanline data (run)";
  58173. }
  58174. while (count-- > 0) {
  58175. scanLineArray[index++] = b;
  58176. }
  58177. }
  58178. else {
  58179. // a non-run
  58180. count = a;
  58181. if ((count == 0) || (count > endIndex - index)) {
  58182. throw "HDR Bad Format, bad scanline data (non-run)";
  58183. }
  58184. scanLineArray[index++] = b;
  58185. if (--count > 0) {
  58186. for (var j = 0; j < count; j++) {
  58187. scanLineArray[index++] = uint8array[dataIndex++];
  58188. }
  58189. }
  58190. }
  58191. }
  58192. }
  58193. // now convert data from buffer into floats
  58194. for (i = 0; i < scanline_width; i++) {
  58195. a = scanLineArray[i];
  58196. b = scanLineArray[i + scanline_width];
  58197. c = scanLineArray[i + 2 * scanline_width];
  58198. d = scanLineArray[i + 3 * scanline_width];
  58199. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  58200. }
  58201. num_scanlines--;
  58202. }
  58203. return resultArray;
  58204. };
  58205. return HDRTools;
  58206. })();
  58207. Internals.HDRTools = HDRTools;
  58208. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58209. })(BABYLON || (BABYLON = {}));
  58210. //_______________________________________________________________
  58211. // Extracted from CubeMapGen:
  58212. // https://code.google.com/archive/p/cubemapgen/
  58213. //
  58214. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  58215. //_______________________________________________________________
  58216. var BABYLON;
  58217. (function (BABYLON) {
  58218. var Internals;
  58219. (function (Internals) {
  58220. /**
  58221. * The bounding box information used during the conversion process.
  58222. */
  58223. var CMGBoundinBox = (function () {
  58224. function CMGBoundinBox() {
  58225. this.min = new BABYLON.Vector3(0, 0, 0);
  58226. this.max = new BABYLON.Vector3(0, 0, 0);
  58227. this.clear();
  58228. }
  58229. CMGBoundinBox.prototype.clear = function () {
  58230. this.min.x = CMGBoundinBox.MAX;
  58231. this.min.y = CMGBoundinBox.MAX;
  58232. this.min.z = CMGBoundinBox.MAX;
  58233. this.max.x = CMGBoundinBox.MIN;
  58234. this.max.y = CMGBoundinBox.MIN;
  58235. this.max.z = CMGBoundinBox.MIN;
  58236. };
  58237. CMGBoundinBox.prototype.augment = function (x, y, z) {
  58238. this.min.x = Math.min(this.min.x, x);
  58239. this.min.y = Math.min(this.min.y, y);
  58240. this.min.z = Math.min(this.min.z, z);
  58241. this.max.x = Math.max(this.max.x, x);
  58242. this.max.y = Math.max(this.max.y, y);
  58243. this.max.z = Math.max(this.max.z, z);
  58244. };
  58245. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  58246. this.min.x = Math.max(this.min.x, x);
  58247. this.min.y = Math.max(this.min.y, y);
  58248. this.min.z = Math.max(this.min.z, z);
  58249. };
  58250. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  58251. this.max.x = Math.min(this.max.x, x);
  58252. this.max.y = Math.min(this.max.y, y);
  58253. this.max.z = Math.min(this.max.z, z);
  58254. };
  58255. CMGBoundinBox.prototype.empty = function () {
  58256. if ((this.min.x > this.max.y) ||
  58257. (this.min.y > this.max.y) ||
  58258. (this.min.z > this.max.y)) {
  58259. return true;
  58260. }
  58261. else {
  58262. return false;
  58263. }
  58264. };
  58265. CMGBoundinBox.MAX = Number.MAX_VALUE;
  58266. CMGBoundinBox.MIN = Number.MIN_VALUE;
  58267. return CMGBoundinBox;
  58268. })();
  58269. /**
  58270. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  58271. * required by the glossinees of a material.
  58272. *
  58273. * This only supports the cosine drop power as well as Warp fixup generation method.
  58274. *
  58275. * This is using the process from CubeMapGen described here:
  58276. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  58277. */
  58278. var PMREMGenerator = (function () {
  58279. /**
  58280. * Constructor of the generator.
  58281. *
  58282. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  58283. * @param inputSize The size of the cubemap faces
  58284. * @param outputSize The size of the output cubemap faces
  58285. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  58286. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  58287. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  58288. * @param specularPower The max specular level of the desired cubemap
  58289. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  58290. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  58291. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  58292. */
  58293. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  58294. this.input = input;
  58295. this.inputSize = inputSize;
  58296. this.outputSize = outputSize;
  58297. this.maxNumMipLevels = maxNumMipLevels;
  58298. this.numChannels = numChannels;
  58299. this.isFloat = isFloat;
  58300. this.specularPower = specularPower;
  58301. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  58302. this.excludeBase = excludeBase;
  58303. this.fixup = fixup;
  58304. this._outputSurface = [];
  58305. this._numMipLevels = 0;
  58306. }
  58307. /**
  58308. * Launches the filter process and return the result.
  58309. *
  58310. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  58311. */
  58312. PMREMGenerator.prototype.filterCubeMap = function () {
  58313. // Init cubemap processor
  58314. this.init();
  58315. // Filters the cubemap
  58316. this.filterCubeMapMipChain();
  58317. // Returns the filtered mips.
  58318. return this._outputSurface;
  58319. };
  58320. PMREMGenerator.prototype.init = function () {
  58321. var i;
  58322. var j;
  58323. var mipLevelSize;
  58324. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  58325. if (this.maxNumMipLevels == 0) {
  58326. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  58327. }
  58328. //first miplevel size
  58329. mipLevelSize = this.outputSize;
  58330. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  58331. for (j = 0; j < this.maxNumMipLevels; j++) {
  58332. this._outputSurface.length++;
  58333. this._outputSurface[j] = [];
  58334. //Iterate over faces for output images
  58335. for (i = 0; i < 6; i++) {
  58336. this._outputSurface[j].length++;
  58337. // Initializes a new array for the output.
  58338. if (this.isFloat) {
  58339. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  58340. }
  58341. else {
  58342. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  58343. }
  58344. }
  58345. //next mip level is half size
  58346. mipLevelSize >>= 1;
  58347. this._numMipLevels++;
  58348. //terminate if mip chain becomes too small
  58349. if (mipLevelSize == 0) {
  58350. this.maxNumMipLevels = j;
  58351. return;
  58352. }
  58353. }
  58354. };
  58355. //--------------------------------------------------------------------------------------
  58356. //Cube map filtering and mip chain generation.
  58357. // the cube map filtereing is specified using a number of parameters:
  58358. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  58359. // indicates the region of the hemisphere to filter over for each tap.
  58360. //
  58361. // Note that the top mip level is also a filtered version of the original input images
  58362. // as well in order to create mip chains for diffuse environment illumination.
  58363. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  58364. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  58365. //
  58366. // Then the mip angle used to genreate the next level of the mip chain from the first level
  58367. // is a_InitialMipAngle
  58368. //
  58369. // The angle for the subsequent levels of the mip chain are specified by their parents
  58370. // filtering angle and a per-level scale and bias
  58371. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  58372. //
  58373. //--------------------------------------------------------------------------------------
  58374. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  58375. // First, take count of the lighting model to modify SpecularPower
  58376. // 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;
  58377. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  58378. //Cone angle start (for generating subsequent mip levels)
  58379. var currentSpecularPower = this.specularPower;
  58380. //Build filter lookup tables based on the source miplevel size
  58381. this.precomputeFilterLookupTables(this.inputSize);
  58382. // Note that we need to filter the first level before generating mipmap
  58383. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  58384. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  58385. // TODO : Write a function to copy and scale the base mipmap in output
  58386. // I am just lazy here and just put a high specular power value, and do some if.
  58387. if (this.excludeBase && (levelIndex == 0)) {
  58388. // 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).
  58389. currentSpecularPower = 100000.0;
  58390. }
  58391. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  58392. var srcCubeImage = this.input;
  58393. var dstCubeImage = this._outputSurface[levelIndex];
  58394. var dstSize = this.outputSize >> levelIndex;
  58395. // Compute required angle.
  58396. var angle = this.getBaseFilterAngle(currentSpecularPower);
  58397. // filter cube surfaces
  58398. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  58399. // fix seams
  58400. if (this.fixup) {
  58401. this.fixupCubeEdges(dstCubeImage, dstSize);
  58402. }
  58403. // Decrease the specular power to generate the mipmap chain
  58404. // TODO : Use another method for Exclude (see first comment at start of the function
  58405. if (this.excludeBase && (levelIndex == 0)) {
  58406. currentSpecularPower = this.specularPower;
  58407. }
  58408. currentSpecularPower *= this.cosinePowerDropPerMip;
  58409. }
  58410. };
  58411. //--------------------------------------------------------------------------------------
  58412. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  58413. // It allow to optimize the texel to access base on the specular power.
  58414. //--------------------------------------------------------------------------------------
  58415. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  58416. // We want to find the alpha such that:
  58417. // cos(alpha)^cosinePower = epsilon
  58418. // That's: acos(epsilon^(1/cosinePower))
  58419. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  58420. var angle = 180.0;
  58421. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  58422. angle *= 180.0 / Math.PI; // Convert to degree
  58423. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  58424. return angle;
  58425. };
  58426. //--------------------------------------------------------------------------------------
  58427. //Builds the following lookup tables prior to filtering:
  58428. // -normalizer cube map
  58429. // -tap weight lookup table
  58430. //
  58431. //--------------------------------------------------------------------------------------
  58432. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  58433. var srcTexelAngle;
  58434. var iCubeFace;
  58435. //clear pre-existing normalizer cube map
  58436. this._normCubeMap = [];
  58437. //Normalized vectors per cubeface and per-texel solid angle
  58438. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  58439. };
  58440. //--------------------------------------------------------------------------------------
  58441. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  58442. //
  58443. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  58444. //
  58445. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  58446. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  58447. // below
  58448. //--------------------------------------------------------------------------------------
  58449. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  58450. var iCubeFace;
  58451. var u;
  58452. var v;
  58453. //iterate over cube faces
  58454. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58455. //First three channels for norm cube, and last channel for solid angle
  58456. this._normCubeMap.push(new Float32Array(size * size * 4));
  58457. //fast texture walk, build normalizer cube map
  58458. var facesData = this.input[iCubeFace];
  58459. for (v = 0; v < size; v++) {
  58460. for (u = 0; u < size; u++) {
  58461. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  58462. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  58463. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  58464. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  58465. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  58466. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  58467. }
  58468. }
  58469. }
  58470. };
  58471. //--------------------------------------------------------------------------------------
  58472. // Convert cubemap face texel coordinates and face idx to 3D vector
  58473. // note the U and V coords are integer coords and range from 0 to size-1
  58474. // this routine can be used to generate a normalizer cube map
  58475. //--------------------------------------------------------------------------------------
  58476. // SL BEGIN
  58477. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  58478. var nvcU;
  58479. var nvcV;
  58480. var tempVec;
  58481. // Change from original AMD code
  58482. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  58483. // + 0.5f is for texel center addressing
  58484. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  58485. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  58486. // warp fixup
  58487. if (fixup && size > 1) {
  58488. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  58489. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  58490. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  58491. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  58492. }
  58493. // Get current vector
  58494. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  58495. // U contribution
  58496. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  58497. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  58498. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  58499. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  58500. // V contribution and Sum
  58501. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  58502. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  58503. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  58504. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  58505. //add face axis
  58506. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  58507. PMREMGenerator._vectorTemp.x += faceAxis[0];
  58508. PMREMGenerator._vectorTemp.y += faceAxis[1];
  58509. PMREMGenerator._vectorTemp.z += faceAxis[2];
  58510. //normalize vector
  58511. PMREMGenerator._vectorTemp.normalize();
  58512. return PMREMGenerator._vectorTemp;
  58513. };
  58514. //--------------------------------------------------------------------------------------
  58515. // Convert 3D vector to cubemap face texel coordinates and face idx
  58516. // note the U and V coords are integer coords and range from 0 to size-1
  58517. // this routine can be used to generate a normalizer cube map
  58518. //
  58519. // returns face IDX and texel coords
  58520. //--------------------------------------------------------------------------------------
  58521. // SL BEGIN
  58522. /*
  58523. Mapping Texture Coordinates to Cube Map Faces
  58524. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  58525. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  58526. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  58527. map arrangement in Pixar's RenderMan package.
  58528. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  58529. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  58530. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  58531. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  58532. the major axis direction). The target column in the table below explains how the major axis direction
  58533. maps to the 2D image of a particular cube map target.
  58534. major axis
  58535. direction target sc tc ma
  58536. ---------- --------------------------------- --- --- ---
  58537. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  58538. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  58539. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  58540. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  58541. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  58542. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  58543. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  58544. an updated (s,t) is calculated as follows
  58545. s = ( sc/|ma| + 1 ) / 2
  58546. t = ( tc/|ma| + 1 ) / 2
  58547. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  58548. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  58549. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  58550. */
  58551. // Note this method return U and V in range from 0 to size-1
  58552. // SL END
  58553. // Store the information in vector3 for convenience (faceindex, u, v)
  58554. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  58555. var maxCoord;
  58556. var faceIdx;
  58557. //absolute value 3
  58558. var absX = Math.abs(x);
  58559. var absY = Math.abs(y);
  58560. var absZ = Math.abs(z);
  58561. if (absX >= absY && absX >= absZ) {
  58562. maxCoord = absX;
  58563. if (x >= 0) {
  58564. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  58565. }
  58566. else {
  58567. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  58568. }
  58569. }
  58570. else if (absY >= absX && absY >= absZ) {
  58571. maxCoord = absY;
  58572. if (y >= 0) {
  58573. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  58574. }
  58575. else {
  58576. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  58577. }
  58578. }
  58579. else {
  58580. maxCoord = absZ;
  58581. if (z >= 0) {
  58582. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  58583. }
  58584. else {
  58585. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  58586. }
  58587. }
  58588. //divide through by max coord so face vector lies on cube face
  58589. var scale = 1 / maxCoord;
  58590. x *= scale;
  58591. y *= scale;
  58592. z *= scale;
  58593. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  58594. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  58595. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  58596. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  58597. // Modify original AMD code to return value from 0 to Size - 1
  58598. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  58599. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  58600. PMREMGenerator._vectorTemp.x = faceIdx;
  58601. PMREMGenerator._vectorTemp.y = u;
  58602. PMREMGenerator._vectorTemp.z = v;
  58603. return PMREMGenerator._vectorTemp;
  58604. };
  58605. //--------------------------------------------------------------------------------------
  58606. //Original code from Ignacio CastaÒo
  58607. // This formula is from Manne ÷hrstrˆm's thesis.
  58608. // Take two coordiantes in the range [-1, 1] that define a portion of a
  58609. // cube face and return the area of the projection of that portion on the
  58610. // surface of the sphere.
  58611. //--------------------------------------------------------------------------------------
  58612. PMREMGenerator.prototype.areaElement = function (x, y) {
  58613. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  58614. };
  58615. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  58616. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  58617. // (+ 0.5f is for texel center addressing)
  58618. u = (2.0 * (u + 0.5) / size) - 1.0;
  58619. v = (2.0 * (v + 0.5) / size) - 1.0;
  58620. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  58621. var invResolution = 1.0 / size;
  58622. // U and V are the -1..1 texture coordinate on the current face.
  58623. // Get projected area for this texel
  58624. var x0 = u - invResolution;
  58625. var y0 = v - invResolution;
  58626. var x1 = u + invResolution;
  58627. var y1 = v + invResolution;
  58628. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  58629. return solidAngle;
  58630. };
  58631. //--------------------------------------------------------------------------------------
  58632. //The key to the speed of these filtering routines is to quickly define a per-face
  58633. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  58634. // Later these pixels are selectively processed based on their dot products to see if
  58635. // they reside within the filtering cone.
  58636. //
  58637. //This is done by computing the smallest per-texel angle to get a conservative estimate
  58638. // of the number of texels needed to be covered in width and height order to filter the
  58639. // region. the bounding box for the center taps face is defined first, and if the
  58640. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  58641. // defined next
  58642. //--------------------------------------------------------------------------------------
  58643. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  58644. // note that pixels within these regions may be rejected
  58645. // based on the anlge
  58646. var iCubeFace;
  58647. var u;
  58648. var v;
  58649. // bounding box per face to specify region to process
  58650. var filterExtents = [];
  58651. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58652. filterExtents.push(new CMGBoundinBox());
  58653. }
  58654. // min angle a src texel can cover (in degrees)
  58655. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  58656. // angle about center tap to define filter cone
  58657. // filter angle is 1/2 the cone angle
  58658. var filterAngle = filterConeAngle / 2.0;
  58659. //ensure filter angle is larger than a texel
  58660. if (filterAngle < srcTexelAngle) {
  58661. filterAngle = srcTexelAngle;
  58662. }
  58663. //ensure filter cone is always smaller than the hemisphere
  58664. if (filterAngle > 90.0) {
  58665. filterAngle = 90.0;
  58666. }
  58667. // the maximum number of texels in 1D the filter cone angle will cover
  58668. // used to determine bounding box size for filter extents
  58669. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  58670. // ensure conservative region always covers at least one texel
  58671. if (filterSize < 1) {
  58672. filterSize = 1;
  58673. }
  58674. // dotProdThresh threshold based on cone angle to determine whether or not taps
  58675. // reside within the cone angle
  58676. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  58677. // process required faces
  58678. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58679. //iterate over dst cube map face texel
  58680. for (v = 0; v < dstSize; v++) {
  58681. for (u = 0; u < dstSize; u++) {
  58682. //get center tap direction
  58683. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  58684. //clear old per-face filter extents
  58685. this.clearFilterExtents(filterExtents);
  58686. //define per-face filter extents
  58687. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  58688. //perform filtering of src faces using filter extents
  58689. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  58690. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  58691. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  58692. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  58693. }
  58694. }
  58695. }
  58696. };
  58697. //--------------------------------------------------------------------------------------
  58698. //Clear filter extents for the 6 cube map faces
  58699. //--------------------------------------------------------------------------------------
  58700. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  58701. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  58702. filterExtents[iCubeFaces].clear();
  58703. }
  58704. };
  58705. //--------------------------------------------------------------------------------------
  58706. //Define per-face bounding box filter extents
  58707. //
  58708. // These define conservative texel regions in each of the faces the filter can possibly
  58709. // process. When the pixels in the regions are actually processed, the dot product
  58710. // between the tap vector and the center tap vector is used to determine the weight of
  58711. // the tap and whether or not the tap is within the cone.
  58712. //
  58713. //--------------------------------------------------------------------------------------
  58714. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  58715. //neighboring face and bleed over amount, and width of BBOX for
  58716. // left, right, top, and bottom edges of this face
  58717. var bleedOverAmount = [0, 0, 0, 0];
  58718. var bleedOverBBoxMin = [0, 0, 0, 0];
  58719. var bleedOverBBoxMax = [0, 0, 0, 0];
  58720. var neighborFace;
  58721. var neighborEdge;
  58722. var oppositeFaceIdx;
  58723. //get face idx, and u, v info from center tap dir
  58724. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  58725. var faceIdx = result.x;
  58726. var u = result.y;
  58727. var v = result.z;
  58728. //define bbox size within face
  58729. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  58730. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  58731. filterExtents[faceIdx].clampMin(0, 0, 0);
  58732. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  58733. //u and v extent in face corresponding to center tap
  58734. var minU = filterExtents[faceIdx].min.x;
  58735. var minV = filterExtents[faceIdx].min.y;
  58736. var maxU = filterExtents[faceIdx].max.x;
  58737. var maxV = filterExtents[faceIdx].max.y;
  58738. //bleed over amounts for face across u=0 edge (left)
  58739. bleedOverAmount[0] = (bboxSize - u);
  58740. bleedOverBBoxMin[0] = minV;
  58741. bleedOverBBoxMax[0] = maxV;
  58742. //bleed over amounts for face across u=1 edge (right)
  58743. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  58744. bleedOverBBoxMin[1] = minV;
  58745. bleedOverBBoxMax[1] = maxV;
  58746. //bleed over to face across v=0 edge (up)
  58747. bleedOverAmount[2] = (bboxSize - v);
  58748. bleedOverBBoxMin[2] = minU;
  58749. bleedOverBBoxMax[2] = maxU;
  58750. //bleed over to face across v=1 edge (down)
  58751. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  58752. bleedOverBBoxMin[3] = minU;
  58753. bleedOverBBoxMax[3] = maxU;
  58754. //compute bleed over regions in neighboring faces
  58755. for (var i = 0; i < 4; i++) {
  58756. if (bleedOverAmount[i] > 0) {
  58757. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  58758. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  58759. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  58760. // be flipped: the cases are
  58761. // if a left edge mates with a left or bottom edge on the neighbor
  58762. // if a top edge mates with a top or right edge on the neighbor
  58763. // if a right edge mates with a right or top edge on the neighbor
  58764. // if a bottom edge mates with a bottom or left edge on the neighbor
  58765. //Seeing as the edges are enumerated as follows
  58766. // left =0
  58767. // right =1
  58768. // top =2
  58769. // bottom =3
  58770. //
  58771. // so if the edge enums are the same, or the sum of the enums == 3,
  58772. // the bbox needs to be flipped
  58773. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  58774. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  58775. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  58776. }
  58777. //The way the bounding box is extended onto the neighboring face
  58778. // depends on which edge of neighboring face abuts with this one
  58779. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  58780. case PMREMGenerator.CP_EDGE_LEFT:
  58781. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  58782. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  58783. break;
  58784. case PMREMGenerator.CP_EDGE_RIGHT:
  58785. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  58786. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  58787. break;
  58788. case PMREMGenerator.CP_EDGE_TOP:
  58789. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  58790. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  58791. break;
  58792. case PMREMGenerator.CP_EDGE_BOTTOM:
  58793. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  58794. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  58795. break;
  58796. }
  58797. //clamp filter extents in non-center tap faces to remain within surface
  58798. filterExtents[neighborFace].clampMin(0, 0, 0);
  58799. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  58800. }
  58801. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  58802. // from the center tap face, then process the opposite face entirely for now.
  58803. //Note that the cases in which this happens, what usually happens is that
  58804. // more than one edge bleeds onto the opposite face, and the bounding box
  58805. // encompasses the entire cube map face.
  58806. if (bleedOverAmount[i] > srcSize) {
  58807. //determine opposite face
  58808. switch (faceIdx) {
  58809. case PMREMGenerator.CP_FACE_X_POS:
  58810. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  58811. break;
  58812. case PMREMGenerator.CP_FACE_X_NEG:
  58813. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  58814. break;
  58815. case PMREMGenerator.CP_FACE_Y_POS:
  58816. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  58817. break;
  58818. case PMREMGenerator.CP_FACE_Y_NEG:
  58819. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  58820. break;
  58821. case PMREMGenerator.CP_FACE_Z_POS:
  58822. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  58823. break;
  58824. case PMREMGenerator.CP_FACE_Z_NEG:
  58825. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  58826. break;
  58827. default:
  58828. break;
  58829. }
  58830. //just encompass entire face for now
  58831. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  58832. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  58833. }
  58834. }
  58835. };
  58836. //--------------------------------------------------------------------------------------
  58837. //ProcessFilterExtents
  58838. // Process bounding box in each cube face
  58839. //
  58840. //--------------------------------------------------------------------------------------
  58841. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  58842. //accumulators are 64-bit floats in order to have the precision needed
  58843. // over a summation of a large number of pixels
  58844. var dstAccum = [0, 0, 0, 0];
  58845. var weightAccum = 0;
  58846. var k = 0;
  58847. var nSrcChannels = this.numChannels;
  58848. // norm cube map and srcCubeMap have same face width
  58849. var faceWidth = srcSize;
  58850. //amount to add to pointer to move to next scanline in images
  58851. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  58852. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  58853. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  58854. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  58855. // iterate over cubefaces
  58856. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  58857. //if bbox is non empty
  58858. if (!filterExtents[iFaceIdx].empty()) {
  58859. var uStart = filterExtents[iFaceIdx].min.x;
  58860. var vStart = filterExtents[iFaceIdx].min.y;
  58861. var uEnd = filterExtents[iFaceIdx].max.x;
  58862. var vEnd = filterExtents[iFaceIdx].max.y;
  58863. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  58864. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  58865. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  58866. for (var v = vStart; v <= vEnd; v++) {
  58867. var normCubeRowWalk = 0;
  58868. var srcCubeRowWalk = 0;
  58869. for (var u = uStart; u <= uEnd; u++) {
  58870. //pointer to direction in cube map associated with texel
  58871. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  58872. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  58873. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  58874. //check dot product to see if texel is within cone
  58875. var tapDotProd = texelVectX * centerTapDir.x +
  58876. texelVectY * centerTapDir.y +
  58877. texelVectZ * centerTapDir.z;
  58878. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  58879. //solid angle stored in 4th channel of normalizer/solid angle cube map
  58880. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  58881. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  58882. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  58883. // so just adding one to specularpower do the trick.
  58884. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  58885. //iterate over channels
  58886. for (k = 0; k < nSrcChannels; k++) {
  58887. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  58888. srcCubeRowWalk++;
  58889. }
  58890. weightAccum += weight; //accumulate weight
  58891. }
  58892. else {
  58893. //step across source pixel
  58894. srcCubeRowWalk += nSrcChannels;
  58895. }
  58896. normCubeRowWalk += 4; // 4 channels per norm cube map.
  58897. }
  58898. startIndexNormCubeMap += normCubePitch;
  58899. startIndexSrcCubeMap += srcCubePitch;
  58900. }
  58901. }
  58902. }
  58903. //divide through by weights if weight is non zero
  58904. if (weightAccum != 0.0) {
  58905. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  58906. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  58907. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  58908. if (this.numChannels > 3) {
  58909. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  58910. }
  58911. }
  58912. else {
  58913. // otherwise sample nearest
  58914. // get face idx and u, v texel coordinate in face
  58915. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  58916. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  58917. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  58918. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  58919. if (this.numChannels > 3) {
  58920. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  58921. }
  58922. }
  58923. return PMREMGenerator._vectorTemp;
  58924. };
  58925. //--------------------------------------------------------------------------------------
  58926. // Fixup cube edges
  58927. //
  58928. // average texels on cube map faces across the edges
  58929. // WARP/BENT Method Only.
  58930. //--------------------------------------------------------------------------------------
  58931. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  58932. var k;
  58933. var j;
  58934. var i;
  58935. var iFace;
  58936. var iCorner = 0;
  58937. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  58938. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  58939. // note that if functionality to filter across the three texels for each corner, then
  58940. //indexed by corner and face idx. the array contains the face the start points belongs to.
  58941. var cornerPtr = [
  58942. [[], [], []],
  58943. [[], [], []],
  58944. [[], [], []],
  58945. [[], [], []],
  58946. [[], [], []],
  58947. [[], [], []],
  58948. [[], [], []],
  58949. [[], [], []]
  58950. ];
  58951. //if there is no fixup, or fixup width = 0, do nothing
  58952. if (cubeMapSize < 1) {
  58953. return;
  58954. }
  58955. //special case 1x1 cubemap, average face colors
  58956. if (cubeMapSize == 1) {
  58957. //iterate over channels
  58958. for (k = 0; k < this.numChannels; k++) {
  58959. var accum = 0.0;
  58960. //iterate over faces to accumulate face colors
  58961. for (iFace = 0; iFace < 6; iFace++) {
  58962. accum += cubeMap[iFace][k];
  58963. }
  58964. //compute average over 6 face colors
  58965. accum /= 6.0;
  58966. //iterate over faces to distribute face colors
  58967. for (iFace = 0; iFace < 6; iFace++) {
  58968. cubeMap[iFace][k] = accum;
  58969. }
  58970. }
  58971. return;
  58972. }
  58973. //iterate over faces to collect list of corner texel pointers
  58974. for (iFace = 0; iFace < 6; iFace++) {
  58975. //the 4 corner pointers for this face
  58976. faceCornerStartIndicies[0] = [iFace, 0];
  58977. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  58978. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  58979. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  58980. //iterate over face corners to collect cube corner pointers
  58981. for (iCorner = 0; iCorner < 4; iCorner++) {
  58982. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  58983. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  58984. cornerNumPtrs[corner]++;
  58985. }
  58986. }
  58987. //iterate over corners to average across corner tap values
  58988. for (iCorner = 0; iCorner < 8; iCorner++) {
  58989. for (k = 0; k < this.numChannels; k++) {
  58990. var cornerTapAccum = 0.0;
  58991. //iterate over corner texels and average results
  58992. for (i = 0; i < 3; i++) {
  58993. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  58994. }
  58995. //divide by 3 to compute average of corner tap values
  58996. cornerTapAccum *= (1.0 / 3.0);
  58997. //iterate over corner texels and average results
  58998. for (i = 0; i < 3; i++) {
  58999. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  59000. }
  59001. }
  59002. }
  59003. //iterate over the twelve edges of the cube to average across edges
  59004. for (i = 0; i < 12; i++) {
  59005. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  59006. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  59007. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  59008. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  59009. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  59010. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  59011. var edgeWalk = 0;
  59012. var neighborEdgeWalk = 0;
  59013. //Determine walking pointers based on edge type
  59014. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  59015. switch (edge) {
  59016. case PMREMGenerator.CP_EDGE_LEFT:
  59017. // no change to faceEdgeStartPtr
  59018. edgeWalk = this.numChannels * cubeMapSize;
  59019. break;
  59020. case PMREMGenerator.CP_EDGE_RIGHT:
  59021. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59022. edgeWalk = this.numChannels * cubeMapSize;
  59023. break;
  59024. case PMREMGenerator.CP_EDGE_TOP:
  59025. // no change to faceEdgeStartPtr
  59026. edgeWalk = this.numChannels;
  59027. break;
  59028. case PMREMGenerator.CP_EDGE_BOTTOM:
  59029. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  59030. edgeWalk = this.numChannels;
  59031. break;
  59032. }
  59033. //For certain types of edge abutments, the neighbor edge walk needs to
  59034. // be flipped: the cases are
  59035. // if a left edge mates with a left or bottom edge on the neighbor
  59036. // if a top edge mates with a top or right edge on the neighbor
  59037. // if a right edge mates with a right or top edge on the neighbor
  59038. // if a bottom edge mates with a bottom or left edge on the neighbor
  59039. //Seeing as the edges are enumerated as follows
  59040. // left =0
  59041. // right =1
  59042. // top =2
  59043. // bottom =3
  59044. //
  59045. //If the edge enums are the same, or the sum of the enums == 3,
  59046. // the neighbor edge walk needs to be flipped
  59047. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  59048. switch (neighborEdge) {
  59049. case PMREMGenerator.CP_EDGE_LEFT:
  59050. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  59051. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  59052. break;
  59053. case PMREMGenerator.CP_EDGE_RIGHT:
  59054. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  59055. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  59056. break;
  59057. case PMREMGenerator.CP_EDGE_TOP:
  59058. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59059. neighborEdgeWalk = -this.numChannels;
  59060. break;
  59061. case PMREMGenerator.CP_EDGE_BOTTOM:
  59062. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  59063. neighborEdgeWalk = -this.numChannels;
  59064. break;
  59065. }
  59066. }
  59067. else {
  59068. //swapped direction neighbor edge walk
  59069. switch (neighborEdge) {
  59070. case PMREMGenerator.CP_EDGE_LEFT:
  59071. //no change to neighborEdgeStartPtr for this case since it points
  59072. // to the upper left corner already
  59073. neighborEdgeWalk = this.numChannels * cubeMapSize;
  59074. break;
  59075. case PMREMGenerator.CP_EDGE_RIGHT:
  59076. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59077. neighborEdgeWalk = this.numChannels * cubeMapSize;
  59078. break;
  59079. case PMREMGenerator.CP_EDGE_TOP:
  59080. //no change to neighborEdgeStartPtr for this case since it points
  59081. // to the upper left corner already
  59082. neighborEdgeWalk = this.numChannels;
  59083. break;
  59084. case PMREMGenerator.CP_EDGE_BOTTOM:
  59085. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  59086. neighborEdgeWalk = this.numChannels;
  59087. break;
  59088. }
  59089. }
  59090. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  59091. //nearby neighborhood
  59092. //step ahead one texel on edge
  59093. edgeStartIndex += edgeWalk;
  59094. neighborEdgeStartIndex += neighborEdgeWalk;
  59095. // note that this loop does not process the corner texels, since they have already been
  59096. // averaged across faces across earlier
  59097. for (j = 1; j < (cubeMapSize - 1); j++) {
  59098. //for each set of taps along edge, average them
  59099. // and rewrite the results into the edges
  59100. for (k = 0; k < this.numChannels; k++) {
  59101. var edgeTap = cubeMap[face][edgeStartIndex + k];
  59102. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  59103. //compute average of tap intensity values
  59104. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  59105. //propagate average of taps to edge taps
  59106. cubeMap[face][edgeStartIndex + k] = avgTap;
  59107. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  59108. }
  59109. edgeStartIndex += edgeWalk;
  59110. neighborEdgeStartIndex += neighborEdgeWalk;
  59111. }
  59112. }
  59113. };
  59114. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  59115. PMREMGenerator.CP_UDIR = 0;
  59116. PMREMGenerator.CP_VDIR = 1;
  59117. PMREMGenerator.CP_FACEAXIS = 2;
  59118. //used to index cube faces
  59119. PMREMGenerator.CP_FACE_X_POS = 0;
  59120. PMREMGenerator.CP_FACE_X_NEG = 1;
  59121. PMREMGenerator.CP_FACE_Y_POS = 2;
  59122. PMREMGenerator.CP_FACE_Y_NEG = 3;
  59123. PMREMGenerator.CP_FACE_Z_POS = 4;
  59124. PMREMGenerator.CP_FACE_Z_NEG = 5;
  59125. //used to index image edges
  59126. // NOTE.. the actual number corresponding to the edge is important
  59127. // do not change these, or the code will break
  59128. //
  59129. // CP_EDGE_LEFT is u = 0
  59130. // CP_EDGE_RIGHT is u = width-1
  59131. // CP_EDGE_TOP is v = 0
  59132. // CP_EDGE_BOTTOM is v = height-1
  59133. PMREMGenerator.CP_EDGE_LEFT = 0;
  59134. PMREMGenerator.CP_EDGE_RIGHT = 1;
  59135. PMREMGenerator.CP_EDGE_TOP = 2;
  59136. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  59137. //corners of CUBE map (P or N specifys if it corresponds to the
  59138. // positive or negative direction each of X, Y, and Z
  59139. PMREMGenerator.CP_CORNER_NNN = 0;
  59140. PMREMGenerator.CP_CORNER_NNP = 1;
  59141. PMREMGenerator.CP_CORNER_NPN = 2;
  59142. PMREMGenerator.CP_CORNER_NPP = 3;
  59143. PMREMGenerator.CP_CORNER_PNN = 4;
  59144. PMREMGenerator.CP_CORNER_PNP = 5;
  59145. PMREMGenerator.CP_CORNER_PPN = 6;
  59146. PMREMGenerator.CP_CORNER_PPP = 7;
  59147. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  59148. //3x2 matrices that map cube map indexing vectors in 3d
  59149. // (after face selection and divide through by the
  59150. // _ABSOLUTE VALUE_ of the max coord)
  59151. // into NVC space
  59152. //Note this currently assumes the D3D cube face ordering and orientation
  59153. PMREMGenerator._sgFace2DMapping = [
  59154. //XPOS face
  59155. [[0, 0, -1],
  59156. [0, -1, 0],
  59157. [1, 0, 0]],
  59158. //XNEG face
  59159. [[0, 0, 1],
  59160. [0, -1, 0],
  59161. [-1, 0, 0]],
  59162. //YPOS face
  59163. [[1, 0, 0],
  59164. [0, 0, 1],
  59165. [0, 1, 0]],
  59166. //YNEG face
  59167. [[1, 0, 0],
  59168. [0, 0, -1],
  59169. [0, -1, 0]],
  59170. //ZPOS face
  59171. [[1, 0, 0],
  59172. [0, -1, 0],
  59173. [0, 0, 1]],
  59174. //ZNEG face
  59175. [[-1, 0, 0],
  59176. [0, -1, 0],
  59177. [0, 0, -1]],
  59178. ];
  59179. //------------------------------------------------------------------------------
  59180. // D3D cube map face specification
  59181. // mapping from 3D x,y,z cube map lookup coordinates
  59182. // to 2D within face u,v coordinates
  59183. //
  59184. // --------------------> U direction
  59185. // | (within-face texture space)
  59186. // | _____
  59187. // | | |
  59188. // | | +Y |
  59189. // | _____|_____|_____ _____
  59190. // | | | | | |
  59191. // | | -X | +Z | +X | -Z |
  59192. // | |_____|_____|_____|_____|
  59193. // | | |
  59194. // | | -Y |
  59195. // | |_____|
  59196. // |
  59197. // v V direction
  59198. // (within-face texture space)
  59199. //------------------------------------------------------------------------------
  59200. //Information about neighbors and how texture coorrdinates change across faces
  59201. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  59202. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  59203. //Note this currently assumes the D3D cube face ordering and orientation
  59204. PMREMGenerator._sgCubeNgh = [
  59205. //XPOS face
  59206. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59207. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59208. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59209. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  59210. //XNEG face
  59211. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59212. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  59213. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  59214. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  59215. //YPOS face
  59216. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  59217. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  59218. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  59219. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  59220. //YNEG face
  59221. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  59222. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59223. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59224. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  59225. //ZPOS face
  59226. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59227. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  59228. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59229. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  59230. //ZNEG face
  59231. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59232. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59233. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  59234. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  59235. ];
  59236. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  59237. // this table is used to average over the edges.
  59238. PMREMGenerator._sgCubeEdgeList = [
  59239. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  59240. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59241. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  59242. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59243. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59244. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59245. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  59246. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  59247. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  59248. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59249. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  59250. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  59251. ];
  59252. //Information about which of the 8 cube corners are correspond to the
  59253. // the 4 corners in each cube face
  59254. // the order is upper left, upper right, lower left, lower right
  59255. PMREMGenerator._sgCubeCornerList = [
  59256. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  59257. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  59258. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  59259. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  59260. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  59261. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  59262. ];
  59263. return PMREMGenerator;
  59264. })();
  59265. Internals.PMREMGenerator = PMREMGenerator;
  59266. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59267. })(BABYLON || (BABYLON = {}));
  59268. var BABYLON;
  59269. (function (BABYLON) {
  59270. /**
  59271. * This represents a texture coming from an HDR input.
  59272. *
  59273. * The only supported format is currently panorama picture stored in RGBE format.
  59274. * Example of such files can be found on HDRLib: http://hdrlib.com/
  59275. */
  59276. var HDRCubeTexture = (function (_super) {
  59277. __extends(HDRCubeTexture, _super);
  59278. /**
  59279. * Instantiates an HDRTexture from the following parameters.
  59280. *
  59281. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  59282. * @param scene The scene the texture will be used in
  59283. * @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.
  59284. * @param noMipmap Forces to not generate the mipmap if true
  59285. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  59286. * @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)
  59287. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  59288. */
  59289. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  59290. if (noMipmap === void 0) { noMipmap = false; }
  59291. if (generateHarmonics === void 0) { generateHarmonics = true; }
  59292. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  59293. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  59294. _super.call(this, scene);
  59295. this._useInGammaSpace = false;
  59296. this._generateHarmonics = true;
  59297. this._isBABYLONPreprocessed = false;
  59298. /**
  59299. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  59300. */
  59301. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  59302. /**
  59303. * The spherical polynomial data extracted from the texture.
  59304. */
  59305. this.sphericalPolynomial = null;
  59306. /**
  59307. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  59308. * This is usefull at run time to apply the good shader.
  59309. */
  59310. this.isPMREM = false;
  59311. if (!url) {
  59312. return;
  59313. }
  59314. this.name = url;
  59315. this.url = url;
  59316. this.hasAlpha = false;
  59317. this.isCube = true;
  59318. this._textureMatrix = BABYLON.Matrix.Identity();
  59319. if (size) {
  59320. this._isBABYLONPreprocessed = false;
  59321. this._noMipmap = noMipmap;
  59322. this._size = size;
  59323. this._useInGammaSpace = useInGammaSpace;
  59324. this._usePMREMGenerator = usePMREMGenerator &&
  59325. scene.getEngine().getCaps().textureLOD &&
  59326. this.getScene().getEngine().getCaps().textureFloat &&
  59327. !this._useInGammaSpace;
  59328. }
  59329. else {
  59330. this._isBABYLONPreprocessed = true;
  59331. this._noMipmap = false;
  59332. this._useInGammaSpace = false;
  59333. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  59334. this.getScene().getEngine().getCaps().textureFloat &&
  59335. !this._useInGammaSpace;
  59336. }
  59337. this.isPMREM = this._usePMREMGenerator;
  59338. this._texture = this._getFromCache(url, this._noMipmap);
  59339. if (!this._texture) {
  59340. if (!scene.useDelayedTextureLoading) {
  59341. this.loadTexture();
  59342. }
  59343. else {
  59344. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59345. }
  59346. }
  59347. }
  59348. /**
  59349. * Occurs when the file is a preprocessed .babylon.hdr file.
  59350. */
  59351. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  59352. var _this = this;
  59353. var mipLevels = 0;
  59354. var floatArrayView = null;
  59355. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  59356. var mips = [];
  59357. var startIndex = 30;
  59358. for (var level = 0; level < mipLevels; level++) {
  59359. mips.push([]);
  59360. // Fill each pixel of the mip level.
  59361. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  59362. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59363. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  59364. mips[level].push(faceData);
  59365. startIndex += faceSize;
  59366. }
  59367. }
  59368. return mips;
  59369. } : null;
  59370. var callback = function (buffer) {
  59371. // Create Native Array Views
  59372. var intArrayView = new Int32Array(buffer);
  59373. floatArrayView = new Float32Array(buffer);
  59374. // Fill header.
  59375. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  59376. _this._size = intArrayView[1]; // CubeMap max mip face size.
  59377. // Update Texture Information.
  59378. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  59379. // Fill polynomial information.
  59380. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  59381. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  59382. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  59383. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  59384. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  59385. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  59386. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  59387. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  59388. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  59389. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  59390. // Fill pixel data.
  59391. mipLevels = intArrayView[29]; // Number of mip levels.
  59392. var startIndex = 30;
  59393. var data = [];
  59394. var faceSize = Math.pow(_this._size, 2) * 3;
  59395. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59396. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  59397. startIndex += faceSize;
  59398. }
  59399. var results = [];
  59400. var byteArray = null;
  59401. // Push each faces.
  59402. for (var k = 0; k < 6; k++) {
  59403. var dataFace = null;
  59404. // If special cases.
  59405. if (!mipmapGenerator) {
  59406. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  59407. dataFace = data[j];
  59408. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59409. // 3 channels of 1 bytes per pixel in bytes.
  59410. var byteBuffer = new ArrayBuffer(faceSize);
  59411. byteArray = new Uint8Array(byteBuffer);
  59412. }
  59413. for (var i = 0; i < _this._size * _this._size; i++) {
  59414. // Put in gamma space if requested.
  59415. if (_this._useInGammaSpace) {
  59416. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59417. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59418. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59419. }
  59420. // Convert to int texture for fallback.
  59421. if (byteArray) {
  59422. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59423. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59424. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59425. // May use luminance instead if the result is not accurate.
  59426. var max = Math.max(Math.max(r, g), b);
  59427. if (max > 255) {
  59428. var scale = 255 / max;
  59429. r *= scale;
  59430. g *= scale;
  59431. b *= scale;
  59432. }
  59433. byteArray[(i * 3) + 0] = r;
  59434. byteArray[(i * 3) + 1] = g;
  59435. byteArray[(i * 3) + 2] = b;
  59436. }
  59437. }
  59438. }
  59439. else {
  59440. dataFace = data[k];
  59441. }
  59442. // Fill the array accordingly.
  59443. if (byteArray) {
  59444. results.push(byteArray);
  59445. }
  59446. else {
  59447. results.push(dataFace);
  59448. }
  59449. }
  59450. return results;
  59451. };
  59452. 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);
  59453. };
  59454. /**
  59455. * Occurs when the file is raw .hdr file.
  59456. */
  59457. HDRCubeTexture.prototype.loadHDRTexture = function () {
  59458. var _this = this;
  59459. var callback = function (buffer) {
  59460. // Extract the raw linear data.
  59461. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  59462. // Generate harmonics if needed.
  59463. if (_this._generateHarmonics) {
  59464. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  59465. }
  59466. var results = [];
  59467. var byteArray = null;
  59468. // Push each faces.
  59469. for (var j = 0; j < 6; j++) {
  59470. // Create uintarray fallback.
  59471. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59472. // 3 channels of 1 bytes per pixel in bytes.
  59473. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  59474. byteArray = new Uint8Array(byteBuffer);
  59475. }
  59476. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  59477. // If special cases.
  59478. if (_this._useInGammaSpace || byteArray) {
  59479. for (var i = 0; i < _this._size * _this._size; i++) {
  59480. // Put in gamma space if requested.
  59481. if (_this._useInGammaSpace) {
  59482. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59483. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59484. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59485. }
  59486. // Convert to int texture for fallback.
  59487. if (byteArray) {
  59488. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59489. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59490. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59491. // May use luminance instead if the result is not accurate.
  59492. var max = Math.max(Math.max(r, g), b);
  59493. if (max > 255) {
  59494. var scale = 255 / max;
  59495. r *= scale;
  59496. g *= scale;
  59497. b *= scale;
  59498. }
  59499. byteArray[(i * 3) + 0] = r;
  59500. byteArray[(i * 3) + 1] = g;
  59501. byteArray[(i * 3) + 2] = b;
  59502. }
  59503. }
  59504. }
  59505. if (byteArray) {
  59506. results.push(byteArray);
  59507. }
  59508. else {
  59509. results.push(dataFace);
  59510. }
  59511. }
  59512. return results;
  59513. };
  59514. var mipmapGenerator = null;
  59515. if (!this._noMipmap &&
  59516. this._usePMREMGenerator) {
  59517. mipmapGenerator = function (data) {
  59518. // Custom setup of the generator matching with the PBR shader values.
  59519. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  59520. return generator.filterCubeMap();
  59521. };
  59522. }
  59523. 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);
  59524. };
  59525. /**
  59526. * Starts the loading process of the texture.
  59527. */
  59528. HDRCubeTexture.prototype.loadTexture = function () {
  59529. if (this._isBABYLONPreprocessed) {
  59530. this.loadBabylonTexture();
  59531. }
  59532. else {
  59533. this.loadHDRTexture();
  59534. }
  59535. };
  59536. HDRCubeTexture.prototype.clone = function () {
  59537. var size = this._isBABYLONPreprocessed ? null : this._size;
  59538. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  59539. // Base texture
  59540. newTexture.level = this.level;
  59541. newTexture.wrapU = this.wrapU;
  59542. newTexture.wrapV = this.wrapV;
  59543. newTexture.coordinatesIndex = this.coordinatesIndex;
  59544. newTexture.coordinatesMode = this.coordinatesMode;
  59545. return newTexture;
  59546. };
  59547. // Methods
  59548. HDRCubeTexture.prototype.delayLoad = function () {
  59549. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59550. return;
  59551. }
  59552. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59553. this._texture = this._getFromCache(this.url, this._noMipmap);
  59554. if (!this._texture) {
  59555. this.loadTexture();
  59556. }
  59557. };
  59558. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  59559. return this._textureMatrix;
  59560. };
  59561. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59562. var texture = null;
  59563. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  59564. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  59565. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  59566. texture.name = parsedTexture.name;
  59567. texture.hasAlpha = parsedTexture.hasAlpha;
  59568. texture.level = parsedTexture.level;
  59569. texture.coordinatesMode = parsedTexture.coordinatesMode;
  59570. }
  59571. return texture;
  59572. };
  59573. HDRCubeTexture.prototype.serialize = function () {
  59574. if (!this.name) {
  59575. return null;
  59576. }
  59577. var serializationObject = {};
  59578. serializationObject.name = this.name;
  59579. serializationObject.hasAlpha = this.hasAlpha;
  59580. serializationObject.isCube = true;
  59581. serializationObject.level = this.level;
  59582. serializationObject.size = this._size;
  59583. serializationObject.coordinatesMode = this.coordinatesMode;
  59584. serializationObject.useInGammaSpace = this._useInGammaSpace;
  59585. serializationObject.generateHarmonics = this._generateHarmonics;
  59586. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  59587. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  59588. serializationObject.customType = "BABYLON.HDRCubeTexture";
  59589. return serializationObject;
  59590. };
  59591. /**
  59592. * Saves as a file the data contained in the texture in a binary format.
  59593. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59594. * as the spherical used in the lighting.
  59595. * @param url The HDR file url.
  59596. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59597. * @param onError Method called if any error happens during download.
  59598. * @return The packed binary data.
  59599. */
  59600. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  59601. if (onError === void 0) { onError = null; }
  59602. var callback = function (buffer) {
  59603. var data = new Blob([buffer], { type: 'application/octet-stream' });
  59604. // Returns a URL you can use as a href.
  59605. var objUrl = window.URL.createObjectURL(data);
  59606. // Simulates a link to it and click to dowload.
  59607. var a = document.createElement("a");
  59608. document.body.appendChild(a);
  59609. a.style.display = "none";
  59610. a.href = objUrl;
  59611. a.download = "envmap.babylon.hdr";
  59612. a.click();
  59613. };
  59614. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  59615. };
  59616. /**
  59617. * Serializes the data contained in the texture in a binary format.
  59618. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59619. * as the spherical used in the lighting.
  59620. * @param url The HDR file url.
  59621. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59622. * @param onError Method called if any error happens during download.
  59623. * @return The packed binary data.
  59624. */
  59625. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  59626. if (onError === void 0) { onError = null; }
  59627. // Needs the url tho create the texture.
  59628. if (!url) {
  59629. return null;
  59630. }
  59631. // Check Power of two size.
  59632. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  59633. return null;
  59634. }
  59635. var getDataCallback = function (dataBuffer) {
  59636. // Extract the raw linear data.
  59637. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  59638. // Generate harmonics if needed.
  59639. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  59640. // Generate seamless faces
  59641. var mipGeneratorArray = [];
  59642. // Data are known to be in +X +Y +Z -X -Y -Z
  59643. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  59644. mipGeneratorArray.push(cubeData.right); // +X
  59645. mipGeneratorArray.push(cubeData.left); // -X
  59646. mipGeneratorArray.push(cubeData.up); // +Y
  59647. mipGeneratorArray.push(cubeData.down); // -Y
  59648. mipGeneratorArray.push(cubeData.front); // +Z
  59649. mipGeneratorArray.push(cubeData.back); // -Z
  59650. // Custom setup of the generator matching with the PBR shader values.
  59651. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  59652. var mippedData = generator.filterCubeMap();
  59653. // Compute required byte length.
  59654. var byteLength = 1 * 4; // Raw Data Version int32.
  59655. byteLength += 4; // CubeMap max mip face size int32.
  59656. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  59657. // Add data size.
  59658. byteLength += 4; // Number of mip levels int32.
  59659. for (var level = 0; level < mippedData.length; level++) {
  59660. var mipSize = size >> level;
  59661. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  59662. }
  59663. // Prepare binary structure.
  59664. var buffer = new ArrayBuffer(byteLength);
  59665. var intArrayView = new Int32Array(buffer);
  59666. var floatArrayView = new Float32Array(buffer);
  59667. // Fill header.
  59668. intArrayView[0] = 1; // Version 1.
  59669. intArrayView[1] = size; // CubeMap max mip face size.
  59670. // Fill polynomial information.
  59671. sphericalPolynomial.x.toArray(floatArrayView, 2);
  59672. sphericalPolynomial.y.toArray(floatArrayView, 5);
  59673. sphericalPolynomial.z.toArray(floatArrayView, 8);
  59674. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  59675. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  59676. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  59677. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  59678. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  59679. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  59680. // Fill pixel data.
  59681. intArrayView[29] = mippedData.length; // Number of mip levels.
  59682. var startIndex = 30;
  59683. for (var level = 0; level < mippedData.length; level++) {
  59684. // Fill each pixel of the mip level.
  59685. var faceSize = Math.pow(size >> level, 2) * 3;
  59686. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59687. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  59688. startIndex += faceSize;
  59689. }
  59690. }
  59691. // Callback.
  59692. callback(buffer);
  59693. };
  59694. // Download and process.
  59695. BABYLON.Tools.LoadFile(url, function (data) {
  59696. getDataCallback(data);
  59697. }, null, null, true, onError);
  59698. };
  59699. HDRCubeTexture._facesMapping = [
  59700. "right",
  59701. "up",
  59702. "front",
  59703. "left",
  59704. "down",
  59705. "back"
  59706. ];
  59707. return HDRCubeTexture;
  59708. })(BABYLON.BaseTexture);
  59709. BABYLON.HDRCubeTexture = HDRCubeTexture;
  59710. })(BABYLON || (BABYLON = {}));
  59711. var BABYLON;
  59712. (function (BABYLON) {
  59713. var Debug;
  59714. (function (Debug) {
  59715. /**
  59716. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  59717. */
  59718. var SkeletonViewer = (function () {
  59719. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  59720. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59721. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59722. this.skeleton = skeleton;
  59723. this.mesh = mesh;
  59724. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59725. this.renderingGroupId = renderingGroupId;
  59726. this.color = BABYLON.Color3.White();
  59727. this._debugLines = [];
  59728. this._isEnabled = false;
  59729. this._scene = scene;
  59730. this.update();
  59731. this._renderFunction = this.update.bind(this);
  59732. }
  59733. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59734. get: function () {
  59735. return this._isEnabled;
  59736. },
  59737. set: function (value) {
  59738. if (this._isEnabled === value) {
  59739. return;
  59740. }
  59741. this._isEnabled = value;
  59742. if (value) {
  59743. this._scene.registerBeforeRender(this._renderFunction);
  59744. }
  59745. else {
  59746. this._scene.unregisterBeforeRender(this._renderFunction);
  59747. }
  59748. },
  59749. enumerable: true,
  59750. configurable: true
  59751. });
  59752. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59753. if (x === void 0) { x = 0; }
  59754. if (y === void 0) { y = 0; }
  59755. if (z === void 0) { z = 0; }
  59756. var tmat = BABYLON.Tmp.Matrix[0];
  59757. var parentBone = bone.getParent();
  59758. tmat.copyFrom(bone.getLocalMatrix());
  59759. if (x !== 0 || y !== 0 || z !== 0) {
  59760. var tmat2 = BABYLON.Tmp.Matrix[1];
  59761. BABYLON.Matrix.IdentityToRef(tmat2);
  59762. tmat2.m[12] = x;
  59763. tmat2.m[13] = y;
  59764. tmat2.m[14] = z;
  59765. tmat2.multiplyToRef(tmat, tmat);
  59766. }
  59767. if (parentBone) {
  59768. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59769. }
  59770. tmat.multiplyToRef(meshMat, tmat);
  59771. position.x = tmat.m[12];
  59772. position.y = tmat.m[13];
  59773. position.z = tmat.m[14];
  59774. };
  59775. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59776. var len = bones.length;
  59777. for (var i = 0; i < len; i++) {
  59778. var bone = bones[i];
  59779. var points = this._debugLines[i];
  59780. if (!points) {
  59781. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59782. this._debugLines[i] = points;
  59783. }
  59784. this._getBonePosition(points[0], bone, meshMat);
  59785. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59786. }
  59787. };
  59788. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59789. var len = bones.length;
  59790. var boneNum = 0;
  59791. for (var i = len - 1; i >= 0; i--) {
  59792. var childBone = bones[i];
  59793. var parentBone = childBone.getParent();
  59794. if (!parentBone) {
  59795. continue;
  59796. }
  59797. var points = this._debugLines[boneNum];
  59798. if (!points) {
  59799. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59800. this._debugLines[boneNum] = points;
  59801. }
  59802. this._getBonePosition(points[0], childBone, meshMat);
  59803. this._getBonePosition(points[1], parentBone, meshMat);
  59804. boneNum++;
  59805. }
  59806. };
  59807. SkeletonViewer.prototype.update = function () {
  59808. if (this.autoUpdateBonesMatrices) {
  59809. this._updateBoneMatrix(this.skeleton.bones[0]);
  59810. }
  59811. if (this.skeleton.bones[0].length === undefined) {
  59812. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59813. }
  59814. else {
  59815. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59816. }
  59817. if (!this._debugMesh) {
  59818. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  59819. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59820. }
  59821. else {
  59822. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59823. }
  59824. this._debugMesh.color = this.color;
  59825. };
  59826. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  59827. if (bone.getParent()) {
  59828. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  59829. }
  59830. var children = bone.children;
  59831. var len = children.length;
  59832. for (var i = 0; i < len; i++) {
  59833. this._updateBoneMatrix(children[i]);
  59834. }
  59835. };
  59836. SkeletonViewer.prototype.dispose = function () {
  59837. if (this._debugMesh) {
  59838. this.isEnabled = false;
  59839. this._debugMesh.dispose();
  59840. this._debugMesh = null;
  59841. }
  59842. };
  59843. return SkeletonViewer;
  59844. })();
  59845. Debug.SkeletonViewer = SkeletonViewer;
  59846. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59847. })(BABYLON || (BABYLON = {}));
  59848. var BABYLON;
  59849. (function (BABYLON) {
  59850. /**
  59851. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  59852. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  59853. * 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;
  59854. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  59855. */
  59856. var ColorCurves = (function () {
  59857. function ColorCurves() {
  59858. this._dirty = true;
  59859. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  59860. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  59861. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59862. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  59863. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59864. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  59865. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  59866. this._globalHue = 30;
  59867. this._globalDensity = 0;
  59868. this._globalSaturation = 0;
  59869. this._globalExposure = 0;
  59870. this._highlightsHue = 30;
  59871. this._highlightsDensity = 0;
  59872. this._highlightsSaturation = 0;
  59873. this._highlightsExposure = 0;
  59874. this._midtonesHue = 30;
  59875. this._midtonesDensity = 0;
  59876. this._midtonesSaturation = 0;
  59877. this._midtonesExposure = 0;
  59878. this._shadowsHue = 30;
  59879. this._shadowsDensity = 0;
  59880. this._shadowsSaturation = 0;
  59881. this._shadowsExposure = 0;
  59882. }
  59883. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  59884. /**
  59885. * Gets the global Hue value.
  59886. * 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).
  59887. */
  59888. get: function () {
  59889. return this._globalHue;
  59890. },
  59891. /**
  59892. * Sets the global Hue value.
  59893. * 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).
  59894. */
  59895. set: function (value) {
  59896. this._globalHue = value;
  59897. this._dirty = true;
  59898. },
  59899. enumerable: true,
  59900. configurable: true
  59901. });
  59902. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  59903. /**
  59904. * Gets the global Density value.
  59905. * 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.
  59906. * Values less than zero provide a filter of opposite hue.
  59907. */
  59908. get: function () {
  59909. return this._globalDensity;
  59910. },
  59911. /**
  59912. * Sets the global Density value.
  59913. * 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.
  59914. * Values less than zero provide a filter of opposite hue.
  59915. */
  59916. set: function (value) {
  59917. this._globalDensity = value;
  59918. this._dirty = true;
  59919. },
  59920. enumerable: true,
  59921. configurable: true
  59922. });
  59923. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  59924. /**
  59925. * Gets the global Saturation value.
  59926. * 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.
  59927. */
  59928. get: function () {
  59929. return this._globalSaturation;
  59930. },
  59931. /**
  59932. * Sets the global Saturation value.
  59933. * 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.
  59934. */
  59935. set: function (value) {
  59936. this._globalSaturation = value;
  59937. this._dirty = true;
  59938. },
  59939. enumerable: true,
  59940. configurable: true
  59941. });
  59942. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  59943. /**
  59944. * Gets the highlights Hue value.
  59945. * 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).
  59946. */
  59947. get: function () {
  59948. return this._highlightsHue;
  59949. },
  59950. /**
  59951. * Sets the highlights Hue value.
  59952. * 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).
  59953. */
  59954. set: function (value) {
  59955. this._highlightsHue = value;
  59956. this._dirty = true;
  59957. },
  59958. enumerable: true,
  59959. configurable: true
  59960. });
  59961. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  59962. /**
  59963. * Gets the highlights Density value.
  59964. * 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.
  59965. * Values less than zero provide a filter of opposite hue.
  59966. */
  59967. get: function () {
  59968. return this._highlightsDensity;
  59969. },
  59970. /**
  59971. * Sets the highlights Density value.
  59972. * 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.
  59973. * Values less than zero provide a filter of opposite hue.
  59974. */
  59975. set: function (value) {
  59976. this._highlightsDensity = value;
  59977. this._dirty = true;
  59978. },
  59979. enumerable: true,
  59980. configurable: true
  59981. });
  59982. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  59983. /**
  59984. * Gets the highlights Saturation value.
  59985. * 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.
  59986. */
  59987. get: function () {
  59988. return this._highlightsSaturation;
  59989. },
  59990. /**
  59991. * Sets the highlights Saturation value.
  59992. * 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.
  59993. */
  59994. set: function (value) {
  59995. this._highlightsSaturation = value;
  59996. this._dirty = true;
  59997. },
  59998. enumerable: true,
  59999. configurable: true
  60000. });
  60001. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  60002. /**
  60003. * Gets the highlights Exposure value.
  60004. * 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.
  60005. */
  60006. get: function () {
  60007. return this._highlightsExposure;
  60008. },
  60009. /**
  60010. * Sets the highlights Exposure value.
  60011. * 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.
  60012. */
  60013. set: function (value) {
  60014. this._highlightsExposure = value;
  60015. this._dirty = true;
  60016. },
  60017. enumerable: true,
  60018. configurable: true
  60019. });
  60020. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  60021. /**
  60022. * Gets the midtones Hue value.
  60023. * 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).
  60024. */
  60025. get: function () {
  60026. return this._midtonesHue;
  60027. },
  60028. /**
  60029. * Sets the midtones Hue value.
  60030. * 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).
  60031. */
  60032. set: function (value) {
  60033. this._midtonesHue = value;
  60034. this._dirty = true;
  60035. },
  60036. enumerable: true,
  60037. configurable: true
  60038. });
  60039. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  60040. /**
  60041. * Gets the midtones Density value.
  60042. * 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.
  60043. * Values less than zero provide a filter of opposite hue.
  60044. */
  60045. get: function () {
  60046. return this._midtonesDensity;
  60047. },
  60048. /**
  60049. * Sets the midtones Density value.
  60050. * 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.
  60051. * Values less than zero provide a filter of opposite hue.
  60052. */
  60053. set: function (value) {
  60054. this._midtonesDensity = value;
  60055. this._dirty = true;
  60056. },
  60057. enumerable: true,
  60058. configurable: true
  60059. });
  60060. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  60061. /**
  60062. * Gets the midtones Saturation value.
  60063. * 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.
  60064. */
  60065. get: function () {
  60066. return this._midtonesSaturation;
  60067. },
  60068. /**
  60069. * Sets the midtones Saturation value.
  60070. * 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.
  60071. */
  60072. set: function (value) {
  60073. this._midtonesSaturation = value;
  60074. this._dirty = true;
  60075. },
  60076. enumerable: true,
  60077. configurable: true
  60078. });
  60079. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  60080. /**
  60081. * Gets the midtones Exposure value.
  60082. * 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.
  60083. */
  60084. get: function () {
  60085. return this._midtonesExposure;
  60086. },
  60087. /**
  60088. * Sets the midtones Exposure value.
  60089. * 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.
  60090. */
  60091. set: function (value) {
  60092. this._midtonesExposure = value;
  60093. this._dirty = true;
  60094. },
  60095. enumerable: true,
  60096. configurable: true
  60097. });
  60098. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  60099. /**
  60100. * Gets the shadows Hue value.
  60101. * 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).
  60102. */
  60103. get: function () {
  60104. return this._shadowsHue;
  60105. },
  60106. /**
  60107. * Sets the shadows Hue value.
  60108. * 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).
  60109. */
  60110. set: function (value) {
  60111. this._shadowsHue = value;
  60112. this._dirty = true;
  60113. },
  60114. enumerable: true,
  60115. configurable: true
  60116. });
  60117. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  60118. /**
  60119. * Gets the shadows Density value.
  60120. * 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.
  60121. * Values less than zero provide a filter of opposite hue.
  60122. */
  60123. get: function () {
  60124. return this._shadowsDensity;
  60125. },
  60126. /**
  60127. * Sets the shadows Density value.
  60128. * 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.
  60129. * Values less than zero provide a filter of opposite hue.
  60130. */
  60131. set: function (value) {
  60132. this._shadowsDensity = value;
  60133. this._dirty = true;
  60134. },
  60135. enumerable: true,
  60136. configurable: true
  60137. });
  60138. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  60139. /**
  60140. * Gets the shadows Saturation value.
  60141. * 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.
  60142. */
  60143. get: function () {
  60144. return this._shadowsSaturation;
  60145. },
  60146. /**
  60147. * Sets the shadows Saturation value.
  60148. * 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.
  60149. */
  60150. set: function (value) {
  60151. this._shadowsSaturation = value;
  60152. this._dirty = true;
  60153. },
  60154. enumerable: true,
  60155. configurable: true
  60156. });
  60157. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  60158. /**
  60159. * Gets the shadows Exposure value.
  60160. * 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.
  60161. */
  60162. get: function () {
  60163. return this._shadowsExposure;
  60164. },
  60165. /**
  60166. * Sets the shadows Exposure value.
  60167. * 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.
  60168. */
  60169. set: function (value) {
  60170. this._shadowsExposure = value;
  60171. this._dirty = true;
  60172. },
  60173. enumerable: true,
  60174. configurable: true
  60175. });
  60176. /**
  60177. * Binds the color curves to the shader.
  60178. * @param colorCurves The color curve to bind
  60179. * @param effect The effect to bind to
  60180. */
  60181. ColorCurves.Bind = function (colorCurves, effect) {
  60182. if (colorCurves._dirty) {
  60183. colorCurves._dirty = false;
  60184. // Fill in global info.
  60185. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  60186. // Compute highlights info.
  60187. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  60188. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  60189. // Compute midtones info.
  60190. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  60191. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  60192. // Compute shadows info.
  60193. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  60194. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  60195. // Compute deltas (neutral is midtones).
  60196. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  60197. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  60198. }
  60199. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  60200. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  60201. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  60202. };
  60203. /**
  60204. * Prepare the list of uniforms associated with the ColorCurves effects.
  60205. * @param uniformsList The list of uniforms used in the effect
  60206. */
  60207. ColorCurves.PrepareUniforms = function (uniformsList) {
  60208. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  60209. };
  60210. /**
  60211. * Returns color grading data based on a hue, density, saturation and exposure value.
  60212. * @param filterHue The hue of the color filter.
  60213. * @param filterDensity The density of the color filter.
  60214. * @param saturation The saturation.
  60215. * @param exposure The exposure.
  60216. * @param result The result data container.
  60217. */
  60218. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  60219. if (hue == null) {
  60220. return;
  60221. }
  60222. hue = ColorCurves.clamp(hue, 0, 360);
  60223. density = ColorCurves.clamp(density, -100, 100);
  60224. saturation = ColorCurves.clamp(saturation, -100, 100);
  60225. exposure = ColorCurves.clamp(exposure, -100, 100);
  60226. // Remap the slider/config filter density with non-linear mapping and also scale by half
  60227. // so that the maximum filter density is only 50% control. This provides fine control
  60228. // for small values and reasonable range.
  60229. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  60230. density *= 0.5;
  60231. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  60232. if (density < 0) {
  60233. density *= -1;
  60234. hue = (hue + 180) % 360;
  60235. }
  60236. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  60237. result.scaleToRef(2, result);
  60238. result.a = 1 + 0.01 * saturation;
  60239. };
  60240. /**
  60241. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  60242. * @param value The input slider value in range [-100,100].
  60243. * @returns Adjusted value.
  60244. */
  60245. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  60246. value /= 100;
  60247. var x = Math.abs(value);
  60248. x = Math.pow(x, 2);
  60249. if (value < 0) {
  60250. x *= -1;
  60251. }
  60252. x *= 100;
  60253. return x;
  60254. };
  60255. /**
  60256. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  60257. * @param hue The hue (H) input.
  60258. * @param saturation The saturation (S) input.
  60259. * @param brightness The brightness (B) input.
  60260. * @result An RGBA color represented as Vector4.
  60261. */
  60262. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  60263. var h = ColorCurves.clamp(hue, 0, 360);
  60264. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  60265. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  60266. if (s === 0) {
  60267. result.r = v;
  60268. result.g = v;
  60269. result.b = v;
  60270. }
  60271. else {
  60272. // sector 0 to 5
  60273. h /= 60;
  60274. var i = Math.floor(h);
  60275. // fractional part of h
  60276. var f = h - i;
  60277. var p = v * (1 - s);
  60278. var q = v * (1 - s * f);
  60279. var t = v * (1 - s * (1 - f));
  60280. switch (i) {
  60281. case 0:
  60282. result.r = v;
  60283. result.g = t;
  60284. result.b = p;
  60285. break;
  60286. case 1:
  60287. result.r = q;
  60288. result.g = v;
  60289. result.b = p;
  60290. break;
  60291. case 2:
  60292. result.r = p;
  60293. result.g = v;
  60294. result.b = t;
  60295. break;
  60296. case 3:
  60297. result.r = p;
  60298. result.g = q;
  60299. result.b = v;
  60300. break;
  60301. case 4:
  60302. result.r = t;
  60303. result.g = p;
  60304. result.b = v;
  60305. break;
  60306. default:
  60307. result.r = v;
  60308. result.g = p;
  60309. result.b = q;
  60310. break;
  60311. }
  60312. }
  60313. result.a = 1;
  60314. };
  60315. /**
  60316. * Returns a value clamped between min and max
  60317. * @param value The value to clamp
  60318. * @param min The minimum of value
  60319. * @param max The maximum of value
  60320. * @returns The clamped value.
  60321. */
  60322. ColorCurves.clamp = function (value, min, max) {
  60323. return Math.min(Math.max(value, min), max);
  60324. };
  60325. /**
  60326. * Clones the current color curve instance.
  60327. * @return The cloned curves
  60328. */
  60329. ColorCurves.prototype.clone = function () {
  60330. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  60331. };
  60332. /**
  60333. * Serializes the current color curve instance to a json representation.
  60334. * @return a JSON representation
  60335. */
  60336. ColorCurves.prototype.serialize = function () {
  60337. return BABYLON.SerializationHelper.Serialize(this);
  60338. };
  60339. /**
  60340. * Parses the color curve from a json representation.
  60341. * @param source the JSON source to parse
  60342. * @return The parsed curves
  60343. */
  60344. ColorCurves.Parse = function (source) {
  60345. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  60346. };
  60347. __decorate([
  60348. BABYLON.serialize()
  60349. ], ColorCurves.prototype, "_globalHue", void 0);
  60350. __decorate([
  60351. BABYLON.serialize()
  60352. ], ColorCurves.prototype, "_globalDensity", void 0);
  60353. __decorate([
  60354. BABYLON.serialize()
  60355. ], ColorCurves.prototype, "_globalSaturation", void 0);
  60356. __decorate([
  60357. BABYLON.serialize()
  60358. ], ColorCurves.prototype, "_globalExposure", void 0);
  60359. __decorate([
  60360. BABYLON.serialize()
  60361. ], ColorCurves.prototype, "_highlightsHue", void 0);
  60362. __decorate([
  60363. BABYLON.serialize()
  60364. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  60365. __decorate([
  60366. BABYLON.serialize()
  60367. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  60368. __decorate([
  60369. BABYLON.serialize()
  60370. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  60371. __decorate([
  60372. BABYLON.serialize()
  60373. ], ColorCurves.prototype, "_midtonesHue", void 0);
  60374. __decorate([
  60375. BABYLON.serialize()
  60376. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  60377. __decorate([
  60378. BABYLON.serialize()
  60379. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  60380. __decorate([
  60381. BABYLON.serialize()
  60382. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  60383. return ColorCurves;
  60384. })();
  60385. BABYLON.ColorCurves = ColorCurves;
  60386. })(BABYLON || (BABYLON = {}));
  60387. var BABYLON;
  60388. (function (BABYLON) {
  60389. /**
  60390. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  60391. * It can help converting any input color in a desired output one. This can then be used to create effects
  60392. * from sepia, black and white to sixties or futuristic rendering...
  60393. *
  60394. * The only supported format is currently 3dl.
  60395. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  60396. */
  60397. var ColorGradingTexture = (function (_super) {
  60398. __extends(ColorGradingTexture, _super);
  60399. /**
  60400. * Instantiates a ColorGradingTexture from the following parameters.
  60401. *
  60402. * @param url The location of the color gradind data (currently only supporting 3dl)
  60403. * @param scene The scene the texture will be used in
  60404. */
  60405. function ColorGradingTexture(url, scene) {
  60406. _super.call(this, scene);
  60407. if (!url) {
  60408. return;
  60409. }
  60410. this._textureMatrix = BABYLON.Matrix.Identity();
  60411. this.name = url;
  60412. this.url = url;
  60413. this.hasAlpha = false;
  60414. this.isCube = false;
  60415. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60416. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60417. this.anisotropicFilteringLevel = 1;
  60418. this._texture = this._getFromCache(url, true);
  60419. if (!this._texture) {
  60420. if (!scene.useDelayedTextureLoading) {
  60421. this.loadTexture();
  60422. }
  60423. else {
  60424. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  60425. }
  60426. }
  60427. }
  60428. /**
  60429. * Returns the texture matrix used in most of the material.
  60430. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  60431. */
  60432. ColorGradingTexture.prototype.getTextureMatrix = function () {
  60433. return this._textureMatrix;
  60434. };
  60435. /**
  60436. * Occurs when the file being loaded is a .3dl LUT file.
  60437. */
  60438. ColorGradingTexture.prototype.load3dlTexture = function () {
  60439. var _this = this;
  60440. var mipLevels = 0;
  60441. var floatArrayView = null;
  60442. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60443. this._texture = texture;
  60444. var callback = function (text) {
  60445. var data;
  60446. var tempData;
  60447. var line;
  60448. var lines = text.split('\n');
  60449. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  60450. var maxColor = 0;
  60451. for (var i = 0; i < lines.length; i++) {
  60452. line = lines[i];
  60453. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  60454. continue;
  60455. if (line.indexOf('#') === 0)
  60456. continue;
  60457. var words = line.split(" ");
  60458. if (size === 0) {
  60459. // Number of space + one
  60460. size = words.length;
  60461. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  60462. tempData = new Float32Array(size * size * size * 4);
  60463. continue;
  60464. }
  60465. if (size != 0) {
  60466. var r = Math.max(parseInt(words[0]), 0);
  60467. var g = Math.max(parseInt(words[1]), 0);
  60468. var b = Math.max(parseInt(words[2]), 0);
  60469. maxColor = Math.max(r, maxColor);
  60470. maxColor = Math.max(g, maxColor);
  60471. maxColor = Math.max(b, maxColor);
  60472. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  60473. tempData[pixelStorageIndex + 0] = r;
  60474. tempData[pixelStorageIndex + 1] = g;
  60475. tempData[pixelStorageIndex + 2] = b;
  60476. tempData[pixelStorageIndex + 3] = 0;
  60477. pixelIndexSlice++;
  60478. if (pixelIndexSlice % size == 0) {
  60479. pixelIndexH++;
  60480. pixelIndexSlice = 0;
  60481. if (pixelIndexH % size == 0) {
  60482. pixelIndexW++;
  60483. pixelIndexH = 0;
  60484. }
  60485. }
  60486. }
  60487. }
  60488. for (var i = 0; i < tempData.length; i++) {
  60489. var value = tempData[i];
  60490. data[i] = (value / maxColor * 255);
  60491. }
  60492. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  60493. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  60494. };
  60495. BABYLON.Tools.LoadFile(this.url, callback);
  60496. return this._texture;
  60497. };
  60498. /**
  60499. * Starts the loading process of the texture.
  60500. */
  60501. ColorGradingTexture.prototype.loadTexture = function () {
  60502. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  60503. this.load3dlTexture();
  60504. }
  60505. };
  60506. /**
  60507. * Clones the color gradind texture.
  60508. */
  60509. ColorGradingTexture.prototype.clone = function () {
  60510. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  60511. // Base texture
  60512. newTexture.level = this.level;
  60513. return newTexture;
  60514. };
  60515. /**
  60516. * Called during delayed load for textures.
  60517. */
  60518. ColorGradingTexture.prototype.delayLoad = function () {
  60519. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60520. return;
  60521. }
  60522. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  60523. this._texture = this._getFromCache(this.url, true);
  60524. if (!this._texture) {
  60525. this.loadTexture();
  60526. }
  60527. };
  60528. /**
  60529. * Binds the color grading to the shader.
  60530. * @param colorGrading The texture to bind
  60531. * @param effect The effect to bind to
  60532. */
  60533. ColorGradingTexture.Bind = function (colorGrading, effect) {
  60534. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  60535. var x = colorGrading.level; // Texture Level
  60536. var y = colorGrading.getSize().height; // Texture Size example with 8
  60537. var z = y - 1.0; // SizeMinusOne 8 - 1
  60538. var w = 1 / y; // Space of 1 slice 1 / 8
  60539. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  60540. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  60541. 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
  60542. 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
  60543. 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
  60544. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  60545. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  60546. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  60547. };
  60548. /**
  60549. * Prepare the list of uniforms associated with the ColorGrading effects.
  60550. * @param uniformsList The list of uniforms used in the effect
  60551. * @param samplersList The list of samplers used in the effect
  60552. */
  60553. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  60554. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  60555. samplersList.push("cameraColorGrading2DSampler");
  60556. };
  60557. /**
  60558. * Parses a color grading texture serialized by Babylon.
  60559. * @param parsedTexture The texture information being parsedTexture
  60560. * @param scene The scene to load the texture in
  60561. * @param rootUrl The root url of the data assets to load
  60562. * @return A color gradind texture
  60563. */
  60564. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60565. var texture = null;
  60566. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  60567. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  60568. texture.name = parsedTexture.name;
  60569. texture.level = parsedTexture.level;
  60570. }
  60571. return texture;
  60572. };
  60573. /**
  60574. * Serializes the LUT texture to json format.
  60575. */
  60576. ColorGradingTexture.prototype.serialize = function () {
  60577. if (!this.name) {
  60578. return null;
  60579. }
  60580. var serializationObject = {};
  60581. serializationObject.name = this.name;
  60582. serializationObject.level = this.level;
  60583. serializationObject.customType = "BABYLON.ColorGradingTexture";
  60584. return serializationObject;
  60585. };
  60586. /**
  60587. * Empty line regex stored for GC.
  60588. */
  60589. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  60590. return ColorGradingTexture;
  60591. })(BABYLON.BaseTexture);
  60592. BABYLON.ColorGradingTexture = ColorGradingTexture;
  60593. })(BABYLON || (BABYLON = {}));
  60594. var BABYLON;
  60595. (function (BABYLON) {
  60596. var PBRMaterialDefines = (function (_super) {
  60597. __extends(PBRMaterialDefines, _super);
  60598. function PBRMaterialDefines() {
  60599. _super.call(this);
  60600. this.ALBEDO = false;
  60601. this.AMBIENT = false;
  60602. this.OPACITY = false;
  60603. this.OPACITYRGB = false;
  60604. this.REFLECTION = false;
  60605. this.EMISSIVE = false;
  60606. this.REFLECTIVITY = false;
  60607. this.BUMP = false;
  60608. this.PARALLAX = false;
  60609. this.PARALLAXOCCLUSION = false;
  60610. this.SPECULAROVERALPHA = false;
  60611. this.CLIPPLANE = false;
  60612. this.ALPHATEST = false;
  60613. this.ALPHAFROMALBEDO = false;
  60614. this.POINTSIZE = false;
  60615. this.FOG = false;
  60616. this.SPECULARTERM = false;
  60617. this.OPACITYFRESNEL = false;
  60618. this.EMISSIVEFRESNEL = false;
  60619. this.FRESNEL = false;
  60620. this.NORMAL = false;
  60621. this.UV1 = false;
  60622. this.UV2 = false;
  60623. this.VERTEXCOLOR = false;
  60624. this.VERTEXALPHA = false;
  60625. this.NUM_BONE_INFLUENCERS = 0;
  60626. this.BonesPerMesh = 0;
  60627. this.INSTANCES = false;
  60628. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  60629. this.MICROSURFACEAUTOMATIC = false;
  60630. this.EMISSIVEASILLUMINATION = false;
  60631. this.LINKEMISSIVEWITHALBEDO = false;
  60632. this.LIGHTMAP = false;
  60633. this.USELIGHTMAPASSHADOWMAP = false;
  60634. this.REFLECTIONMAP_3D = false;
  60635. this.REFLECTIONMAP_SPHERICAL = false;
  60636. this.REFLECTIONMAP_PLANAR = false;
  60637. this.REFLECTIONMAP_CUBIC = false;
  60638. this.REFLECTIONMAP_PROJECTION = false;
  60639. this.REFLECTIONMAP_SKYBOX = false;
  60640. this.REFLECTIONMAP_EXPLICIT = false;
  60641. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  60642. this.INVERTCUBICMAP = false;
  60643. this.LOGARITHMICDEPTH = false;
  60644. this.CAMERATONEMAP = false;
  60645. this.CAMERACONTRAST = false;
  60646. this.CAMERACOLORGRADING = false;
  60647. this.CAMERACOLORCURVES = false;
  60648. this.OVERLOADEDVALUES = false;
  60649. this.OVERLOADEDSHADOWVALUES = false;
  60650. this.USESPHERICALFROMREFLECTIONMAP = false;
  60651. this.REFRACTION = false;
  60652. this.REFRACTIONMAP_3D = false;
  60653. this.LINKREFRACTIONTOTRANSPARENCY = false;
  60654. this.REFRACTIONMAPINLINEARSPACE = false;
  60655. this.LODBASEDMICROSFURACE = false;
  60656. this.USEPHYSICALLIGHTFALLOFF = false;
  60657. this.RADIANCEOVERALPHA = false;
  60658. this.USEPMREMREFLECTION = false;
  60659. this.USEPMREMREFRACTION = false;
  60660. this.OPENGLNORMALMAP = false;
  60661. this.INVERTNORMALMAPX = false;
  60662. this.INVERTNORMALMAPY = false;
  60663. this.SHADOWFULLFLOAT = false;
  60664. this.rebuild();
  60665. }
  60666. return PBRMaterialDefines;
  60667. })(BABYLON.MaterialDefines);
  60668. /**
  60669. * The Physically based material of BJS.
  60670. *
  60671. * This offers the main features of a standard PBR material.
  60672. * For more information, please refer to the documentation :
  60673. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  60674. */
  60675. var PBRMaterial = (function (_super) {
  60676. __extends(PBRMaterial, _super);
  60677. /**
  60678. * Instantiates a new PBRMaterial instance.
  60679. *
  60680. * @param name The material name
  60681. * @param scene The scene the material will be use in.
  60682. */
  60683. function PBRMaterial(name, scene) {
  60684. var _this = this;
  60685. _super.call(this, name, scene);
  60686. /**
  60687. * Intensity of the direct lights e.g. the four lights available in your scene.
  60688. * This impacts both the direct diffuse and specular highlights.
  60689. */
  60690. this.directIntensity = 1.0;
  60691. /**
  60692. * Intensity of the emissive part of the material.
  60693. * This helps controlling the emissive effect without modifying the emissive color.
  60694. */
  60695. this.emissiveIntensity = 1.0;
  60696. /**
  60697. * Intensity of the environment e.g. how much the environment will light the object
  60698. * either through harmonics for rough material or through the refelction for shiny ones.
  60699. */
  60700. this.environmentIntensity = 1.0;
  60701. /**
  60702. * This is a special control allowing the reduction of the specular highlights coming from the
  60703. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  60704. */
  60705. this.specularIntensity = 1.0;
  60706. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  60707. /**
  60708. * Debug Control allowing disabling the bump map on this material.
  60709. */
  60710. this.disableBumpMap = false;
  60711. /**
  60712. * Debug Control helping enforcing or dropping the darkness of shadows.
  60713. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  60714. */
  60715. this.overloadedShadowIntensity = 1.0;
  60716. /**
  60717. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  60718. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  60719. */
  60720. this.overloadedShadeIntensity = 1.0;
  60721. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  60722. /**
  60723. * The camera exposure used on this material.
  60724. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  60725. * This corresponds to a photographic exposure.
  60726. */
  60727. this.cameraExposure = 1.0;
  60728. /**
  60729. * The camera contrast used on this material.
  60730. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  60731. */
  60732. this.cameraContrast = 1.0;
  60733. /**
  60734. * Color Grading 2D Lookup Texture.
  60735. * This allows special effects like sepia, black and white to sixties rendering style.
  60736. */
  60737. this.cameraColorGradingTexture = null;
  60738. /**
  60739. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  60740. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  60741. * 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;
  60742. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  60743. */
  60744. this.cameraColorCurves = null;
  60745. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  60746. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  60747. /**
  60748. * Debug Control allowing to overload the ambient color.
  60749. * This as to be use with the overloadedAmbientIntensity parameter.
  60750. */
  60751. this.overloadedAmbient = BABYLON.Color3.White();
  60752. /**
  60753. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  60754. */
  60755. this.overloadedAmbientIntensity = 0.0;
  60756. /**
  60757. * Debug Control allowing to overload the albedo color.
  60758. * This as to be use with the overloadedAlbedoIntensity parameter.
  60759. */
  60760. this.overloadedAlbedo = BABYLON.Color3.White();
  60761. /**
  60762. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  60763. */
  60764. this.overloadedAlbedoIntensity = 0.0;
  60765. /**
  60766. * Debug Control allowing to overload the reflectivity color.
  60767. * This as to be use with the overloadedReflectivityIntensity parameter.
  60768. */
  60769. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  60770. /**
  60771. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  60772. */
  60773. this.overloadedReflectivityIntensity = 0.0;
  60774. /**
  60775. * Debug Control allowing to overload the emissive color.
  60776. * This as to be use with the overloadedEmissiveIntensity parameter.
  60777. */
  60778. this.overloadedEmissive = BABYLON.Color3.White();
  60779. /**
  60780. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  60781. */
  60782. this.overloadedEmissiveIntensity = 0.0;
  60783. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  60784. /**
  60785. * Debug Control allowing to overload the reflection color.
  60786. * This as to be use with the overloadedReflectionIntensity parameter.
  60787. */
  60788. this.overloadedReflection = BABYLON.Color3.White();
  60789. /**
  60790. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  60791. */
  60792. this.overloadedReflectionIntensity = 0.0;
  60793. /**
  60794. * Debug Control allowing to overload the microsurface.
  60795. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  60796. */
  60797. this.overloadedMicroSurface = 0.0;
  60798. /**
  60799. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  60800. */
  60801. this.overloadedMicroSurfaceIntensity = 0.0;
  60802. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  60803. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  60804. /**
  60805. * AKA Diffuse Color in other nomenclature.
  60806. */
  60807. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  60808. /**
  60809. * AKA Specular Color in other nomenclature.
  60810. */
  60811. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  60812. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  60813. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  60814. /**
  60815. * AKA Glossiness in other nomenclature.
  60816. */
  60817. this.microSurface = 0.9;
  60818. /**
  60819. * source material index of refraction (IOR)' / 'destination material IOR.
  60820. */
  60821. this.indexOfRefraction = 0.66;
  60822. /**
  60823. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  60824. */
  60825. this.invertRefractionY = false;
  60826. /**
  60827. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  60828. * Materials half opaque for instance using refraction could benefit from this control.
  60829. */
  60830. this.linkRefractionWithTransparency = false;
  60831. /**
  60832. * The emissive and albedo are linked to never be more than one (Energy conservation).
  60833. */
  60834. this.linkEmissiveWithAlbedo = false;
  60835. this.useLightmapAsShadowmap = false;
  60836. /**
  60837. * In this mode, the emissive informtaion will always be added to the lighting once.
  60838. * A light for instance can be thought as emissive.
  60839. */
  60840. this.useEmissiveAsIllumination = false;
  60841. /**
  60842. * Secifies that the alpha is coming form the albedo channel alpha channel.
  60843. */
  60844. this.useAlphaFromAlbedoTexture = false;
  60845. /**
  60846. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  60847. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  60848. */
  60849. this.useSpecularOverAlpha = true;
  60850. /**
  60851. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  60852. */
  60853. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  60854. /**
  60855. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  60856. * The material will try to infer what glossiness each pixel should be.
  60857. */
  60858. this.useAutoMicroSurfaceFromReflectivityMap = false;
  60859. /**
  60860. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  60861. * the creation of the material.
  60862. */
  60863. this.useScalarInLinearSpace = false;
  60864. /**
  60865. * BJS is using an harcoded light falloff based on a manually sets up range.
  60866. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  60867. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  60868. */
  60869. this.usePhysicalLightFalloff = true;
  60870. /**
  60871. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  60872. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  60873. */
  60874. this.useRadianceOverAlpha = true;
  60875. /**
  60876. * Allows using the bump map in parallax mode.
  60877. */
  60878. this.useParallax = false;
  60879. /**
  60880. * Allows using the bump map in parallax occlusion mode.
  60881. */
  60882. this.useParallaxOcclusion = false;
  60883. /**
  60884. * Controls the scale bias of the parallax mode.
  60885. */
  60886. this.parallaxScaleBias = 0.05;
  60887. /**
  60888. * If sets to true, disables all the lights affecting the material.
  60889. */
  60890. this.disableLighting = false;
  60891. /**
  60892. * Number of Simultaneous lights allowed on the material.
  60893. */
  60894. this.maxSimultaneousLights = 4;
  60895. /**
  60896. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  60897. */
  60898. this.invertNormalMapX = false;
  60899. /**
  60900. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  60901. */
  60902. this.invertNormalMapY = false;
  60903. this._renderTargets = new BABYLON.SmartArray(16);
  60904. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  60905. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  60906. this._tempColor = new BABYLON.Color3();
  60907. this._defines = new PBRMaterialDefines();
  60908. this._cachedDefines = new PBRMaterialDefines();
  60909. this._myScene = null;
  60910. this._myShadowGenerator = null;
  60911. this._cachedDefines.BonesPerMesh = -1;
  60912. this.getRenderTargetTextures = function () {
  60913. _this._renderTargets.reset();
  60914. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  60915. _this._renderTargets.push(_this.reflectionTexture);
  60916. }
  60917. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  60918. _this._renderTargets.push(_this.refractionTexture);
  60919. }
  60920. return _this._renderTargets;
  60921. };
  60922. }
  60923. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  60924. get: function () {
  60925. return this._useLogarithmicDepth;
  60926. },
  60927. set: function (value) {
  60928. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  60929. },
  60930. enumerable: true,
  60931. configurable: true
  60932. });
  60933. PBRMaterial.prototype.needAlphaBlending = function () {
  60934. if (this.linkRefractionWithTransparency) {
  60935. return false;
  60936. }
  60937. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  60938. };
  60939. PBRMaterial.prototype.needAlphaTesting = function () {
  60940. if (this.linkRefractionWithTransparency) {
  60941. return false;
  60942. }
  60943. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  60944. };
  60945. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  60946. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  60947. };
  60948. PBRMaterial.prototype.getAlphaTestTexture = function () {
  60949. return this.albedoTexture;
  60950. };
  60951. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60952. if (!mesh) {
  60953. return true;
  60954. }
  60955. if (this._defines.INSTANCES !== useInstances) {
  60956. return false;
  60957. }
  60958. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  60959. return true;
  60960. }
  60961. return false;
  60962. };
  60963. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  60964. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  60965. };
  60966. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  60967. if (!useScalarInLinear) {
  60968. color.toLinearSpaceToRef(ref);
  60969. }
  60970. else {
  60971. ref.r = color.r;
  60972. ref.g = color.g;
  60973. ref.b = color.b;
  60974. }
  60975. };
  60976. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  60977. var lightIndex = 0;
  60978. var depthValuesAlreadySet = false;
  60979. for (var index = 0; index < scene.lights.length; index++) {
  60980. var light = scene.lights[index];
  60981. if (!light.isEnabled()) {
  60982. continue;
  60983. }
  60984. if (!light.canAffectMesh(mesh)) {
  60985. continue;
  60986. }
  60987. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  60988. // GAMMA CORRECTION.
  60989. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  60990. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  60991. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  60992. if (defines["SPECULARTERM"]) {
  60993. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  60994. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  60995. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  60996. }
  60997. // Shadows
  60998. if (scene.shadowsEnabled) {
  60999. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  61000. }
  61001. lightIndex++;
  61002. if (lightIndex === maxSimultaneousLights)
  61003. break;
  61004. }
  61005. };
  61006. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  61007. if (this.checkReadyOnlyOnce) {
  61008. if (this._wasPreviouslyReady) {
  61009. return true;
  61010. }
  61011. }
  61012. var scene = this.getScene();
  61013. if (!this.checkReadyOnEveryCall) {
  61014. if (this._renderId === scene.getRenderId()) {
  61015. if (this._checkCache(scene, mesh, useInstances)) {
  61016. return true;
  61017. }
  61018. }
  61019. }
  61020. var engine = scene.getEngine();
  61021. var needNormals = false;
  61022. var needUVs = false;
  61023. this._defines.reset();
  61024. if (scene.texturesEnabled) {
  61025. // Textures
  61026. if (scene.texturesEnabled) {
  61027. if (scene.getEngine().getCaps().textureLOD) {
  61028. this._defines.LODBASEDMICROSFURACE = true;
  61029. }
  61030. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  61031. if (!this.albedoTexture.isReady()) {
  61032. return false;
  61033. }
  61034. else {
  61035. needUVs = true;
  61036. this._defines.ALBEDO = true;
  61037. }
  61038. }
  61039. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  61040. if (!this.ambientTexture.isReady()) {
  61041. return false;
  61042. }
  61043. else {
  61044. needUVs = true;
  61045. this._defines.AMBIENT = true;
  61046. }
  61047. }
  61048. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  61049. if (!this.opacityTexture.isReady()) {
  61050. return false;
  61051. }
  61052. else {
  61053. needUVs = true;
  61054. this._defines.OPACITY = true;
  61055. if (this.opacityTexture.getAlphaFromRGB) {
  61056. this._defines.OPACITYRGB = true;
  61057. }
  61058. }
  61059. }
  61060. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  61061. if (!this.reflectionTexture.isReady()) {
  61062. return false;
  61063. }
  61064. else {
  61065. needNormals = true;
  61066. this._defines.REFLECTION = true;
  61067. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  61068. this._defines.INVERTCUBICMAP = true;
  61069. }
  61070. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  61071. switch (this.reflectionTexture.coordinatesMode) {
  61072. case BABYLON.Texture.CUBIC_MODE:
  61073. case BABYLON.Texture.INVCUBIC_MODE:
  61074. this._defines.REFLECTIONMAP_CUBIC = true;
  61075. break;
  61076. case BABYLON.Texture.EXPLICIT_MODE:
  61077. this._defines.REFLECTIONMAP_EXPLICIT = true;
  61078. break;
  61079. case BABYLON.Texture.PLANAR_MODE:
  61080. this._defines.REFLECTIONMAP_PLANAR = true;
  61081. break;
  61082. case BABYLON.Texture.PROJECTION_MODE:
  61083. this._defines.REFLECTIONMAP_PROJECTION = true;
  61084. break;
  61085. case BABYLON.Texture.SKYBOX_MODE:
  61086. this._defines.REFLECTIONMAP_SKYBOX = true;
  61087. break;
  61088. case BABYLON.Texture.SPHERICAL_MODE:
  61089. this._defines.REFLECTIONMAP_SPHERICAL = true;
  61090. break;
  61091. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  61092. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  61093. break;
  61094. }
  61095. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  61096. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  61097. needNormals = true;
  61098. if (this.reflectionTexture.isPMREM) {
  61099. this._defines.USEPMREMREFLECTION = true;
  61100. }
  61101. }
  61102. }
  61103. }
  61104. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  61105. if (!this.lightmapTexture.isReady()) {
  61106. return false;
  61107. }
  61108. else {
  61109. needUVs = true;
  61110. this._defines.LIGHTMAP = true;
  61111. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  61112. }
  61113. }
  61114. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  61115. if (!this.emissiveTexture.isReady()) {
  61116. return false;
  61117. }
  61118. else {
  61119. needUVs = true;
  61120. this._defines.EMISSIVE = true;
  61121. }
  61122. }
  61123. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  61124. if (!this.reflectivityTexture.isReady()) {
  61125. return false;
  61126. }
  61127. else {
  61128. needUVs = true;
  61129. this._defines.REFLECTIVITY = true;
  61130. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  61131. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  61132. }
  61133. }
  61134. }
  61135. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  61136. if (!this.bumpTexture.isReady()) {
  61137. return false;
  61138. }
  61139. else {
  61140. needUVs = true;
  61141. this._defines.BUMP = true;
  61142. if (this.useParallax) {
  61143. this._defines.PARALLAX = true;
  61144. if (this.useParallaxOcclusion) {
  61145. this._defines.PARALLAXOCCLUSION = true;
  61146. }
  61147. }
  61148. if (this.invertNormalMapX) {
  61149. this._defines.INVERTNORMALMAPX = true;
  61150. }
  61151. if (this.invertNormalMapY) {
  61152. this._defines.INVERTNORMALMAPY = true;
  61153. }
  61154. }
  61155. }
  61156. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  61157. if (!this.refractionTexture.isReady()) {
  61158. return false;
  61159. }
  61160. else {
  61161. needUVs = true;
  61162. this._defines.REFRACTION = true;
  61163. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  61164. if (this.linkRefractionWithTransparency) {
  61165. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  61166. }
  61167. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  61168. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  61169. if (this.refractionTexture.isPMREM) {
  61170. this._defines.USEPMREMREFRACTION = true;
  61171. }
  61172. }
  61173. }
  61174. }
  61175. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  61176. if (!this.cameraColorGradingTexture.isReady()) {
  61177. return false;
  61178. }
  61179. else {
  61180. this._defines.CAMERACOLORGRADING = true;
  61181. }
  61182. }
  61183. }
  61184. // Effect
  61185. if (scene.clipPlane) {
  61186. this._defines.CLIPPLANE = true;
  61187. }
  61188. if (engine.getAlphaTesting()) {
  61189. this._defines.ALPHATEST = true;
  61190. }
  61191. if (this._shouldUseAlphaFromAlbedoTexture()) {
  61192. this._defines.ALPHAFROMALBEDO = true;
  61193. }
  61194. if (this.useEmissiveAsIllumination) {
  61195. this._defines.EMISSIVEASILLUMINATION = true;
  61196. }
  61197. if (this.linkEmissiveWithAlbedo) {
  61198. this._defines.LINKEMISSIVEWITHALBEDO = true;
  61199. }
  61200. if (this.useLogarithmicDepth) {
  61201. this._defines.LOGARITHMICDEPTH = true;
  61202. }
  61203. if (this.cameraContrast != 1) {
  61204. this._defines.CAMERACONTRAST = true;
  61205. }
  61206. if (this.cameraExposure != 1) {
  61207. this._defines.CAMERATONEMAP = true;
  61208. }
  61209. if (this.cameraColorCurves) {
  61210. this._defines.CAMERACOLORCURVES = true;
  61211. }
  61212. if (this.overloadedShadeIntensity != 1 ||
  61213. this.overloadedShadowIntensity != 1) {
  61214. this._defines.OVERLOADEDSHADOWVALUES = true;
  61215. }
  61216. if (this.overloadedMicroSurfaceIntensity > 0 ||
  61217. this.overloadedEmissiveIntensity > 0 ||
  61218. this.overloadedReflectivityIntensity > 0 ||
  61219. this.overloadedAlbedoIntensity > 0 ||
  61220. this.overloadedAmbientIntensity > 0 ||
  61221. this.overloadedReflectionIntensity > 0) {
  61222. this._defines.OVERLOADEDVALUES = true;
  61223. }
  61224. // Point size
  61225. if (this.pointsCloud || scene.forcePointsCloud) {
  61226. this._defines.POINTSIZE = true;
  61227. }
  61228. // Fog
  61229. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  61230. this._defines.FOG = true;
  61231. }
  61232. if (scene.lightsEnabled && !this.disableLighting) {
  61233. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  61234. }
  61235. if (BABYLON.StandardMaterial.FresnelEnabled) {
  61236. // Fresnel
  61237. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  61238. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61239. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  61240. this._defines.OPACITYFRESNEL = true;
  61241. }
  61242. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61243. this._defines.EMISSIVEFRESNEL = true;
  61244. }
  61245. needNormals = true;
  61246. this._defines.FRESNEL = true;
  61247. }
  61248. }
  61249. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  61250. this._defines.SPECULAROVERALPHA = true;
  61251. }
  61252. if (this.usePhysicalLightFalloff) {
  61253. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  61254. }
  61255. if (this.useRadianceOverAlpha) {
  61256. this._defines.RADIANCEOVERALPHA = true;
  61257. }
  61258. // Attribs
  61259. if (mesh) {
  61260. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61261. this._defines.NORMAL = true;
  61262. }
  61263. if (needUVs) {
  61264. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61265. this._defines.UV1 = true;
  61266. }
  61267. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61268. this._defines.UV2 = true;
  61269. }
  61270. }
  61271. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  61272. this._defines.VERTEXCOLOR = true;
  61273. if (mesh.hasVertexAlpha) {
  61274. this._defines.VERTEXALPHA = true;
  61275. }
  61276. }
  61277. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61278. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  61279. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  61280. }
  61281. // Instances
  61282. if (useInstances) {
  61283. this._defines.INSTANCES = true;
  61284. }
  61285. }
  61286. // Get correct effect
  61287. if (!this._defines.isEqual(this._cachedDefines)) {
  61288. this._defines.cloneTo(this._cachedDefines);
  61289. scene.resetCachedMaterial();
  61290. // Fallbacks
  61291. var fallbacks = new BABYLON.EffectFallbacks();
  61292. if (this._defines.REFLECTION) {
  61293. fallbacks.addFallback(0, "REFLECTION");
  61294. }
  61295. if (this._defines.REFRACTION) {
  61296. fallbacks.addFallback(0, "REFRACTION");
  61297. }
  61298. if (this._defines.REFLECTIVITY) {
  61299. fallbacks.addFallback(0, "REFLECTIVITY");
  61300. }
  61301. if (this._defines.BUMP) {
  61302. fallbacks.addFallback(0, "BUMP");
  61303. }
  61304. if (this._defines.PARALLAX) {
  61305. fallbacks.addFallback(1, "PARALLAX");
  61306. }
  61307. if (this._defines.PARALLAXOCCLUSION) {
  61308. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  61309. }
  61310. if (this._defines.SPECULAROVERALPHA) {
  61311. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  61312. }
  61313. if (this._defines.FOG) {
  61314. fallbacks.addFallback(1, "FOG");
  61315. }
  61316. if (this._defines.POINTSIZE) {
  61317. fallbacks.addFallback(0, "POINTSIZE");
  61318. }
  61319. if (this._defines.LOGARITHMICDEPTH) {
  61320. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  61321. }
  61322. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  61323. if (this._defines.SPECULARTERM) {
  61324. fallbacks.addFallback(0, "SPECULARTERM");
  61325. }
  61326. if (this._defines.OPACITYFRESNEL) {
  61327. fallbacks.addFallback(1, "OPACITYFRESNEL");
  61328. }
  61329. if (this._defines.EMISSIVEFRESNEL) {
  61330. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  61331. }
  61332. if (this._defines.FRESNEL) {
  61333. fallbacks.addFallback(3, "FRESNEL");
  61334. }
  61335. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  61336. fallbacks.addCPUSkinningFallback(0, mesh);
  61337. }
  61338. //Attributes
  61339. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61340. if (this._defines.NORMAL) {
  61341. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61342. }
  61343. if (this._defines.UV1) {
  61344. attribs.push(BABYLON.VertexBuffer.UVKind);
  61345. }
  61346. if (this._defines.UV2) {
  61347. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61348. }
  61349. if (this._defines.VERTEXCOLOR) {
  61350. attribs.push(BABYLON.VertexBuffer.ColorKind);
  61351. }
  61352. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  61353. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  61354. // Legacy browser patch
  61355. var shaderName = "pbr";
  61356. if (!scene.getEngine().getCaps().standardDerivatives) {
  61357. shaderName = "legacypbr";
  61358. }
  61359. var join = this._defines.toString();
  61360. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  61361. "vFogInfos", "vFogColor", "pointSize",
  61362. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  61363. "mBones",
  61364. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  61365. "depthValues",
  61366. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  61367. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  61368. "logarithmicDepthConstant",
  61369. "vSphericalX", "vSphericalY", "vSphericalZ",
  61370. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  61371. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  61372. "vMicrosurfaceTextureLods",
  61373. "vCameraInfos"
  61374. ];
  61375. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  61376. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  61377. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  61378. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  61379. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  61380. }
  61381. if (!this._effect.isReady()) {
  61382. return false;
  61383. }
  61384. this._renderId = scene.getRenderId();
  61385. this._wasPreviouslyReady = true;
  61386. if (mesh) {
  61387. if (!mesh._materialDefines) {
  61388. mesh._materialDefines = new PBRMaterialDefines();
  61389. }
  61390. this._defines.cloneTo(mesh._materialDefines);
  61391. }
  61392. return true;
  61393. };
  61394. PBRMaterial.prototype.unbind = function () {
  61395. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  61396. this._effect.setTexture("reflection2DSampler", null);
  61397. }
  61398. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  61399. this._effect.setTexture("refraction2DSampler", null);
  61400. }
  61401. _super.prototype.unbind.call(this);
  61402. };
  61403. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  61404. this._effect.setMatrix("world", world);
  61405. };
  61406. PBRMaterial.prototype.bind = function (world, mesh) {
  61407. this._myScene = this.getScene();
  61408. // Matrices
  61409. this.bindOnlyWorldMatrix(world);
  61410. // Bones
  61411. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  61412. if (this._myScene.getCachedMaterial() !== this) {
  61413. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  61414. if (BABYLON.StandardMaterial.FresnelEnabled) {
  61415. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  61416. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  61417. }
  61418. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61419. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  61420. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  61421. }
  61422. }
  61423. // Textures
  61424. if (this._myScene.texturesEnabled) {
  61425. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  61426. this._effect.setTexture("albedoSampler", this.albedoTexture);
  61427. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  61428. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  61429. }
  61430. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  61431. this._effect.setTexture("ambientSampler", this.ambientTexture);
  61432. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  61433. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  61434. }
  61435. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  61436. this._effect.setTexture("opacitySampler", this.opacityTexture);
  61437. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  61438. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  61439. }
  61440. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  61441. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  61442. if (this.reflectionTexture.isCube) {
  61443. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  61444. }
  61445. else {
  61446. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  61447. }
  61448. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  61449. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  61450. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  61451. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  61452. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  61453. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  61454. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  61455. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  61456. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  61457. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  61458. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  61459. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  61460. }
  61461. }
  61462. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  61463. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  61464. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  61465. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  61466. }
  61467. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  61468. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  61469. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  61470. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  61471. }
  61472. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  61473. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  61474. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  61475. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  61476. }
  61477. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  61478. this._effect.setTexture("bumpSampler", this.bumpTexture);
  61479. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  61480. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  61481. }
  61482. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  61483. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  61484. var depth = 1.0;
  61485. if (this.refractionTexture.isCube) {
  61486. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  61487. }
  61488. else {
  61489. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  61490. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  61491. if (this.refractionTexture.depth) {
  61492. depth = this.refractionTexture.depth;
  61493. }
  61494. }
  61495. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  61496. }
  61497. if ((this.reflectionTexture || this.refractionTexture)) {
  61498. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  61499. }
  61500. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  61501. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  61502. }
  61503. }
  61504. // Clip plane
  61505. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  61506. // Point size
  61507. if (this.pointsCloud) {
  61508. this._effect.setFloat("pointSize", this.pointSize);
  61509. }
  61510. // Colors
  61511. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  61512. // GAMMA CORRECTION.
  61513. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  61514. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  61515. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  61516. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  61517. // GAMMA CORRECTION.
  61518. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  61519. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  61520. // GAMMA CORRECTION.
  61521. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  61522. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  61523. }
  61524. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  61525. // GAMMA CORRECTION.
  61526. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  61527. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  61528. // Lights
  61529. if (this._myScene.lightsEnabled && !this.disableLighting) {
  61530. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  61531. }
  61532. // View
  61533. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  61534. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  61535. }
  61536. // Fog
  61537. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  61538. this._lightingInfos.x = this.directIntensity;
  61539. this._lightingInfos.y = this.emissiveIntensity;
  61540. this._lightingInfos.z = this.environmentIntensity;
  61541. this._lightingInfos.w = this.specularIntensity;
  61542. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  61543. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  61544. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  61545. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  61546. this._cameraInfos.x = this.cameraExposure;
  61547. this._cameraInfos.y = this.cameraContrast;
  61548. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  61549. if (this.cameraColorCurves) {
  61550. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  61551. }
  61552. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  61553. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  61554. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  61555. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  61556. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  61557. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  61558. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  61559. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  61560. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  61561. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  61562. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  61563. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  61564. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  61565. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  61566. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  61567. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  61568. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  61569. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  61570. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  61571. // Log. depth
  61572. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  61573. }
  61574. _super.prototype.bind.call(this, world, mesh);
  61575. this._myScene = null;
  61576. };
  61577. PBRMaterial.prototype.getAnimatables = function () {
  61578. var results = [];
  61579. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  61580. results.push(this.albedoTexture);
  61581. }
  61582. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  61583. results.push(this.ambientTexture);
  61584. }
  61585. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  61586. results.push(this.opacityTexture);
  61587. }
  61588. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  61589. results.push(this.reflectionTexture);
  61590. }
  61591. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  61592. results.push(this.emissiveTexture);
  61593. }
  61594. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  61595. results.push(this.reflectivityTexture);
  61596. }
  61597. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  61598. results.push(this.bumpTexture);
  61599. }
  61600. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  61601. results.push(this.lightmapTexture);
  61602. }
  61603. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  61604. results.push(this.refractionTexture);
  61605. }
  61606. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  61607. results.push(this.cameraColorGradingTexture);
  61608. }
  61609. return results;
  61610. };
  61611. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61612. if (forceDisposeTextures) {
  61613. if (this.albedoTexture) {
  61614. this.albedoTexture.dispose();
  61615. }
  61616. if (this.ambientTexture) {
  61617. this.ambientTexture.dispose();
  61618. }
  61619. if (this.opacityTexture) {
  61620. this.opacityTexture.dispose();
  61621. }
  61622. if (this.reflectionTexture) {
  61623. this.reflectionTexture.dispose();
  61624. }
  61625. if (this.emissiveTexture) {
  61626. this.emissiveTexture.dispose();
  61627. }
  61628. if (this.reflectivityTexture) {
  61629. this.reflectivityTexture.dispose();
  61630. }
  61631. if (this.bumpTexture) {
  61632. this.bumpTexture.dispose();
  61633. }
  61634. if (this.lightmapTexture) {
  61635. this.lightmapTexture.dispose();
  61636. }
  61637. if (this.refractionTexture) {
  61638. this.refractionTexture.dispose();
  61639. }
  61640. if (this.cameraColorGradingTexture) {
  61641. this.cameraColorGradingTexture.dispose();
  61642. }
  61643. }
  61644. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61645. };
  61646. PBRMaterial.prototype.clone = function (name) {
  61647. var _this = this;
  61648. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  61649. };
  61650. PBRMaterial.prototype.serialize = function () {
  61651. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61652. serializationObject.customType = "BABYLON.PBRMaterial";
  61653. return serializationObject;
  61654. };
  61655. // Statics
  61656. PBRMaterial.Parse = function (source, scene, rootUrl) {
  61657. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  61658. };
  61659. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  61660. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  61661. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  61662. PBRMaterial._scaledReflection = new BABYLON.Color3();
  61663. __decorate([
  61664. BABYLON.serialize()
  61665. ], PBRMaterial.prototype, "directIntensity", void 0);
  61666. __decorate([
  61667. BABYLON.serialize()
  61668. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  61669. __decorate([
  61670. BABYLON.serialize()
  61671. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  61672. __decorate([
  61673. BABYLON.serialize()
  61674. ], PBRMaterial.prototype, "specularIntensity", void 0);
  61675. __decorate([
  61676. BABYLON.serialize()
  61677. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  61678. __decorate([
  61679. BABYLON.serialize()
  61680. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  61681. __decorate([
  61682. BABYLON.serialize()
  61683. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  61684. __decorate([
  61685. BABYLON.serialize()
  61686. ], PBRMaterial.prototype, "cameraExposure", void 0);
  61687. __decorate([
  61688. BABYLON.serialize()
  61689. ], PBRMaterial.prototype, "cameraContrast", void 0);
  61690. __decorate([
  61691. BABYLON.serializeAsTexture()
  61692. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  61693. __decorate([
  61694. BABYLON.serializeAsColorCurves()
  61695. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  61696. __decorate([
  61697. BABYLON.serializeAsColor3()
  61698. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  61699. __decorate([
  61700. BABYLON.serialize()
  61701. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  61702. __decorate([
  61703. BABYLON.serializeAsColor3()
  61704. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  61705. __decorate([
  61706. BABYLON.serialize()
  61707. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  61708. __decorate([
  61709. BABYLON.serializeAsColor3()
  61710. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  61711. __decorate([
  61712. BABYLON.serialize()
  61713. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  61714. __decorate([
  61715. BABYLON.serializeAsColor3()
  61716. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  61717. __decorate([
  61718. BABYLON.serialize()
  61719. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  61720. __decorate([
  61721. BABYLON.serializeAsColor3()
  61722. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  61723. __decorate([
  61724. BABYLON.serialize()
  61725. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  61726. __decorate([
  61727. BABYLON.serialize()
  61728. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  61729. __decorate([
  61730. BABYLON.serialize()
  61731. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  61732. __decorate([
  61733. BABYLON.serializeAsTexture()
  61734. ], PBRMaterial.prototype, "albedoTexture", void 0);
  61735. __decorate([
  61736. BABYLON.serializeAsTexture()
  61737. ], PBRMaterial.prototype, "ambientTexture", void 0);
  61738. __decorate([
  61739. BABYLON.serializeAsTexture()
  61740. ], PBRMaterial.prototype, "opacityTexture", void 0);
  61741. __decorate([
  61742. BABYLON.serializeAsTexture()
  61743. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  61744. __decorate([
  61745. BABYLON.serializeAsTexture()
  61746. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  61747. __decorate([
  61748. BABYLON.serializeAsTexture()
  61749. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  61750. __decorate([
  61751. BABYLON.serializeAsTexture()
  61752. ], PBRMaterial.prototype, "bumpTexture", void 0);
  61753. __decorate([
  61754. BABYLON.serializeAsTexture()
  61755. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  61756. __decorate([
  61757. BABYLON.serializeAsTexture()
  61758. ], PBRMaterial.prototype, "refractionTexture", void 0);
  61759. __decorate([
  61760. BABYLON.serializeAsColor3("ambient")
  61761. ], PBRMaterial.prototype, "ambientColor", void 0);
  61762. __decorate([
  61763. BABYLON.serializeAsColor3("albedo")
  61764. ], PBRMaterial.prototype, "albedoColor", void 0);
  61765. __decorate([
  61766. BABYLON.serializeAsColor3("reflectivity")
  61767. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  61768. __decorate([
  61769. BABYLON.serializeAsColor3("reflection")
  61770. ], PBRMaterial.prototype, "reflectionColor", void 0);
  61771. __decorate([
  61772. BABYLON.serializeAsColor3("emissive")
  61773. ], PBRMaterial.prototype, "emissiveColor", void 0);
  61774. __decorate([
  61775. BABYLON.serialize()
  61776. ], PBRMaterial.prototype, "microSurface", void 0);
  61777. __decorate([
  61778. BABYLON.serialize()
  61779. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  61780. __decorate([
  61781. BABYLON.serialize()
  61782. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  61783. __decorate([
  61784. BABYLON.serializeAsFresnelParameters()
  61785. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  61786. __decorate([
  61787. BABYLON.serializeAsFresnelParameters()
  61788. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  61789. __decorate([
  61790. BABYLON.serialize()
  61791. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  61792. __decorate([
  61793. BABYLON.serialize()
  61794. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  61795. __decorate([
  61796. BABYLON.serialize()
  61797. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  61798. __decorate([
  61799. BABYLON.serialize()
  61800. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  61801. __decorate([
  61802. BABYLON.serialize()
  61803. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  61804. __decorate([
  61805. BABYLON.serialize()
  61806. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  61807. __decorate([
  61808. BABYLON.serialize()
  61809. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  61810. __decorate([
  61811. BABYLON.serialize()
  61812. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  61813. __decorate([
  61814. BABYLON.serialize()
  61815. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  61816. __decorate([
  61817. BABYLON.serialize()
  61818. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  61819. __decorate([
  61820. BABYLON.serialize()
  61821. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  61822. __decorate([
  61823. BABYLON.serialize()
  61824. ], PBRMaterial.prototype, "useParallax", void 0);
  61825. __decorate([
  61826. BABYLON.serialize()
  61827. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  61828. __decorate([
  61829. BABYLON.serialize()
  61830. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  61831. __decorate([
  61832. BABYLON.serialize()
  61833. ], PBRMaterial.prototype, "disableLighting", void 0);
  61834. __decorate([
  61835. BABYLON.serialize()
  61836. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  61837. __decorate([
  61838. BABYLON.serialize()
  61839. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  61840. __decorate([
  61841. BABYLON.serialize()
  61842. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  61843. __decorate([
  61844. BABYLON.serialize()
  61845. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  61846. return PBRMaterial;
  61847. })(BABYLON.Material);
  61848. BABYLON.PBRMaterial = PBRMaterial;
  61849. })(BABYLON || (BABYLON = {}));
  61850. var BABYLON;
  61851. (function (BABYLON) {
  61852. var StandardRenderingPipeline = (function (_super) {
  61853. __extends(StandardRenderingPipeline, _super);
  61854. /**
  61855. * @constructor
  61856. * @param {string} name - The rendering pipeline name
  61857. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61858. * @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)
  61859. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  61860. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61861. */
  61862. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  61863. var _this = this;
  61864. if (originalPostProcess === void 0) { originalPostProcess = null; }
  61865. _super.call(this, scene.getEngine(), name);
  61866. this.downSampleX4PostProcess = null;
  61867. this.brightPassPostProcess = null;
  61868. this.gaussianBlurHPostProcesses = [];
  61869. this.gaussianBlurVPostProcesses = [];
  61870. this.textureAdderPostProcess = null;
  61871. this.depthOfFieldSourcePostProcess = null;
  61872. this.depthOfFieldPostProcess = null;
  61873. this.brightThreshold = 1.0;
  61874. this.gaussianCoefficient = 0.25;
  61875. this.gaussianMean = 1.0;
  61876. this.gaussianStandardDeviation = 1.0;
  61877. this.exposure = 1.0;
  61878. this.lensTexture = null;
  61879. this.depthOfFieldDistance = 10.0;
  61880. this._depthRenderer = null;
  61881. // Getters and setters
  61882. this._blurEnabled = true;
  61883. this._depthOfFieldEnabled = false;
  61884. // Initialize
  61885. this._scene = scene;
  61886. // Create pass post-processe
  61887. if (!originalPostProcess) {
  61888. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  61889. }
  61890. else {
  61891. this.originalPostProcess = originalPostProcess;
  61892. }
  61893. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  61894. // Create down sample X4 post-process
  61895. this._createDownSampleX4PostProcess(scene, ratio / 2);
  61896. // Create bright pass post-process
  61897. this._createBrightPassPostProcess(scene, ratio / 2);
  61898. // Create gaussian blur post-processes (down sampling blurs)
  61899. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  61900. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  61901. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  61902. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  61903. // Create texture adder post-process
  61904. this._createTextureAdderPostProcess(scene, ratio);
  61905. // Create depth-of-field source post-process
  61906. this.depthOfFieldSourcePostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61907. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.depthOfFieldSourcePostProcess; }, true));
  61908. // Create gaussian blur used by depth-of-field
  61909. this._createGaussianBlurPostProcesses(scene, ratio / 2, 4);
  61910. // Create depth-of-field post-process
  61911. this._createDepthOfFieldPostProcess(scene, ratio);
  61912. // Finish
  61913. scene.postProcessRenderPipelineManager.addPipeline(this);
  61914. if (cameras !== null) {
  61915. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  61916. }
  61917. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfFieldSource", cameras);
  61918. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH4", cameras);
  61919. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV4", cameras);
  61920. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", cameras);
  61921. }
  61922. Object.defineProperty(StandardRenderingPipeline.prototype, "BlurEnabled", {
  61923. get: function () {
  61924. return this._blurEnabled;
  61925. },
  61926. set: function (enabled) {
  61927. if (enabled && !this._blurEnabled || !enabled && this._blurEnabled) {
  61928. for (var i = 0; i < this.gaussianBlurHPostProcesses.length - 1; i++) {
  61929. if (enabled) {
  61930. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._scene.cameras);
  61931. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._scene.cameras);
  61932. }
  61933. else {
  61934. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._scene.cameras);
  61935. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._scene.cameras);
  61936. }
  61937. }
  61938. }
  61939. this._blurEnabled = enabled;
  61940. },
  61941. enumerable: true,
  61942. configurable: true
  61943. });
  61944. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  61945. get: function () {
  61946. return this._depthOfFieldEnabled;
  61947. },
  61948. set: function (enabled) {
  61949. if (enabled && !this._depthOfFieldEnabled) {
  61950. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfFieldSource", this._scene.cameras);
  61951. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH4", this._scene.cameras);
  61952. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV4", this._scene.cameras);
  61953. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  61954. this._depthRenderer = this._scene.enableDepthRenderer();
  61955. }
  61956. else if (!enabled && this._depthOfFieldEnabled) {
  61957. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfFieldSource", this._scene.cameras);
  61958. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH4", this._scene.cameras);
  61959. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV4", this._scene.cameras);
  61960. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  61961. }
  61962. this._depthOfFieldEnabled = enabled;
  61963. },
  61964. enumerable: true,
  61965. configurable: true
  61966. });
  61967. // Down Sample X4 Post-Processs
  61968. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  61969. var _this = this;
  61970. var downSampleX4Offsets = new Array(32);
  61971. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61972. this.downSampleX4PostProcess.onApply = function (effect) {
  61973. var id = 0;
  61974. for (var i = -2; i < 2; i++) {
  61975. for (var j = -2; j < 2; j++) {
  61976. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  61977. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  61978. id += 2;
  61979. }
  61980. }
  61981. effect.setArray2("dsOffsets", downSampleX4Offsets);
  61982. };
  61983. // Add to pipeline
  61984. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  61985. };
  61986. // Brightpass Post-Process
  61987. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  61988. var _this = this;
  61989. var brightOffsets = new Array(8);
  61990. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61991. this.brightPassPostProcess.onApply = function (effect) {
  61992. var sU = (1.0 / _this.brightPassPostProcess.width);
  61993. var sV = (1.0 / _this.brightPassPostProcess.height);
  61994. brightOffsets[0] = -0.5 * sU;
  61995. brightOffsets[1] = 0.5 * sV;
  61996. brightOffsets[2] = 0.5 * sU;
  61997. brightOffsets[3] = 0.5 * sV;
  61998. brightOffsets[4] = -0.5 * sU;
  61999. brightOffsets[5] = -0.5 * sV;
  62000. brightOffsets[6] = 0.5 * sU;
  62001. brightOffsets[7] = -0.5 * sV;
  62002. effect.setArray2("dsOffsets", brightOffsets);
  62003. effect.setFloat("brightThreshold", _this.brightThreshold);
  62004. };
  62005. // Add to pipeline
  62006. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  62007. };
  62008. // Create gaussian blur H&V post-processes
  62009. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  62010. var _this = this;
  62011. var blurOffsets = new Array(9);
  62012. var blurWeights = new Array(9);
  62013. var uniforms = ["blurOffsets", "blurWeights"];
  62014. var callback = function (height) {
  62015. return function (effect) {
  62016. // Weights
  62017. var x = 0.0;
  62018. for (var i = 0; i < 9; i++) {
  62019. x = (i - 4.0) / 4.0;
  62020. blurWeights[i] =
  62021. _this.gaussianCoefficient
  62022. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  62023. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  62024. }
  62025. var lastOutputDimensions = {
  62026. width: scene.getEngine().getRenderWidth(),
  62027. height: scene.getEngine().getRenderHeight()
  62028. };
  62029. for (var i = 0; i < 9; i++) {
  62030. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  62031. blurOffsets[i] = value;
  62032. }
  62033. effect.setArray("blurOffsets", blurOffsets);
  62034. effect.setArray("blurWeights", blurWeights);
  62035. };
  62036. };
  62037. // Create horizontal gaussian blur post-processes
  62038. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62039. gaussianBlurHPostProcess.onApply = callback(false);
  62040. // Create vertical gaussian blur post-process
  62041. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62042. gaussianBlurVPostProcess.onApply = callback(true);
  62043. // Add to pipeline
  62044. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  62045. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  62046. // Finish
  62047. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  62048. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  62049. };
  62050. // Create texture adder post-process
  62051. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  62052. var _this = this;
  62053. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  62054. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62055. this.textureAdderPostProcess.onApply = function (effect) {
  62056. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  62057. effect.setTexture("lensSampler", _this.lensTexture);
  62058. effect.setFloat("exposure", _this.exposure);
  62059. };
  62060. // Add to pipeline
  62061. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  62062. };
  62063. // Create depth-of-field post-process
  62064. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  62065. var _this = this;
  62066. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62067. this.depthOfFieldPostProcess.onApply = function (effect) {
  62068. effect.setTextureFromPostProcess("otherSampler", _this.depthOfFieldSourcePostProcess);
  62069. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  62070. effect.setFloat("distance", _this.depthOfFieldDistance);
  62071. };
  62072. // Add to pipeline
  62073. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  62074. };
  62075. return StandardRenderingPipeline;
  62076. })(BABYLON.PostProcessRenderPipeline);
  62077. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  62078. })(BABYLON || (BABYLON = {}));
  62079. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","ellipse2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","ellipse2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","lines2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","lines2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","rect2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","rect2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","sprite2dPixelShader":"varying vec2 vUV;\nvarying float vOpacity;\nuniform bool alphaTest;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest)\n{\nif (color.a<0.95) {\ndiscard;\n}\n}\ncolor.a*=vOpacity;\ngl_FragColor=color;\n}","sprite2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 scaleFactor;\natt vec2 textureSize;\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\nvoid main(void) {\nvec2 pos2;\n\nvec2 off=vec2(0.0,0.0);\nvec2 sfSizeUV=sizeUV*scaleFactor;\nfloat frame=properties.x;\nfloat invertY=properties.y;\nfloat alignToPixel=properties.z;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sfSizeUV.x)+off.x,topLeftUV.y-off.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sfSizeUV.x)+off.x,(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),topLeftUV.y-off.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\nif (alignToPixel == 1.0)\n{\npos.xy=floor(pos2.xy*sizeUV*textureSize);\n} else {\npos.xy=pos2.xy*sizeUV*textureSize;\n}\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n} ","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\ngl_FragColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\ngl_FragColor=color*vColor;\n}","text2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=floor(pos2.xy*superSampleFactor*sizeUV*textureSize); \npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  62080. 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"};
  62081. 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,D=s*c-a*m,q=s*y-h*m,V=e*c-a*u,H=e*y-h*u,N=e*m-s*u;return t.m[0]=R*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=b*F,t.m[1]=-(n*z-r*w+o*v)*F,t.m[5]=(i*z-r*d+o*g)*F,t.m[9]=-(i*w-n*d+o*T)*F,t.m[13]=(i*v-n*g+r*T)*F,t.m[2]=(n*A-r*L+o*C)*F,t.m[6]=-(i*A-r*P+o*Z)*F,t.m[10]=(i*L-n*P+o*S)*F,t.m[14]=-(i*C-n*Z+r*S)*F,t.m[3]=-(n*I-r*D+o*q)*F,t.m[7]=(i*I-r*V+o*H)*F,t.m[11]=-(i*D-n*V+o*N)*F,t.m[15]=(i*q-n*H+r*N)*F,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;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.PerspectiveFovWebVRToRef=function(t,i,n,r,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);r.m[0]=u,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=m,r.m[6]=r.m[7]=0,r.m[8]=(h-a)*u*.5,r.m[9]=-((e-s)*m*.5),r.m[10]=-n/(i-n),r.m[11]=1,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=i*n/(i-n)},t.GetFinalMatrix=function(i,n,r,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,e=-2*n,s=-2*r,h=-2*o;i.m[0]=e*n+1,i.m[1]=s*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=e*r,i.m[5]=s*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=r*n.m[0]+o*n.m[1]+e*n.m[2]+s*n.m[3],a=r*n.m[4]+o*n.m[5]+e*n.m[6]+s*n.m[7],m=r*n.m[8]+o*n.m[9]+e*n.m[10]+s*n.m[11],y=r*n.m[12]+o*n.m[13]+e*n.m[14]+s*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return 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={}));";
  62082. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  62083. module.exports = BABYLON;
  62084. };