babylon.max.js 3.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. })();
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. })();
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = function (left, right) {
  551. var x = (left.x < right.x) ? left.x : right.x;
  552. var y = (left.y < right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. })();
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.TransformCoordinates = function (vector, transformation) {
  834. var result = Vector3.Zero();
  835. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  836. return result;
  837. };
  838. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  839. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  840. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  841. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  842. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  843. result.x = x / w;
  844. result.y = y / w;
  845. result.z = z / w;
  846. };
  847. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  848. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  849. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  850. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  851. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  852. result.x = rx / rw;
  853. result.y = ry / rw;
  854. result.z = rz / rw;
  855. };
  856. Vector3.TransformNormal = function (vector, transformation) {
  857. var result = Vector3.Zero();
  858. Vector3.TransformNormalToRef(vector, transformation, result);
  859. return result;
  860. };
  861. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  862. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  863. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  864. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  865. };
  866. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  867. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  868. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  869. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  870. };
  871. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  872. var squared = amount * amount;
  873. var cubed = amount * squared;
  874. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  875. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  876. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  877. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  878. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  879. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  880. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  881. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  882. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  883. return new Vector3(x, y, z);
  884. };
  885. Vector3.Clamp = function (value, min, max) {
  886. var x = value.x;
  887. x = (x > max.x) ? max.x : x;
  888. x = (x < min.x) ? min.x : x;
  889. var y = value.y;
  890. y = (y > max.y) ? max.y : y;
  891. y = (y < min.y) ? min.y : y;
  892. var z = value.z;
  893. z = (z > max.z) ? max.z : z;
  894. z = (z < min.z) ? min.z : z;
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  898. var squared = amount * amount;
  899. var cubed = amount * squared;
  900. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  901. var part2 = (-2.0 * cubed) + (3.0 * squared);
  902. var part3 = (cubed - (2.0 * squared)) + amount;
  903. var part4 = cubed - squared;
  904. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  905. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  906. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Lerp = function (start, end, amount) {
  910. var x = start.x + ((end.x - start.x) * amount);
  911. var y = start.y + ((end.y - start.y) * amount);
  912. var z = start.z + ((end.z - start.z) * amount);
  913. return new Vector3(x, y, z);
  914. };
  915. Vector3.Dot = function (left, right) {
  916. return (left.x * right.x + left.y * right.y + left.z * right.z);
  917. };
  918. Vector3.Cross = function (left, right) {
  919. var result = Vector3.Zero();
  920. Vector3.CrossToRef(left, right, result);
  921. return result;
  922. };
  923. Vector3.CrossToRef = function (left, right, result) {
  924. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  925. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  926. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  927. result.copyFrom(Tmp.Vector3[0]);
  928. };
  929. Vector3.Normalize = function (vector) {
  930. var result = Vector3.Zero();
  931. Vector3.NormalizeToRef(vector, result);
  932. return result;
  933. };
  934. Vector3.NormalizeToRef = function (vector, result) {
  935. result.copyFrom(vector);
  936. result.normalize();
  937. };
  938. Vector3.Project = function (vector, world, transform, viewport) {
  939. var cw = viewport.width;
  940. var ch = viewport.height;
  941. var cx = viewport.x;
  942. var cy = viewport.y;
  943. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  944. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  945. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  946. world.multiplyToRef(transform, matrix);
  947. matrix.multiplyToRef(viewportMatrix, matrix);
  948. return Vector3.TransformCoordinates(vector, matrix);
  949. };
  950. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  951. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  952. world.multiplyToRef(transform, matrix);
  953. matrix.invert();
  954. source.x = source.x / viewportWidth * 2 - 1;
  955. source.y = -(source.y / viewportHeight * 2 - 1);
  956. var vector = Vector3.TransformCoordinates(source, matrix);
  957. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  958. if (MathTools.WithinEpsilon(num, 1.0)) {
  959. vector = vector.scale(1.0 / num);
  960. }
  961. return vector;
  962. };
  963. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  964. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  965. world.multiplyToRef(view, matrix);
  966. matrix.multiplyToRef(projection, matrix);
  967. matrix.invert();
  968. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  969. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  970. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  971. if (MathTools.WithinEpsilon(num, 1.0)) {
  972. vector = vector.scale(1.0 / num);
  973. }
  974. return vector;
  975. };
  976. Vector3.Minimize = function (left, right) {
  977. var min = left.clone();
  978. min.MinimizeInPlace(right);
  979. return min;
  980. };
  981. Vector3.Maximize = function (left, right) {
  982. var max = left.clone();
  983. max.MaximizeInPlace(right);
  984. return max;
  985. };
  986. Vector3.Distance = function (value1, value2) {
  987. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  988. };
  989. Vector3.DistanceSquared = function (value1, value2) {
  990. var x = value1.x - value2.x;
  991. var y = value1.y - value2.y;
  992. var z = value1.z - value2.z;
  993. return (x * x) + (y * y) + (z * z);
  994. };
  995. Vector3.Center = function (value1, value2) {
  996. var center = value1.add(value2);
  997. center.scaleInPlace(0.5);
  998. return center;
  999. };
  1000. /**
  1001. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1002. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1003. * to something in order to rotate it from its local system to the given target system.
  1004. */
  1005. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1006. var rotation = Vector3.Zero();
  1007. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1008. return rotation;
  1009. };
  1010. /**
  1011. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1012. */
  1013. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1014. var u = axis1.normalize();
  1015. var w = axis3.normalize();
  1016. // world axis
  1017. var X = Axis.X;
  1018. var Y = Axis.Y;
  1019. // equation unknowns and vars
  1020. var yaw = 0.0;
  1021. var pitch = 0.0;
  1022. var roll = 0.0;
  1023. var x = 0.0;
  1024. var y = 0.0;
  1025. var z = 0.0;
  1026. var t = 0.0;
  1027. var sign = -1.0;
  1028. var nbRevert = 0;
  1029. var cross = Tmp.Vector3[0];
  1030. var dot = 0.0;
  1031. // step 1 : rotation around w
  1032. // Rv3(u) = u1, and u1 belongs to plane xOz
  1033. // Rv3(w) = w1 = w invariant
  1034. var u1 = Tmp.Vector3[1];
  1035. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1036. z = 1.0;
  1037. }
  1038. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1039. x = 1.0;
  1040. }
  1041. else {
  1042. t = w.z / w.x;
  1043. x = -t * Math.sqrt(1 / (1 + t * t));
  1044. z = Math.sqrt(1 / (1 + t * t));
  1045. }
  1046. u1.x = x;
  1047. u1.y = y;
  1048. u1.z = z;
  1049. u1.normalize();
  1050. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1051. cross.normalize();
  1052. if (Vector3.Dot(w, cross) < 0) {
  1053. sign = 1.0;
  1054. }
  1055. dot = Vector3.Dot(u, u1);
  1056. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1057. roll = Math.acos(dot) * sign;
  1058. if (Vector3.Dot(u1, X) < 0) {
  1059. roll = Math.PI + roll;
  1060. u1 = u1.scaleInPlace(-1);
  1061. nbRevert++;
  1062. }
  1063. // step 2 : rotate around u1
  1064. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1065. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1066. var w2 = Tmp.Vector3[2];
  1067. var v2 = Tmp.Vector3[3];
  1068. x = 0.0;
  1069. y = 0.0;
  1070. z = 0.0;
  1071. sign = -1.0;
  1072. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1073. x = 1.0;
  1074. }
  1075. else {
  1076. t = u1.z / u1.x;
  1077. x = -t * Math.sqrt(1 / (1 + t * t));
  1078. z = Math.sqrt(1 / (1 + t * t));
  1079. }
  1080. w2.x = x;
  1081. w2.y = y;
  1082. w2.z = z;
  1083. w2.normalize();
  1084. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1085. v2.normalize();
  1086. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1087. cross.normalize();
  1088. if (Vector3.Dot(u1, cross) < 0) {
  1089. sign = 1.0;
  1090. }
  1091. dot = Vector3.Dot(w, w2);
  1092. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1093. pitch = Math.acos(dot) * sign;
  1094. if (Vector3.Dot(v2, Y) < 0) {
  1095. pitch = Math.PI + pitch;
  1096. nbRevert++;
  1097. }
  1098. // step 3 : rotate around v2
  1099. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1100. sign = -1.0;
  1101. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1102. cross.normalize();
  1103. if (Vector3.Dot(cross, Y) < 0) {
  1104. sign = 1.0;
  1105. }
  1106. dot = Vector3.Dot(u1, X);
  1107. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1108. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1109. if (dot < 0 && nbRevert < 2) {
  1110. yaw = Math.PI + yaw;
  1111. }
  1112. ref.x = pitch;
  1113. ref.y = yaw;
  1114. ref.z = roll;
  1115. };
  1116. return Vector3;
  1117. })();
  1118. BABYLON.Vector3 = Vector3;
  1119. //Vector4 class created for EulerAngle class conversion to Quaternion
  1120. var Vector4 = (function () {
  1121. function Vector4(x, y, z, w) {
  1122. this.x = x;
  1123. this.y = y;
  1124. this.z = z;
  1125. this.w = w;
  1126. }
  1127. Vector4.prototype.toString = function () {
  1128. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1129. };
  1130. Vector4.prototype.getClassName = function () {
  1131. return "Vector4";
  1132. };
  1133. Vector4.prototype.getHashCode = function () {
  1134. var hash = this.x || 0;
  1135. hash = (hash * 397) ^ (this.y || 0);
  1136. hash = (hash * 397) ^ (this.z || 0);
  1137. hash = (hash * 397) ^ (this.w || 0);
  1138. return hash;
  1139. };
  1140. // Operators
  1141. Vector4.prototype.asArray = function () {
  1142. var result = [];
  1143. this.toArray(result, 0);
  1144. return result;
  1145. };
  1146. Vector4.prototype.toArray = function (array, index) {
  1147. if (index === undefined) {
  1148. index = 0;
  1149. }
  1150. array[index] = this.x;
  1151. array[index + 1] = this.y;
  1152. array[index + 2] = this.z;
  1153. array[index + 3] = this.w;
  1154. return this;
  1155. };
  1156. Vector4.prototype.addInPlace = function (otherVector) {
  1157. this.x += otherVector.x;
  1158. this.y += otherVector.y;
  1159. this.z += otherVector.z;
  1160. this.w += otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.add = function (otherVector) {
  1164. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1165. };
  1166. Vector4.prototype.addToRef = function (otherVector, result) {
  1167. result.x = this.x + otherVector.x;
  1168. result.y = this.y + otherVector.y;
  1169. result.z = this.z + otherVector.z;
  1170. result.w = this.w + otherVector.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.subtractInPlace = function (otherVector) {
  1174. this.x -= otherVector.x;
  1175. this.y -= otherVector.y;
  1176. this.z -= otherVector.z;
  1177. this.w -= otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.subtract = function (otherVector) {
  1181. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1182. };
  1183. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1184. result.x = this.x - otherVector.x;
  1185. result.y = this.y - otherVector.y;
  1186. result.z = this.z - otherVector.z;
  1187. result.w = this.w - otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1191. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1192. };
  1193. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1194. result.x = this.x - x;
  1195. result.y = this.y - y;
  1196. result.z = this.z - z;
  1197. result.w = this.w - w;
  1198. return this;
  1199. };
  1200. Vector4.prototype.negate = function () {
  1201. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1202. };
  1203. Vector4.prototype.scaleInPlace = function (scale) {
  1204. this.x *= scale;
  1205. this.y *= scale;
  1206. this.z *= scale;
  1207. this.w *= scale;
  1208. return this;
  1209. };
  1210. Vector4.prototype.scale = function (scale) {
  1211. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1212. };
  1213. Vector4.prototype.scaleToRef = function (scale, result) {
  1214. result.x = this.x * scale;
  1215. result.y = this.y * scale;
  1216. result.z = this.z * scale;
  1217. result.w = this.w * scale;
  1218. };
  1219. Vector4.prototype.equals = function (otherVector) {
  1220. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1221. };
  1222. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1223. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1224. return otherVector
  1225. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1226. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1227. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1228. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1229. };
  1230. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1231. return this.x === x && this.y === y && this.z === z && this.w === w;
  1232. };
  1233. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1234. this.x *= otherVector.x;
  1235. this.y *= otherVector.y;
  1236. this.z *= otherVector.z;
  1237. this.w *= otherVector.w;
  1238. return this;
  1239. };
  1240. Vector4.prototype.multiply = function (otherVector) {
  1241. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1242. };
  1243. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1244. result.x = this.x * otherVector.x;
  1245. result.y = this.y * otherVector.y;
  1246. result.z = this.z * otherVector.z;
  1247. result.w = this.w * otherVector.w;
  1248. return this;
  1249. };
  1250. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1251. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1252. };
  1253. Vector4.prototype.divide = function (otherVector) {
  1254. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1255. };
  1256. Vector4.prototype.divideToRef = function (otherVector, result) {
  1257. result.x = this.x / otherVector.x;
  1258. result.y = this.y / otherVector.y;
  1259. result.z = this.z / otherVector.z;
  1260. result.w = this.w / otherVector.w;
  1261. return this;
  1262. };
  1263. Vector4.prototype.MinimizeInPlace = function (other) {
  1264. if (other.x < this.x)
  1265. this.x = other.x;
  1266. if (other.y < this.y)
  1267. this.y = other.y;
  1268. if (other.z < this.z)
  1269. this.z = other.z;
  1270. if (other.w < this.w)
  1271. this.w = other.w;
  1272. return this;
  1273. };
  1274. Vector4.prototype.MaximizeInPlace = function (other) {
  1275. if (other.x > this.x)
  1276. this.x = other.x;
  1277. if (other.y > this.y)
  1278. this.y = other.y;
  1279. if (other.z > this.z)
  1280. this.z = other.z;
  1281. if (other.w > this.w)
  1282. this.w = other.w;
  1283. return this;
  1284. };
  1285. // Properties
  1286. Vector4.prototype.length = function () {
  1287. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1288. };
  1289. Vector4.prototype.lengthSquared = function () {
  1290. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1291. };
  1292. // Methods
  1293. Vector4.prototype.normalize = function () {
  1294. var len = this.length();
  1295. if (len === 0)
  1296. return this;
  1297. var num = 1.0 / len;
  1298. this.x *= num;
  1299. this.y *= num;
  1300. this.z *= num;
  1301. this.w *= num;
  1302. return this;
  1303. };
  1304. Vector4.prototype.toVector3 = function () {
  1305. return new Vector3(this.x, this.y, this.z);
  1306. };
  1307. Vector4.prototype.clone = function () {
  1308. return new Vector4(this.x, this.y, this.z, this.w);
  1309. };
  1310. Vector4.prototype.copyFrom = function (source) {
  1311. this.x = source.x;
  1312. this.y = source.y;
  1313. this.z = source.z;
  1314. this.w = source.w;
  1315. return this;
  1316. };
  1317. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1318. this.x = x;
  1319. this.y = y;
  1320. this.z = z;
  1321. this.w = w;
  1322. return this;
  1323. };
  1324. // Statics
  1325. Vector4.FromArray = function (array, offset) {
  1326. if (!offset) {
  1327. offset = 0;
  1328. }
  1329. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1330. };
  1331. Vector4.FromArrayToRef = function (array, offset, result) {
  1332. result.x = array[offset];
  1333. result.y = array[offset + 1];
  1334. result.z = array[offset + 2];
  1335. result.w = array[offset + 3];
  1336. };
  1337. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1338. result.x = array[offset];
  1339. result.y = array[offset + 1];
  1340. result.z = array[offset + 2];
  1341. result.w = array[offset + 3];
  1342. };
  1343. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1344. result.x = x;
  1345. result.y = y;
  1346. result.z = z;
  1347. result.w = w;
  1348. };
  1349. Vector4.Zero = function () {
  1350. return new Vector4(0, 0, 0, 0);
  1351. };
  1352. Vector4.Normalize = function (vector) {
  1353. var result = Vector4.Zero();
  1354. Vector4.NormalizeToRef(vector, result);
  1355. return result;
  1356. };
  1357. Vector4.NormalizeToRef = function (vector, result) {
  1358. result.copyFrom(vector);
  1359. result.normalize();
  1360. };
  1361. Vector4.Minimize = function (left, right) {
  1362. var min = left.clone();
  1363. min.MinimizeInPlace(right);
  1364. return min;
  1365. };
  1366. Vector4.Maximize = function (left, right) {
  1367. var max = left.clone();
  1368. max.MaximizeInPlace(right);
  1369. return max;
  1370. };
  1371. Vector4.Distance = function (value1, value2) {
  1372. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1373. };
  1374. Vector4.DistanceSquared = function (value1, value2) {
  1375. var x = value1.x - value2.x;
  1376. var y = value1.y - value2.y;
  1377. var z = value1.z - value2.z;
  1378. var w = value1.w - value2.w;
  1379. return (x * x) + (y * y) + (z * z) + (w * w);
  1380. };
  1381. Vector4.Center = function (value1, value2) {
  1382. var center = value1.add(value2);
  1383. center.scaleInPlace(0.5);
  1384. return center;
  1385. };
  1386. return Vector4;
  1387. })();
  1388. BABYLON.Vector4 = Vector4;
  1389. var Size = (function () {
  1390. function Size(width, height) {
  1391. this.width = width;
  1392. this.height = height;
  1393. }
  1394. Size.prototype.toString = function () {
  1395. return "{W: " + this.width + ", H: " + this.height + "}";
  1396. };
  1397. Size.prototype.getClassName = function () {
  1398. return "Size";
  1399. };
  1400. Size.prototype.getHashCode = function () {
  1401. var hash = this.width || 0;
  1402. hash = (hash * 397) ^ (this.height || 0);
  1403. return hash;
  1404. };
  1405. Size.prototype.copyFrom = function (src) {
  1406. this.width = src.width;
  1407. this.height = src.height;
  1408. };
  1409. Size.prototype.copyFromFloats = function (width, height) {
  1410. this.width = width;
  1411. this.height = height;
  1412. };
  1413. Size.prototype.multiplyByFloats = function (w, h) {
  1414. return new Size(this.width * w, this.height * h);
  1415. };
  1416. Size.prototype.clone = function () {
  1417. return new Size(this.width, this.height);
  1418. };
  1419. Size.prototype.equals = function (other) {
  1420. if (!other) {
  1421. return false;
  1422. }
  1423. return (this.width === other.width) && (this.height === other.height);
  1424. };
  1425. Object.defineProperty(Size.prototype, "surface", {
  1426. get: function () {
  1427. return this.width * this.height;
  1428. },
  1429. enumerable: true,
  1430. configurable: true
  1431. });
  1432. Size.Zero = function () {
  1433. return new Size(0, 0);
  1434. };
  1435. Size.prototype.add = function (otherSize) {
  1436. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1437. return r;
  1438. };
  1439. Size.prototype.substract = function (otherSize) {
  1440. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1441. return r;
  1442. };
  1443. Size.Lerp = function (start, end, amount) {
  1444. var w = start.width + ((end.width - start.width) * amount);
  1445. var h = start.height + ((end.height - start.height) * amount);
  1446. return new Size(w, h);
  1447. };
  1448. return Size;
  1449. })();
  1450. BABYLON.Size = Size;
  1451. var Quaternion = (function () {
  1452. function Quaternion(x, y, z, w) {
  1453. if (x === void 0) { x = 0; }
  1454. if (y === void 0) { y = 0; }
  1455. if (z === void 0) { z = 0; }
  1456. if (w === void 0) { w = 1; }
  1457. this.x = x;
  1458. this.y = y;
  1459. this.z = z;
  1460. this.w = w;
  1461. }
  1462. Quaternion.prototype.toString = function () {
  1463. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1464. };
  1465. Quaternion.prototype.getClassName = function () {
  1466. return "Quaternion";
  1467. };
  1468. Quaternion.prototype.getHashCode = function () {
  1469. var hash = this.x || 0;
  1470. hash = (hash * 397) ^ (this.y || 0);
  1471. hash = (hash * 397) ^ (this.z || 0);
  1472. hash = (hash * 397) ^ (this.w || 0);
  1473. return hash;
  1474. };
  1475. Quaternion.prototype.asArray = function () {
  1476. return [this.x, this.y, this.z, this.w];
  1477. };
  1478. Quaternion.prototype.equals = function (otherQuaternion) {
  1479. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1480. };
  1481. Quaternion.prototype.clone = function () {
  1482. return new Quaternion(this.x, this.y, this.z, this.w);
  1483. };
  1484. Quaternion.prototype.copyFrom = function (other) {
  1485. this.x = other.x;
  1486. this.y = other.y;
  1487. this.z = other.z;
  1488. this.w = other.w;
  1489. return this;
  1490. };
  1491. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1492. this.x = x;
  1493. this.y = y;
  1494. this.z = z;
  1495. this.w = w;
  1496. return this;
  1497. };
  1498. Quaternion.prototype.add = function (other) {
  1499. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1500. };
  1501. Quaternion.prototype.subtract = function (other) {
  1502. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1503. };
  1504. Quaternion.prototype.scale = function (value) {
  1505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1506. };
  1507. Quaternion.prototype.multiply = function (q1) {
  1508. var result = new Quaternion(0, 0, 0, 1.0);
  1509. this.multiplyToRef(q1, result);
  1510. return result;
  1511. };
  1512. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1513. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1514. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1515. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1516. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1517. result.copyFromFloats(x, y, z, w);
  1518. return this;
  1519. };
  1520. Quaternion.prototype.multiplyInPlace = function (q1) {
  1521. this.multiplyToRef(q1, this);
  1522. return this;
  1523. };
  1524. Quaternion.prototype.conjugateToRef = function (ref) {
  1525. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1526. return this;
  1527. };
  1528. Quaternion.prototype.conjugateInPlace = function () {
  1529. this.x *= -1;
  1530. this.y *= -1;
  1531. this.z *= -1;
  1532. return this;
  1533. };
  1534. Quaternion.prototype.conjugate = function () {
  1535. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1536. return result;
  1537. };
  1538. Quaternion.prototype.length = function () {
  1539. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1540. };
  1541. Quaternion.prototype.normalize = function () {
  1542. var length = 1.0 / this.length();
  1543. this.x *= length;
  1544. this.y *= length;
  1545. this.z *= length;
  1546. this.w *= length;
  1547. return this;
  1548. };
  1549. Quaternion.prototype.toEulerAngles = function (order) {
  1550. if (order === void 0) { order = "YZX"; }
  1551. var result = Vector3.Zero();
  1552. this.toEulerAnglesToRef(result, order);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1556. if (order === void 0) { order = "YZX"; }
  1557. var heading, attitude, bank;
  1558. var x = this.x, y = this.y, z = this.z, w = this.w;
  1559. switch (order) {
  1560. case "YZX":
  1561. var test = x * y + z * w;
  1562. if (test > 0.499) {
  1563. heading = 2 * Math.atan2(x, w);
  1564. attitude = Math.PI / 2;
  1565. bank = 0;
  1566. }
  1567. if (test < -0.499) {
  1568. heading = -2 * Math.atan2(x, w);
  1569. attitude = -Math.PI / 2;
  1570. bank = 0;
  1571. }
  1572. if (isNaN(heading)) {
  1573. var sqx = x * x;
  1574. var sqy = y * y;
  1575. var sqz = z * z;
  1576. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1577. attitude = Math.asin(2 * test); // attitude
  1578. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1579. }
  1580. break;
  1581. default:
  1582. throw new Error("Euler order " + order + " not supported yet.");
  1583. }
  1584. result.y = heading;
  1585. result.z = attitude;
  1586. result.x = bank;
  1587. return this;
  1588. };
  1589. ;
  1590. Quaternion.prototype.toRotationMatrix = function (result) {
  1591. var xx = this.x * this.x;
  1592. var yy = this.y * this.y;
  1593. var zz = this.z * this.z;
  1594. var xy = this.x * this.y;
  1595. var zw = this.z * this.w;
  1596. var zx = this.z * this.x;
  1597. var yw = this.y * this.w;
  1598. var yz = this.y * this.z;
  1599. var xw = this.x * this.w;
  1600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1601. result.m[1] = 2.0 * (xy + zw);
  1602. result.m[2] = 2.0 * (zx - yw);
  1603. result.m[3] = 0;
  1604. result.m[4] = 2.0 * (xy - zw);
  1605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1606. result.m[6] = 2.0 * (yz + xw);
  1607. result.m[7] = 0;
  1608. result.m[8] = 2.0 * (zx + yw);
  1609. result.m[9] = 2.0 * (yz - xw);
  1610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1611. result.m[11] = 0;
  1612. result.m[12] = 0;
  1613. result.m[13] = 0;
  1614. result.m[14] = 0;
  1615. result.m[15] = 1.0;
  1616. return this;
  1617. };
  1618. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1619. Quaternion.FromRotationMatrixToRef(matrix, this);
  1620. return this;
  1621. };
  1622. // Statics
  1623. Quaternion.FromRotationMatrix = function (matrix) {
  1624. var result = new Quaternion();
  1625. Quaternion.FromRotationMatrixToRef(matrix, result);
  1626. return result;
  1627. };
  1628. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1629. var data = matrix.m;
  1630. var m11 = data[0], m12 = data[4], m13 = data[8];
  1631. var m21 = data[1], m22 = data[5], m23 = data[9];
  1632. var m31 = data[2], m32 = data[6], m33 = data[10];
  1633. var trace = m11 + m22 + m33;
  1634. var s;
  1635. if (trace > 0) {
  1636. s = 0.5 / Math.sqrt(trace + 1.0);
  1637. result.w = 0.25 / s;
  1638. result.x = (m32 - m23) * s;
  1639. result.y = (m13 - m31) * s;
  1640. result.z = (m21 - m12) * s;
  1641. }
  1642. else if (m11 > m22 && m11 > m33) {
  1643. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1644. result.w = (m32 - m23) / s;
  1645. result.x = 0.25 * s;
  1646. result.y = (m12 + m21) / s;
  1647. result.z = (m13 + m31) / s;
  1648. }
  1649. else if (m22 > m33) {
  1650. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1651. result.w = (m13 - m31) / s;
  1652. result.x = (m12 + m21) / s;
  1653. result.y = 0.25 * s;
  1654. result.z = (m23 + m32) / s;
  1655. }
  1656. else {
  1657. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1658. result.w = (m21 - m12) / s;
  1659. result.x = (m13 + m31) / s;
  1660. result.y = (m23 + m32) / s;
  1661. result.z = 0.25 * s;
  1662. }
  1663. };
  1664. Quaternion.Inverse = function (q) {
  1665. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1666. };
  1667. Quaternion.Identity = function () {
  1668. return new Quaternion(0, 0, 0, 1);
  1669. };
  1670. Quaternion.RotationAxis = function (axis, angle) {
  1671. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1672. };
  1673. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1674. var sin = Math.sin(angle / 2);
  1675. axis.normalize();
  1676. result.w = Math.cos(angle / 2);
  1677. result.x = axis.x * sin;
  1678. result.y = axis.y * sin;
  1679. result.z = axis.z * sin;
  1680. return result;
  1681. };
  1682. Quaternion.FromArray = function (array, offset) {
  1683. if (!offset) {
  1684. offset = 0;
  1685. }
  1686. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1687. };
  1688. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1689. var q = new Quaternion();
  1690. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1691. return q;
  1692. };
  1693. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1694. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1695. var halfRoll = roll * 0.5;
  1696. var halfPitch = pitch * 0.5;
  1697. var halfYaw = yaw * 0.5;
  1698. var sinRoll = Math.sin(halfRoll);
  1699. var cosRoll = Math.cos(halfRoll);
  1700. var sinPitch = Math.sin(halfPitch);
  1701. var cosPitch = Math.cos(halfPitch);
  1702. var sinYaw = Math.sin(halfYaw);
  1703. var cosYaw = Math.cos(halfYaw);
  1704. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1705. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1706. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1707. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1708. };
  1709. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1710. var result = new Quaternion();
  1711. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1712. return result;
  1713. };
  1714. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1715. // Produces a quaternion from Euler angles in the z-x-z orientation
  1716. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1717. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1718. var halfBeta = beta * 0.5;
  1719. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1720. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1721. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1722. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1723. };
  1724. Quaternion.Slerp = function (left, right, amount) {
  1725. var num2;
  1726. var num3;
  1727. var num = amount;
  1728. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1729. var flag = false;
  1730. if (num4 < 0) {
  1731. flag = true;
  1732. num4 = -num4;
  1733. }
  1734. if (num4 > 0.999999) {
  1735. num3 = 1 - num;
  1736. num2 = flag ? -num : num;
  1737. }
  1738. else {
  1739. var num5 = Math.acos(num4);
  1740. var num6 = (1.0 / Math.sin(num5));
  1741. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1742. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1743. }
  1744. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1745. };
  1746. return Quaternion;
  1747. })();
  1748. BABYLON.Quaternion = Quaternion;
  1749. var Matrix = (function () {
  1750. function Matrix() {
  1751. this.m = new Float32Array(16);
  1752. }
  1753. // Properties
  1754. Matrix.prototype.isIdentity = function () {
  1755. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1756. return false;
  1757. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1758. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1759. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1760. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1761. return false;
  1762. return true;
  1763. };
  1764. Matrix.prototype.determinant = function () {
  1765. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1766. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1767. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1768. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1769. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1770. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1771. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1772. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1773. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1774. };
  1775. // Methods
  1776. Matrix.prototype.toArray = function () {
  1777. return this.m;
  1778. };
  1779. Matrix.prototype.asArray = function () {
  1780. return this.toArray();
  1781. };
  1782. Matrix.prototype.invert = function () {
  1783. this.invertToRef(this);
  1784. return this;
  1785. };
  1786. Matrix.prototype.reset = function () {
  1787. for (var index = 0; index < 16; index++) {
  1788. this.m[index] = 0;
  1789. }
  1790. return this;
  1791. };
  1792. Matrix.prototype.add = function (other) {
  1793. var result = new Matrix();
  1794. this.addToRef(other, result);
  1795. return result;
  1796. };
  1797. Matrix.prototype.addToRef = function (other, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = this.m[index] + other.m[index];
  1800. }
  1801. return this;
  1802. };
  1803. Matrix.prototype.addToSelf = function (other) {
  1804. for (var index = 0; index < 16; index++) {
  1805. this.m[index] += other.m[index];
  1806. }
  1807. return this;
  1808. };
  1809. Matrix.prototype.invertToRef = function (other) {
  1810. var l1 = this.m[0];
  1811. var l2 = this.m[1];
  1812. var l3 = this.m[2];
  1813. var l4 = this.m[3];
  1814. var l5 = this.m[4];
  1815. var l6 = this.m[5];
  1816. var l7 = this.m[6];
  1817. var l8 = this.m[7];
  1818. var l9 = this.m[8];
  1819. var l10 = this.m[9];
  1820. var l11 = this.m[10];
  1821. var l12 = this.m[11];
  1822. var l13 = this.m[12];
  1823. var l14 = this.m[13];
  1824. var l15 = this.m[14];
  1825. var l16 = this.m[15];
  1826. var l17 = (l11 * l16) - (l12 * l15);
  1827. var l18 = (l10 * l16) - (l12 * l14);
  1828. var l19 = (l10 * l15) - (l11 * l14);
  1829. var l20 = (l9 * l16) - (l12 * l13);
  1830. var l21 = (l9 * l15) - (l11 * l13);
  1831. var l22 = (l9 * l14) - (l10 * l13);
  1832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1837. var l28 = (l7 * l16) - (l8 * l15);
  1838. var l29 = (l6 * l16) - (l8 * l14);
  1839. var l30 = (l6 * l15) - (l7 * l14);
  1840. var l31 = (l5 * l16) - (l8 * l13);
  1841. var l32 = (l5 * l15) - (l7 * l13);
  1842. var l33 = (l5 * l14) - (l6 * l13);
  1843. var l34 = (l7 * l12) - (l8 * l11);
  1844. var l35 = (l6 * l12) - (l8 * l10);
  1845. var l36 = (l6 * l11) - (l7 * l10);
  1846. var l37 = (l5 * l12) - (l8 * l9);
  1847. var l38 = (l5 * l11) - (l7 * l9);
  1848. var l39 = (l5 * l10) - (l6 * l9);
  1849. other.m[0] = l23 * l27;
  1850. other.m[4] = l24 * l27;
  1851. other.m[8] = l25 * l27;
  1852. other.m[12] = l26 * l27;
  1853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1865. return this;
  1866. };
  1867. Matrix.prototype.setTranslation = function (vector3) {
  1868. this.m[12] = vector3.x;
  1869. this.m[13] = vector3.y;
  1870. this.m[14] = vector3.z;
  1871. return this;
  1872. };
  1873. Matrix.prototype.getTranslation = function () {
  1874. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1875. };
  1876. Matrix.prototype.multiply = function (other) {
  1877. var result = new Matrix();
  1878. this.multiplyToRef(other, result);
  1879. return result;
  1880. };
  1881. Matrix.prototype.copyFrom = function (other) {
  1882. for (var index = 0; index < 16; index++) {
  1883. this.m[index] = other.m[index];
  1884. }
  1885. return this;
  1886. };
  1887. Matrix.prototype.copyToArray = function (array, offset) {
  1888. if (offset === void 0) { offset = 0; }
  1889. for (var index = 0; index < 16; index++) {
  1890. array[offset + index] = this.m[index];
  1891. }
  1892. return this;
  1893. };
  1894. Matrix.prototype.multiplyToRef = function (other, result) {
  1895. this.multiplyToArray(other, result.m, 0);
  1896. return this;
  1897. };
  1898. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1899. var tm0 = this.m[0];
  1900. var tm1 = this.m[1];
  1901. var tm2 = this.m[2];
  1902. var tm3 = this.m[3];
  1903. var tm4 = this.m[4];
  1904. var tm5 = this.m[5];
  1905. var tm6 = this.m[6];
  1906. var tm7 = this.m[7];
  1907. var tm8 = this.m[8];
  1908. var tm9 = this.m[9];
  1909. var tm10 = this.m[10];
  1910. var tm11 = this.m[11];
  1911. var tm12 = this.m[12];
  1912. var tm13 = this.m[13];
  1913. var tm14 = this.m[14];
  1914. var tm15 = this.m[15];
  1915. var om0 = other.m[0];
  1916. var om1 = other.m[1];
  1917. var om2 = other.m[2];
  1918. var om3 = other.m[3];
  1919. var om4 = other.m[4];
  1920. var om5 = other.m[5];
  1921. var om6 = other.m[6];
  1922. var om7 = other.m[7];
  1923. var om8 = other.m[8];
  1924. var om9 = other.m[9];
  1925. var om10 = other.m[10];
  1926. var om11 = other.m[11];
  1927. var om12 = other.m[12];
  1928. var om13 = other.m[13];
  1929. var om14 = other.m[14];
  1930. var om15 = other.m[15];
  1931. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1932. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1933. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1934. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1935. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1936. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1937. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1938. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1939. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1940. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1941. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1942. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1943. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1944. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1945. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1946. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1947. return this;
  1948. };
  1949. Matrix.prototype.equals = function (value) {
  1950. return value &&
  1951. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1952. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1953. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1954. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1955. };
  1956. Matrix.prototype.clone = function () {
  1957. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1958. };
  1959. Matrix.prototype.getClassName = function () {
  1960. return "Matrix";
  1961. };
  1962. Matrix.prototype.getHashCode = function () {
  1963. var hash = this.m[0] || 0;
  1964. for (var i = 1; i < 16; i++) {
  1965. hash = (hash * 397) ^ (this.m[i] || 0);
  1966. }
  1967. return hash;
  1968. };
  1969. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1970. translation.x = this.m[12];
  1971. translation.y = this.m[13];
  1972. translation.z = this.m[14];
  1973. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1974. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1975. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1976. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1977. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1978. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1979. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1980. rotation.x = 0;
  1981. rotation.y = 0;
  1982. rotation.z = 0;
  1983. rotation.w = 1;
  1984. return false;
  1985. }
  1986. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1987. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1988. return true;
  1989. };
  1990. // Statics
  1991. Matrix.FromArray = function (array, offset) {
  1992. var result = new Matrix();
  1993. if (!offset) {
  1994. offset = 0;
  1995. }
  1996. Matrix.FromArrayToRef(array, offset, result);
  1997. return result;
  1998. };
  1999. Matrix.FromArrayToRef = function (array, offset, result) {
  2000. for (var index = 0; index < 16; index++) {
  2001. result.m[index] = array[index + offset];
  2002. }
  2003. };
  2004. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2005. for (var index = 0; index < 16; index++) {
  2006. result.m[index] = array[index + offset] * scale;
  2007. }
  2008. };
  2009. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2010. result.m[0] = initialM11;
  2011. result.m[1] = initialM12;
  2012. result.m[2] = initialM13;
  2013. result.m[3] = initialM14;
  2014. result.m[4] = initialM21;
  2015. result.m[5] = initialM22;
  2016. result.m[6] = initialM23;
  2017. result.m[7] = initialM24;
  2018. result.m[8] = initialM31;
  2019. result.m[9] = initialM32;
  2020. result.m[10] = initialM33;
  2021. result.m[11] = initialM34;
  2022. result.m[12] = initialM41;
  2023. result.m[13] = initialM42;
  2024. result.m[14] = initialM43;
  2025. result.m[15] = initialM44;
  2026. };
  2027. Matrix.prototype.getRow = function (index) {
  2028. if (index < 0 || index > 3) {
  2029. return null;
  2030. }
  2031. var i = index * 4;
  2032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2033. };
  2034. Matrix.prototype.setRow = function (index, row) {
  2035. if (index < 0 || index > 3) {
  2036. return this;
  2037. }
  2038. var i = index * 4;
  2039. this.m[i + 0] = row.x;
  2040. this.m[i + 1] = row.y;
  2041. this.m[i + 2] = row.z;
  2042. this.m[i + 3] = row.w;
  2043. return this;
  2044. };
  2045. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2046. var result = new Matrix();
  2047. result.m[0] = initialM11;
  2048. result.m[1] = initialM12;
  2049. result.m[2] = initialM13;
  2050. result.m[3] = initialM14;
  2051. result.m[4] = initialM21;
  2052. result.m[5] = initialM22;
  2053. result.m[6] = initialM23;
  2054. result.m[7] = initialM24;
  2055. result.m[8] = initialM31;
  2056. result.m[9] = initialM32;
  2057. result.m[10] = initialM33;
  2058. result.m[11] = initialM34;
  2059. result.m[12] = initialM41;
  2060. result.m[13] = initialM42;
  2061. result.m[14] = initialM43;
  2062. result.m[15] = initialM44;
  2063. return result;
  2064. };
  2065. Matrix.Compose = function (scale, rotation, translation) {
  2066. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2067. var rotationMatrix = Matrix.Identity();
  2068. rotation.toRotationMatrix(rotationMatrix);
  2069. result = result.multiply(rotationMatrix);
  2070. result.setTranslation(translation);
  2071. return result;
  2072. };
  2073. Matrix.Identity = function () {
  2074. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2075. };
  2076. Matrix.IdentityToRef = function (result) {
  2077. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2078. };
  2079. Matrix.Zero = function () {
  2080. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2081. };
  2082. Matrix.RotationX = function (angle) {
  2083. var result = new Matrix();
  2084. Matrix.RotationXToRef(angle, result);
  2085. return result;
  2086. };
  2087. Matrix.Invert = function (source) {
  2088. var result = new Matrix();
  2089. source.invertToRef(result);
  2090. return result;
  2091. };
  2092. Matrix.RotationXToRef = function (angle, result) {
  2093. var s = Math.sin(angle);
  2094. var c = Math.cos(angle);
  2095. result.m[0] = 1.0;
  2096. result.m[15] = 1.0;
  2097. result.m[5] = c;
  2098. result.m[10] = c;
  2099. result.m[9] = -s;
  2100. result.m[6] = s;
  2101. result.m[1] = 0;
  2102. result.m[2] = 0;
  2103. result.m[3] = 0;
  2104. result.m[4] = 0;
  2105. result.m[7] = 0;
  2106. result.m[8] = 0;
  2107. result.m[11] = 0;
  2108. result.m[12] = 0;
  2109. result.m[13] = 0;
  2110. result.m[14] = 0;
  2111. };
  2112. Matrix.RotationY = function (angle) {
  2113. var result = new Matrix();
  2114. Matrix.RotationYToRef(angle, result);
  2115. return result;
  2116. };
  2117. Matrix.RotationYToRef = function (angle, result) {
  2118. var s = Math.sin(angle);
  2119. var c = Math.cos(angle);
  2120. result.m[5] = 1.0;
  2121. result.m[15] = 1.0;
  2122. result.m[0] = c;
  2123. result.m[2] = -s;
  2124. result.m[8] = s;
  2125. result.m[10] = c;
  2126. result.m[1] = 0;
  2127. result.m[3] = 0;
  2128. result.m[4] = 0;
  2129. result.m[6] = 0;
  2130. result.m[7] = 0;
  2131. result.m[9] = 0;
  2132. result.m[11] = 0;
  2133. result.m[12] = 0;
  2134. result.m[13] = 0;
  2135. result.m[14] = 0;
  2136. };
  2137. Matrix.RotationZ = function (angle) {
  2138. var result = new Matrix();
  2139. Matrix.RotationZToRef(angle, result);
  2140. return result;
  2141. };
  2142. Matrix.RotationZToRef = function (angle, result) {
  2143. var s = Math.sin(angle);
  2144. var c = Math.cos(angle);
  2145. result.m[10] = 1.0;
  2146. result.m[15] = 1.0;
  2147. result.m[0] = c;
  2148. result.m[1] = s;
  2149. result.m[4] = -s;
  2150. result.m[5] = c;
  2151. result.m[2] = 0;
  2152. result.m[3] = 0;
  2153. result.m[6] = 0;
  2154. result.m[7] = 0;
  2155. result.m[8] = 0;
  2156. result.m[9] = 0;
  2157. result.m[11] = 0;
  2158. result.m[12] = 0;
  2159. result.m[13] = 0;
  2160. result.m[14] = 0;
  2161. };
  2162. Matrix.RotationAxis = function (axis, angle) {
  2163. var result = Matrix.Zero();
  2164. Matrix.RotationAxisToRef(axis, angle, result);
  2165. return result;
  2166. };
  2167. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2168. var s = Math.sin(-angle);
  2169. var c = Math.cos(-angle);
  2170. var c1 = 1 - c;
  2171. axis.normalize();
  2172. result.m[0] = (axis.x * axis.x) * c1 + c;
  2173. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2174. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2175. result.m[3] = 0.0;
  2176. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2177. result.m[5] = (axis.y * axis.y) * c1 + c;
  2178. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2179. result.m[7] = 0.0;
  2180. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2181. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2182. result.m[10] = (axis.z * axis.z) * c1 + c;
  2183. result.m[11] = 0.0;
  2184. result.m[15] = 1.0;
  2185. };
  2186. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2187. var result = new Matrix();
  2188. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2189. return result;
  2190. };
  2191. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2192. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2193. this._tempQuaternion.toRotationMatrix(result);
  2194. };
  2195. Matrix.Scaling = function (x, y, z) {
  2196. var result = Matrix.Zero();
  2197. Matrix.ScalingToRef(x, y, z, result);
  2198. return result;
  2199. };
  2200. Matrix.ScalingToRef = function (x, y, z, result) {
  2201. result.m[0] = x;
  2202. result.m[1] = 0;
  2203. result.m[2] = 0;
  2204. result.m[3] = 0;
  2205. result.m[4] = 0;
  2206. result.m[5] = y;
  2207. result.m[6] = 0;
  2208. result.m[7] = 0;
  2209. result.m[8] = 0;
  2210. result.m[9] = 0;
  2211. result.m[10] = z;
  2212. result.m[11] = 0;
  2213. result.m[12] = 0;
  2214. result.m[13] = 0;
  2215. result.m[14] = 0;
  2216. result.m[15] = 1.0;
  2217. };
  2218. Matrix.Translation = function (x, y, z) {
  2219. var result = Matrix.Identity();
  2220. Matrix.TranslationToRef(x, y, z, result);
  2221. return result;
  2222. };
  2223. Matrix.TranslationToRef = function (x, y, z, result) {
  2224. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2225. };
  2226. Matrix.Lerp = function (startValue, endValue, gradient) {
  2227. var result = Matrix.Zero();
  2228. for (var index = 0; index < 16; index++) {
  2229. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2230. }
  2231. return result;
  2232. };
  2233. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2234. var startScale = new Vector3(0, 0, 0);
  2235. var startRotation = new Quaternion();
  2236. var startTranslation = new Vector3(0, 0, 0);
  2237. startValue.decompose(startScale, startRotation, startTranslation);
  2238. var endScale = new Vector3(0, 0, 0);
  2239. var endRotation = new Quaternion();
  2240. var endTranslation = new Vector3(0, 0, 0);
  2241. endValue.decompose(endScale, endRotation, endTranslation);
  2242. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2243. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2244. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2245. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2246. };
  2247. Matrix.LookAtLH = function (eye, target, up) {
  2248. var result = Matrix.Zero();
  2249. Matrix.LookAtLHToRef(eye, target, up, result);
  2250. return result;
  2251. };
  2252. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2253. // Z axis
  2254. target.subtractToRef(eye, this._zAxis);
  2255. this._zAxis.normalize();
  2256. // X axis
  2257. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2258. if (this._xAxis.lengthSquared() === 0) {
  2259. this._xAxis.x = 1.0;
  2260. }
  2261. else {
  2262. this._xAxis.normalize();
  2263. }
  2264. // Y axis
  2265. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2266. this._yAxis.normalize();
  2267. // Eye angles
  2268. var ex = -Vector3.Dot(this._xAxis, eye);
  2269. var ey = -Vector3.Dot(this._yAxis, eye);
  2270. var ez = -Vector3.Dot(this._zAxis, eye);
  2271. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2272. };
  2273. Matrix.LookAtRH = function (eye, target, up) {
  2274. var result = Matrix.Zero();
  2275. Matrix.LookAtRHToRef(eye, target, up, result);
  2276. return result;
  2277. };
  2278. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2279. // Z axis
  2280. eye.subtractToRef(target, this._zAxis);
  2281. this._zAxis.normalize();
  2282. // X axis
  2283. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2284. if (this._xAxis.lengthSquared() === 0) {
  2285. this._xAxis.x = 1.0;
  2286. }
  2287. else {
  2288. this._xAxis.normalize();
  2289. }
  2290. // Y axis
  2291. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2292. this._yAxis.normalize();
  2293. // Eye angles
  2294. var ex = -Vector3.Dot(this._xAxis, eye);
  2295. var ey = -Vector3.Dot(this._yAxis, eye);
  2296. var ez = -Vector3.Dot(this._zAxis, eye);
  2297. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2298. };
  2299. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2300. var matrix = Matrix.Zero();
  2301. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2302. return matrix;
  2303. };
  2304. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2305. var hw = 2.0 / width;
  2306. var hh = 2.0 / height;
  2307. var id = 1.0 / (zfar - znear);
  2308. var nid = znear / (znear - zfar);
  2309. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2310. };
  2311. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2312. var matrix = Matrix.Zero();
  2313. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2314. return matrix;
  2315. };
  2316. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2317. result.m[0] = 2.0 / (right - left);
  2318. result.m[1] = result.m[2] = result.m[3] = 0;
  2319. result.m[5] = 2.0 / (top - bottom);
  2320. result.m[4] = result.m[6] = result.m[7] = 0;
  2321. result.m[10] = 1.0 / (zfar - znear);
  2322. result.m[8] = result.m[9] = result.m[11] = 0;
  2323. result.m[12] = (left + right) / (left - right);
  2324. result.m[13] = (top + bottom) / (bottom - top);
  2325. result.m[14] = -znear / (zfar - znear);
  2326. result.m[15] = 1.0;
  2327. };
  2328. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2329. var matrix = Matrix.Zero();
  2330. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2331. return matrix;
  2332. };
  2333. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2334. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2335. result.m[10] *= -1.0;
  2336. };
  2337. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2338. var matrix = Matrix.Zero();
  2339. matrix.m[0] = (2.0 * znear) / width;
  2340. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2341. matrix.m[5] = (2.0 * znear) / height;
  2342. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2343. matrix.m[10] = -zfar / (znear - zfar);
  2344. matrix.m[8] = matrix.m[9] = 0.0;
  2345. matrix.m[11] = 1.0;
  2346. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2347. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2348. return matrix;
  2349. };
  2350. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2351. var matrix = Matrix.Zero();
  2352. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2353. return matrix;
  2354. };
  2355. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2356. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2357. var tan = 1.0 / (Math.tan(fov * 0.5));
  2358. if (isVerticalFovFixed) {
  2359. result.m[0] = tan / aspect;
  2360. }
  2361. else {
  2362. result.m[0] = tan;
  2363. }
  2364. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2365. if (isVerticalFovFixed) {
  2366. result.m[5] = tan;
  2367. }
  2368. else {
  2369. result.m[5] = tan * aspect;
  2370. }
  2371. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2372. result.m[8] = result.m[9] = 0.0;
  2373. result.m[10] = zfar / (zfar - znear);
  2374. result.m[11] = 1.0;
  2375. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2376. result.m[14] = -(znear * zfar) / (zfar - znear);
  2377. };
  2378. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2379. var matrix = Matrix.Zero();
  2380. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2381. return matrix;
  2382. };
  2383. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2384. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2385. var tan = 1.0 / (Math.tan(fov * 0.5));
  2386. if (isVerticalFovFixed) {
  2387. result.m[0] = tan / aspect;
  2388. }
  2389. else {
  2390. result.m[0] = tan;
  2391. }
  2392. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2393. if (isVerticalFovFixed) {
  2394. result.m[5] = tan;
  2395. }
  2396. else {
  2397. result.m[5] = tan * aspect;
  2398. }
  2399. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2400. result.m[8] = result.m[9] = 0.0;
  2401. result.m[10] = zfar / (znear - zfar);
  2402. result.m[11] = -1.0;
  2403. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2404. result.m[14] = (znear * zfar) / (znear - zfar);
  2405. };
  2406. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2407. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2408. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2409. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2410. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2411. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2412. var xScale = 2.0 / (leftTan + rightTan);
  2413. var yScale = 2.0 / (upTan + downTan);
  2414. result.m[0] = xScale;
  2415. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2416. result.m[5] = yScale;
  2417. result.m[6] = result.m[7] = 0.0;
  2418. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2419. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2420. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2421. result.m[10] = -zfar / (znear - zfar);
  2422. result.m[11] = 1.0;
  2423. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2424. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2425. result.m[14] = (znear * zfar) / (znear - zfar);
  2426. };
  2427. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2428. var cw = viewport.width;
  2429. var ch = viewport.height;
  2430. var cx = viewport.x;
  2431. var cy = viewport.y;
  2432. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2433. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2434. };
  2435. Matrix.GetAsMatrix2x2 = function (matrix) {
  2436. return new Float32Array([
  2437. matrix.m[0], matrix.m[1],
  2438. matrix.m[4], matrix.m[5]
  2439. ]);
  2440. };
  2441. Matrix.GetAsMatrix3x3 = function (matrix) {
  2442. return new Float32Array([
  2443. matrix.m[0], matrix.m[1], matrix.m[2],
  2444. matrix.m[4], matrix.m[5], matrix.m[6],
  2445. matrix.m[8], matrix.m[9], matrix.m[10]
  2446. ]);
  2447. };
  2448. Matrix.Transpose = function (matrix) {
  2449. var result = new Matrix();
  2450. result.m[0] = matrix.m[0];
  2451. result.m[1] = matrix.m[4];
  2452. result.m[2] = matrix.m[8];
  2453. result.m[3] = matrix.m[12];
  2454. result.m[4] = matrix.m[1];
  2455. result.m[5] = matrix.m[5];
  2456. result.m[6] = matrix.m[9];
  2457. result.m[7] = matrix.m[13];
  2458. result.m[8] = matrix.m[2];
  2459. result.m[9] = matrix.m[6];
  2460. result.m[10] = matrix.m[10];
  2461. result.m[11] = matrix.m[14];
  2462. result.m[12] = matrix.m[3];
  2463. result.m[13] = matrix.m[7];
  2464. result.m[14] = matrix.m[11];
  2465. result.m[15] = matrix.m[15];
  2466. return result;
  2467. };
  2468. Matrix.Reflection = function (plane) {
  2469. var matrix = new Matrix();
  2470. Matrix.ReflectionToRef(plane, matrix);
  2471. return matrix;
  2472. };
  2473. Matrix.ReflectionToRef = function (plane, result) {
  2474. plane.normalize();
  2475. var x = plane.normal.x;
  2476. var y = plane.normal.y;
  2477. var z = plane.normal.z;
  2478. var temp = -2 * x;
  2479. var temp2 = -2 * y;
  2480. var temp3 = -2 * z;
  2481. result.m[0] = (temp * x) + 1;
  2482. result.m[1] = temp2 * x;
  2483. result.m[2] = temp3 * x;
  2484. result.m[3] = 0.0;
  2485. result.m[4] = temp * y;
  2486. result.m[5] = (temp2 * y) + 1;
  2487. result.m[6] = temp3 * y;
  2488. result.m[7] = 0.0;
  2489. result.m[8] = temp * z;
  2490. result.m[9] = temp2 * z;
  2491. result.m[10] = (temp3 * z) + 1;
  2492. result.m[11] = 0.0;
  2493. result.m[12] = temp * plane.d;
  2494. result.m[13] = temp2 * plane.d;
  2495. result.m[14] = temp3 * plane.d;
  2496. result.m[15] = 1.0;
  2497. };
  2498. Matrix._tempQuaternion = new Quaternion();
  2499. Matrix._xAxis = Vector3.Zero();
  2500. Matrix._yAxis = Vector3.Zero();
  2501. Matrix._zAxis = Vector3.Zero();
  2502. return Matrix;
  2503. })();
  2504. BABYLON.Matrix = Matrix;
  2505. var Plane = (function () {
  2506. function Plane(a, b, c, d) {
  2507. this.normal = new Vector3(a, b, c);
  2508. this.d = d;
  2509. }
  2510. Plane.prototype.asArray = function () {
  2511. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2512. };
  2513. // Methods
  2514. Plane.prototype.clone = function () {
  2515. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2516. };
  2517. Plane.prototype.getClassName = function () {
  2518. return "Plane";
  2519. };
  2520. Plane.prototype.getHashCode = function () {
  2521. var hash = this.normal.getHashCode();
  2522. hash = (hash * 397) ^ (this.d || 0);
  2523. return hash;
  2524. };
  2525. Plane.prototype.normalize = function () {
  2526. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2527. var magnitude = 0;
  2528. if (norm !== 0) {
  2529. magnitude = 1.0 / norm;
  2530. }
  2531. this.normal.x *= magnitude;
  2532. this.normal.y *= magnitude;
  2533. this.normal.z *= magnitude;
  2534. this.d *= magnitude;
  2535. return this;
  2536. };
  2537. Plane.prototype.transform = function (transformation) {
  2538. var transposedMatrix = Matrix.Transpose(transformation);
  2539. var x = this.normal.x;
  2540. var y = this.normal.y;
  2541. var z = this.normal.z;
  2542. var d = this.d;
  2543. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2544. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2545. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2546. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2547. return new Plane(normalX, normalY, normalZ, finalD);
  2548. };
  2549. Plane.prototype.dotCoordinate = function (point) {
  2550. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2551. };
  2552. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2553. var x1 = point2.x - point1.x;
  2554. var y1 = point2.y - point1.y;
  2555. var z1 = point2.z - point1.z;
  2556. var x2 = point3.x - point1.x;
  2557. var y2 = point3.y - point1.y;
  2558. var z2 = point3.z - point1.z;
  2559. var yz = (y1 * z2) - (z1 * y2);
  2560. var xz = (z1 * x2) - (x1 * z2);
  2561. var xy = (x1 * y2) - (y1 * x2);
  2562. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2563. var invPyth;
  2564. if (pyth !== 0) {
  2565. invPyth = 1.0 / pyth;
  2566. }
  2567. else {
  2568. invPyth = 0;
  2569. }
  2570. this.normal.x = yz * invPyth;
  2571. this.normal.y = xz * invPyth;
  2572. this.normal.z = xy * invPyth;
  2573. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2574. return this;
  2575. };
  2576. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2577. var dot = Vector3.Dot(this.normal, direction);
  2578. return (dot <= epsilon);
  2579. };
  2580. Plane.prototype.signedDistanceTo = function (point) {
  2581. return Vector3.Dot(point, this.normal) + this.d;
  2582. };
  2583. // Statics
  2584. Plane.FromArray = function (array) {
  2585. return new Plane(array[0], array[1], array[2], array[3]);
  2586. };
  2587. Plane.FromPoints = function (point1, point2, point3) {
  2588. var result = new Plane(0, 0, 0, 0);
  2589. result.copyFromPoints(point1, point2, point3);
  2590. return result;
  2591. };
  2592. Plane.FromPositionAndNormal = function (origin, normal) {
  2593. var result = new Plane(0, 0, 0, 0);
  2594. normal.normalize();
  2595. result.normal = normal;
  2596. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2597. return result;
  2598. };
  2599. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2600. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2601. return Vector3.Dot(point, normal) + d;
  2602. };
  2603. return Plane;
  2604. })();
  2605. BABYLON.Plane = Plane;
  2606. var Viewport = (function () {
  2607. function Viewport(x, y, width, height) {
  2608. this.x = x;
  2609. this.y = y;
  2610. this.width = width;
  2611. this.height = height;
  2612. }
  2613. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2614. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2615. };
  2616. return Viewport;
  2617. })();
  2618. BABYLON.Viewport = Viewport;
  2619. var Frustum = (function () {
  2620. function Frustum() {
  2621. }
  2622. Frustum.GetPlanes = function (transform) {
  2623. var frustumPlanes = [];
  2624. for (var index = 0; index < 6; index++) {
  2625. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2626. }
  2627. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2628. return frustumPlanes;
  2629. };
  2630. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2631. // Near
  2632. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2633. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2634. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2635. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2636. frustumPlanes[0].normalize();
  2637. // Far
  2638. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2639. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2640. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2641. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2642. frustumPlanes[1].normalize();
  2643. // Left
  2644. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2645. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2646. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2647. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2648. frustumPlanes[2].normalize();
  2649. // Right
  2650. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2651. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2652. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2653. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2654. frustumPlanes[3].normalize();
  2655. // Top
  2656. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2657. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2658. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2659. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2660. frustumPlanes[4].normalize();
  2661. // Bottom
  2662. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2663. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2664. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2665. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2666. frustumPlanes[5].normalize();
  2667. };
  2668. return Frustum;
  2669. })();
  2670. BABYLON.Frustum = Frustum;
  2671. (function (Space) {
  2672. Space[Space["LOCAL"] = 0] = "LOCAL";
  2673. Space[Space["WORLD"] = 1] = "WORLD";
  2674. })(BABYLON.Space || (BABYLON.Space = {}));
  2675. var Space = BABYLON.Space;
  2676. var Axis = (function () {
  2677. function Axis() {
  2678. }
  2679. Axis.X = new Vector3(1, 0, 0);
  2680. Axis.Y = new Vector3(0, 1, 0);
  2681. Axis.Z = new Vector3(0, 0, 1);
  2682. return Axis;
  2683. })();
  2684. BABYLON.Axis = Axis;
  2685. ;
  2686. var BezierCurve = (function () {
  2687. function BezierCurve() {
  2688. }
  2689. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2690. // Extract X (which is equal to time here)
  2691. var f0 = 1 - 3 * x2 + 3 * x1;
  2692. var f1 = 3 * x2 - 6 * x1;
  2693. var f2 = 3 * x1;
  2694. var refinedT = t;
  2695. for (var i = 0; i < 5; i++) {
  2696. var refinedT2 = refinedT * refinedT;
  2697. var refinedT3 = refinedT2 * refinedT;
  2698. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2699. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2700. refinedT -= (x - t) * slope;
  2701. refinedT = Math.min(1, Math.max(0, refinedT));
  2702. }
  2703. // Resolve cubic bezier for the given x
  2704. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2705. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2706. Math.pow(refinedT, 3);
  2707. };
  2708. return BezierCurve;
  2709. })();
  2710. BABYLON.BezierCurve = BezierCurve;
  2711. (function (Orientation) {
  2712. Orientation[Orientation["CW"] = 0] = "CW";
  2713. Orientation[Orientation["CCW"] = 1] = "CCW";
  2714. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2715. var Orientation = BABYLON.Orientation;
  2716. var Angle = (function () {
  2717. function Angle(radians) {
  2718. var _this = this;
  2719. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2720. this.radians = function () { return _this._radians; };
  2721. this._radians = radians;
  2722. if (this._radians < 0)
  2723. this._radians += (2 * Math.PI);
  2724. }
  2725. Angle.BetweenTwoPoints = function (a, b) {
  2726. var delta = b.subtract(a);
  2727. var theta = Math.atan2(delta.y, delta.x);
  2728. return new Angle(theta);
  2729. };
  2730. Angle.FromRadians = function (radians) {
  2731. return new Angle(radians);
  2732. };
  2733. Angle.FromDegrees = function (degrees) {
  2734. return new Angle(degrees * Math.PI / 180);
  2735. };
  2736. return Angle;
  2737. })();
  2738. BABYLON.Angle = Angle;
  2739. var Arc2 = (function () {
  2740. function Arc2(startPoint, midPoint, endPoint) {
  2741. this.startPoint = startPoint;
  2742. this.midPoint = midPoint;
  2743. this.endPoint = endPoint;
  2744. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2745. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2746. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2747. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2748. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2749. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2750. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2751. var a1 = this.startAngle.degrees();
  2752. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2753. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2754. // angles correction
  2755. if (a2 - a1 > +180.0)
  2756. a2 -= 360.0;
  2757. if (a2 - a1 < -180.0)
  2758. a2 += 360.0;
  2759. if (a3 - a2 > +180.0)
  2760. a3 -= 360.0;
  2761. if (a3 - a2 < -180.0)
  2762. a3 += 360.0;
  2763. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2764. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2765. }
  2766. return Arc2;
  2767. })();
  2768. BABYLON.Arc2 = Arc2;
  2769. var Path2 = (function () {
  2770. function Path2(x, y) {
  2771. this._points = new Array();
  2772. this._length = 0;
  2773. this.closed = false;
  2774. this._points.push(new Vector2(x, y));
  2775. }
  2776. Path2.prototype.addLineTo = function (x, y) {
  2777. if (closed) {
  2778. //Tools.Error("cannot add lines to closed paths");
  2779. return this;
  2780. }
  2781. var newPoint = new Vector2(x, y);
  2782. var previousPoint = this._points[this._points.length - 1];
  2783. this._points.push(newPoint);
  2784. this._length += newPoint.subtract(previousPoint).length();
  2785. return this;
  2786. };
  2787. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2788. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2789. if (closed) {
  2790. //Tools.Error("cannot add arcs to closed paths");
  2791. return this;
  2792. }
  2793. var startPoint = this._points[this._points.length - 1];
  2794. var midPoint = new Vector2(midX, midY);
  2795. var endPoint = new Vector2(endX, endY);
  2796. var arc = new Arc2(startPoint, midPoint, endPoint);
  2797. var increment = arc.angle.radians() / numberOfSegments;
  2798. if (arc.orientation === Orientation.CW)
  2799. increment *= -1;
  2800. var currentAngle = arc.startAngle.radians() + increment;
  2801. for (var i = 0; i < numberOfSegments; i++) {
  2802. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2803. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2804. this.addLineTo(x, y);
  2805. currentAngle += increment;
  2806. }
  2807. return this;
  2808. };
  2809. Path2.prototype.close = function () {
  2810. this.closed = true;
  2811. return this;
  2812. };
  2813. Path2.prototype.length = function () {
  2814. var result = this._length;
  2815. if (!this.closed) {
  2816. var lastPoint = this._points[this._points.length - 1];
  2817. var firstPoint = this._points[0];
  2818. result += (firstPoint.subtract(lastPoint).length());
  2819. }
  2820. return result;
  2821. };
  2822. Path2.prototype.getPoints = function () {
  2823. return this._points;
  2824. };
  2825. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2826. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2827. //Tools.Error("normalized length position should be between 0 and 1.");
  2828. return Vector2.Zero();
  2829. }
  2830. var lengthPosition = normalizedLengthPosition * this.length();
  2831. var previousOffset = 0;
  2832. for (var i = 0; i < this._points.length; i++) {
  2833. var j = (i + 1) % this._points.length;
  2834. var a = this._points[i];
  2835. var b = this._points[j];
  2836. var bToA = b.subtract(a);
  2837. var nextOffset = (bToA.length() + previousOffset);
  2838. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2839. var dir = bToA.normalize();
  2840. var localOffset = lengthPosition - previousOffset;
  2841. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2842. }
  2843. previousOffset = nextOffset;
  2844. }
  2845. //Tools.Error("internal error");
  2846. return Vector2.Zero();
  2847. };
  2848. Path2.StartingAt = function (x, y) {
  2849. return new Path2(x, y);
  2850. };
  2851. return Path2;
  2852. })();
  2853. BABYLON.Path2 = Path2;
  2854. var Path3D = (function () {
  2855. /**
  2856. * new Path3D(path, normal, raw)
  2857. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2858. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2859. * path : an array of Vector3, the curve axis of the Path3D
  2860. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2861. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2862. */
  2863. function Path3D(path, firstNormal, raw) {
  2864. this.path = path;
  2865. this._curve = new Array();
  2866. this._distances = new Array();
  2867. this._tangents = new Array();
  2868. this._normals = new Array();
  2869. this._binormals = new Array();
  2870. for (var p = 0; p < path.length; p++) {
  2871. this._curve[p] = path[p].clone(); // hard copy
  2872. }
  2873. this._raw = raw || false;
  2874. this._compute(firstNormal);
  2875. }
  2876. /**
  2877. * Returns the Path3D array of successive Vector3 designing its curve.
  2878. */
  2879. Path3D.prototype.getCurve = function () {
  2880. return this._curve;
  2881. };
  2882. /**
  2883. * Returns an array populated with tangent vectors on each Path3D curve point.
  2884. */
  2885. Path3D.prototype.getTangents = function () {
  2886. return this._tangents;
  2887. };
  2888. /**
  2889. * Returns an array populated with normal vectors on each Path3D curve point.
  2890. */
  2891. Path3D.prototype.getNormals = function () {
  2892. return this._normals;
  2893. };
  2894. /**
  2895. * Returns an array populated with binormal vectors on each Path3D curve point.
  2896. */
  2897. Path3D.prototype.getBinormals = function () {
  2898. return this._binormals;
  2899. };
  2900. /**
  2901. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2902. */
  2903. Path3D.prototype.getDistances = function () {
  2904. return this._distances;
  2905. };
  2906. /**
  2907. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2908. * Returns the same object updated.
  2909. */
  2910. Path3D.prototype.update = function (path, firstNormal) {
  2911. for (var p = 0; p < path.length; p++) {
  2912. this._curve[p].x = path[p].x;
  2913. this._curve[p].y = path[p].y;
  2914. this._curve[p].z = path[p].z;
  2915. }
  2916. this._compute(firstNormal);
  2917. return this;
  2918. };
  2919. // private function compute() : computes tangents, normals and binormals
  2920. Path3D.prototype._compute = function (firstNormal) {
  2921. var l = this._curve.length;
  2922. // first and last tangents
  2923. this._tangents[0] = this._getFirstNonNullVector(0);
  2924. if (!this._raw) {
  2925. this._tangents[0].normalize();
  2926. }
  2927. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2928. if (!this._raw) {
  2929. this._tangents[l - 1].normalize();
  2930. }
  2931. // normals and binormals at first point : arbitrary vector with _normalVector()
  2932. var tg0 = this._tangents[0];
  2933. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2934. this._normals[0] = pp0;
  2935. if (!this._raw) {
  2936. this._normals[0].normalize();
  2937. }
  2938. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2939. if (!this._raw) {
  2940. this._binormals[0].normalize();
  2941. }
  2942. this._distances[0] = 0.0;
  2943. // normals and binormals : next points
  2944. var prev; // previous vector (segment)
  2945. var cur; // current vector (segment)
  2946. var curTang; // current tangent
  2947. // previous normal
  2948. var prevBinor; // previous binormal
  2949. for (var i = 1; i < l; i++) {
  2950. // tangents
  2951. prev = this._getLastNonNullVector(i);
  2952. if (i < l - 1) {
  2953. cur = this._getFirstNonNullVector(i);
  2954. this._tangents[i] = prev.add(cur);
  2955. this._tangents[i].normalize();
  2956. }
  2957. this._distances[i] = this._distances[i - 1] + prev.length();
  2958. // normals and binormals
  2959. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2960. curTang = this._tangents[i];
  2961. prevBinor = this._binormals[i - 1];
  2962. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2963. if (!this._raw) {
  2964. this._normals[i].normalize();
  2965. }
  2966. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2967. if (!this._raw) {
  2968. this._binormals[i].normalize();
  2969. }
  2970. }
  2971. };
  2972. // private function getFirstNonNullVector(index)
  2973. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2974. Path3D.prototype._getFirstNonNullVector = function (index) {
  2975. var i = 1;
  2976. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2977. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2978. i++;
  2979. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2980. }
  2981. return nNVector;
  2982. };
  2983. // private function getLastNonNullVector(index)
  2984. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2985. Path3D.prototype._getLastNonNullVector = function (index) {
  2986. var i = 1;
  2987. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2988. while (nLVector.length() === 0 && index > i + 1) {
  2989. i++;
  2990. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2991. }
  2992. return nLVector;
  2993. };
  2994. // private function normalVector(v0, vt, va) :
  2995. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2996. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2997. Path3D.prototype._normalVector = function (v0, vt, va) {
  2998. var normal0;
  2999. var tgl = vt.length();
  3000. if (tgl === 0.0) {
  3001. tgl = 1.0;
  3002. }
  3003. if (va === undefined || va === null) {
  3004. var point;
  3005. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3006. point = new Vector3(0.0, -1.0, 0.0);
  3007. }
  3008. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3009. point = new Vector3(1.0, 0.0, 0.0);
  3010. }
  3011. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3012. point = new Vector3(0.0, 0.0, 1.0);
  3013. }
  3014. normal0 = Vector3.Cross(vt, point);
  3015. }
  3016. else {
  3017. normal0 = Vector3.Cross(vt, va);
  3018. Vector3.CrossToRef(normal0, vt, normal0);
  3019. }
  3020. normal0.normalize();
  3021. return normal0;
  3022. };
  3023. return Path3D;
  3024. })();
  3025. BABYLON.Path3D = Path3D;
  3026. var Curve3 = (function () {
  3027. /**
  3028. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3029. * A Curve3 is designed from a series of successive Vector3.
  3030. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3031. */
  3032. function Curve3(points) {
  3033. this._length = 0.0;
  3034. this._points = points;
  3035. this._length = this._computeLength(points);
  3036. }
  3037. /**
  3038. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3039. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3040. * @param v1 (Vector3) the control point
  3041. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3042. * @param nbPoints (integer) the wanted number of points in the curve
  3043. */
  3044. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3045. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3046. var bez = new Array();
  3047. var equation = function (t, val0, val1, val2) {
  3048. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3049. return res;
  3050. };
  3051. for (var i = 0; i <= nbPoints; i++) {
  3052. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  3053. }
  3054. return new Curve3(bez);
  3055. };
  3056. /**
  3057. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3058. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3059. * @param v1 (Vector3) the first control point
  3060. * @param v2 (Vector3) the second control point
  3061. * @param v3 (Vector3) the end point of the Cubic Bezier
  3062. * @param nbPoints (integer) the wanted number of points in the curve
  3063. */
  3064. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3065. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3066. var bez = new Array();
  3067. var equation = function (t, val0, val1, val2, val3) {
  3068. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  3069. return res;
  3070. };
  3071. for (var i = 0; i <= nbPoints; i++) {
  3072. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  3073. }
  3074. return new Curve3(bez);
  3075. };
  3076. /**
  3077. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3078. * @param p1 (Vector3) the origin point of the Hermite Spline
  3079. * @param t1 (Vector3) the tangent vector at the origin point
  3080. * @param p2 (Vector3) the end point of the Hermite Spline
  3081. * @param t2 (Vector3) the tangent vector at the end point
  3082. * @param nbPoints (integer) the wanted number of points in the curve
  3083. */
  3084. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3085. var hermite = new Array();
  3086. var step = 1.0 / nbPoints;
  3087. for (var i = 0; i <= nbPoints; i++) {
  3088. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3089. }
  3090. return new Curve3(hermite);
  3091. };
  3092. /**
  3093. * Returns the Curve3 stored array of successive Vector3
  3094. */
  3095. Curve3.prototype.getPoints = function () {
  3096. return this._points;
  3097. };
  3098. /**
  3099. * Returns the computed length (float) of the curve.
  3100. */
  3101. Curve3.prototype.length = function () {
  3102. return this._length;
  3103. };
  3104. /**
  3105. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3106. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3107. * curveA and curveB keep unchanged.
  3108. */
  3109. Curve3.prototype.continue = function (curve) {
  3110. var lastPoint = this._points[this._points.length - 1];
  3111. var continuedPoints = this._points.slice();
  3112. var curvePoints = curve.getPoints();
  3113. for (var i = 1; i < curvePoints.length; i++) {
  3114. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3115. }
  3116. var continuedCurve = new Curve3(continuedPoints);
  3117. return continuedCurve;
  3118. };
  3119. Curve3.prototype._computeLength = function (path) {
  3120. var l = 0;
  3121. for (var i = 1; i < path.length; i++) {
  3122. l += (path[i].subtract(path[i - 1])).length();
  3123. }
  3124. return l;
  3125. };
  3126. return Curve3;
  3127. })();
  3128. BABYLON.Curve3 = Curve3;
  3129. // SphericalHarmonics
  3130. var SphericalHarmonics = (function () {
  3131. function SphericalHarmonics() {
  3132. this.L00 = Vector3.Zero();
  3133. this.L1_1 = Vector3.Zero();
  3134. this.L10 = Vector3.Zero();
  3135. this.L11 = Vector3.Zero();
  3136. this.L2_2 = Vector3.Zero();
  3137. this.L2_1 = Vector3.Zero();
  3138. this.L20 = Vector3.Zero();
  3139. this.L21 = Vector3.Zero();
  3140. this.L22 = Vector3.Zero();
  3141. }
  3142. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3143. var colorVector = new Vector3(color.r, color.g, color.b);
  3144. var c = colorVector.scale(deltaSolidAngle);
  3145. this.L00 = this.L00.add(c.scale(0.282095));
  3146. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3147. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3148. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3149. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3150. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3151. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3152. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3153. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3154. };
  3155. SphericalHarmonics.prototype.scale = function (scale) {
  3156. this.L00 = this.L00.scale(scale);
  3157. this.L1_1 = this.L1_1.scale(scale);
  3158. this.L10 = this.L10.scale(scale);
  3159. this.L11 = this.L11.scale(scale);
  3160. this.L2_2 = this.L2_2.scale(scale);
  3161. this.L2_1 = this.L2_1.scale(scale);
  3162. this.L20 = this.L20.scale(scale);
  3163. this.L21 = this.L21.scale(scale);
  3164. this.L22 = this.L22.scale(scale);
  3165. };
  3166. return SphericalHarmonics;
  3167. })();
  3168. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3169. // SphericalPolynomial
  3170. var SphericalPolynomial = (function () {
  3171. function SphericalPolynomial() {
  3172. this.x = Vector3.Zero();
  3173. this.y = Vector3.Zero();
  3174. this.z = Vector3.Zero();
  3175. this.xx = Vector3.Zero();
  3176. this.yy = Vector3.Zero();
  3177. this.zz = Vector3.Zero();
  3178. this.xy = Vector3.Zero();
  3179. this.yz = Vector3.Zero();
  3180. this.zx = Vector3.Zero();
  3181. }
  3182. SphericalPolynomial.prototype.addAmbient = function (color) {
  3183. var colorVector = new Vector3(color.r, color.g, color.b);
  3184. this.xx = this.xx.add(colorVector);
  3185. this.yy = this.yy.add(colorVector);
  3186. this.zz = this.zz.add(colorVector);
  3187. };
  3188. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3189. var result = new SphericalPolynomial();
  3190. result.x = harmonics.L11.scale(1.02333);
  3191. result.y = harmonics.L1_1.scale(1.02333);
  3192. result.z = harmonics.L10.scale(1.02333);
  3193. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3194. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3195. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3196. result.yz = harmonics.L2_1.scale(0.858086);
  3197. result.zx = harmonics.L21.scale(0.858086);
  3198. result.xy = harmonics.L2_2.scale(0.858086);
  3199. return result;
  3200. };
  3201. return SphericalPolynomial;
  3202. })();
  3203. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3204. // Vertex formats
  3205. var PositionNormalVertex = (function () {
  3206. function PositionNormalVertex(position, normal) {
  3207. if (position === void 0) { position = Vector3.Zero(); }
  3208. if (normal === void 0) { normal = Vector3.Up(); }
  3209. this.position = position;
  3210. this.normal = normal;
  3211. }
  3212. PositionNormalVertex.prototype.clone = function () {
  3213. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3214. };
  3215. return PositionNormalVertex;
  3216. })();
  3217. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3218. var PositionNormalTextureVertex = (function () {
  3219. function PositionNormalTextureVertex(position, normal, uv) {
  3220. if (position === void 0) { position = Vector3.Zero(); }
  3221. if (normal === void 0) { normal = Vector3.Up(); }
  3222. if (uv === void 0) { uv = Vector2.Zero(); }
  3223. this.position = position;
  3224. this.normal = normal;
  3225. this.uv = uv;
  3226. }
  3227. PositionNormalTextureVertex.prototype.clone = function () {
  3228. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3229. };
  3230. return PositionNormalTextureVertex;
  3231. })();
  3232. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3233. // Temporary pre-allocated objects for engine internal use
  3234. // usage in any internal function :
  3235. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3236. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3237. var Tmp = (function () {
  3238. function Tmp() {
  3239. }
  3240. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3241. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3242. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3243. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3244. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3245. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3246. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3247. Matrix.Zero(), Matrix.Zero(),
  3248. Matrix.Zero(), Matrix.Zero(),
  3249. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3250. return Tmp;
  3251. })();
  3252. BABYLON.Tmp = Tmp;
  3253. })(BABYLON || (BABYLON = {}));
  3254. var BABYLON;
  3255. (function (BABYLON) {
  3256. function generateSerializableMember(type, sourceName) {
  3257. return function (target, propertyKey) {
  3258. if (!target.__serializableMembers) {
  3259. target.__serializableMembers = {};
  3260. }
  3261. if (!target.__serializableMembers[propertyKey]) {
  3262. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3263. }
  3264. };
  3265. }
  3266. function serialize(sourceName) {
  3267. return generateSerializableMember(0, sourceName); // value member
  3268. }
  3269. BABYLON.serialize = serialize;
  3270. function serializeAsTexture(sourceName) {
  3271. return generateSerializableMember(1, sourceName); // texture member
  3272. }
  3273. BABYLON.serializeAsTexture = serializeAsTexture;
  3274. function serializeAsColor3(sourceName) {
  3275. return generateSerializableMember(2, sourceName); // color3 member
  3276. }
  3277. BABYLON.serializeAsColor3 = serializeAsColor3;
  3278. function serializeAsFresnelParameters(sourceName) {
  3279. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3280. }
  3281. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3282. function serializeAsVector2(sourceName) {
  3283. return generateSerializableMember(4, sourceName); // vector2 member
  3284. }
  3285. BABYLON.serializeAsVector2 = serializeAsVector2;
  3286. function serializeAsVector3(sourceName) {
  3287. return generateSerializableMember(5, sourceName); // vector3 member
  3288. }
  3289. BABYLON.serializeAsVector3 = serializeAsVector3;
  3290. function serializeAsMeshReference(sourceName) {
  3291. return generateSerializableMember(6, sourceName); // mesh reference member
  3292. }
  3293. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3294. function serializeAsColorCurves(sourceName) {
  3295. return generateSerializableMember(7, sourceName); // color curves
  3296. }
  3297. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3298. var SerializationHelper = (function () {
  3299. function SerializationHelper() {
  3300. }
  3301. SerializationHelper.Serialize = function (entity, serializationObject) {
  3302. if (!serializationObject) {
  3303. serializationObject = {};
  3304. }
  3305. // Tags
  3306. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3307. // Properties
  3308. for (var property in entity.__serializableMembers) {
  3309. var propertyDescriptor = entity.__serializableMembers[property];
  3310. var targetPropertyName = propertyDescriptor.sourceName || property;
  3311. var propertyType = propertyDescriptor.type;
  3312. var sourceProperty = entity[property];
  3313. if (sourceProperty !== undefined && sourceProperty !== null) {
  3314. switch (propertyType) {
  3315. case 0:
  3316. serializationObject[targetPropertyName] = sourceProperty;
  3317. break;
  3318. case 1:
  3319. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3320. break;
  3321. case 2:
  3322. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3323. break;
  3324. case 3:
  3325. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3326. break;
  3327. case 4:
  3328. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3329. break;
  3330. case 5:
  3331. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3332. break;
  3333. case 6:
  3334. serializationObject[targetPropertyName] = sourceProperty.id;
  3335. break;
  3336. case 7:
  3337. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3338. break;
  3339. }
  3340. }
  3341. }
  3342. return serializationObject;
  3343. };
  3344. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3345. var destination = creationFunction();
  3346. // Tags
  3347. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3348. // Properties
  3349. for (var property in destination.__serializableMembers) {
  3350. var propertyDescriptor = destination.__serializableMembers[property];
  3351. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3352. var propertyType = propertyDescriptor.type;
  3353. if (sourceProperty !== undefined && sourceProperty !== null) {
  3354. switch (propertyType) {
  3355. case 0:
  3356. destination[property] = sourceProperty;
  3357. break;
  3358. case 1:
  3359. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3360. break;
  3361. case 2:
  3362. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3363. break;
  3364. case 3:
  3365. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3366. break;
  3367. case 4:
  3368. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3369. break;
  3370. case 5:
  3371. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3372. break;
  3373. case 6:
  3374. destination[property] = scene.getLastMeshByID(sourceProperty);
  3375. break;
  3376. case 7:
  3377. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3378. break;
  3379. }
  3380. }
  3381. }
  3382. return destination;
  3383. };
  3384. SerializationHelper.Clone = function (creationFunction, source) {
  3385. var destination = creationFunction();
  3386. // Tags
  3387. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3388. // Properties
  3389. for (var property in destination.__serializableMembers) {
  3390. var propertyDescriptor = destination.__serializableMembers[property];
  3391. var sourceProperty = source[property];
  3392. var propertyType = propertyDescriptor.type;
  3393. if (sourceProperty !== undefined && sourceProperty !== null) {
  3394. switch (propertyType) {
  3395. case 0: // Value
  3396. case 6:
  3397. destination[property] = sourceProperty;
  3398. break;
  3399. case 1: // Texture
  3400. case 2: // Color3
  3401. case 3: // FresnelParameters
  3402. case 4: // Vector2
  3403. case 5: // Vector3
  3404. case 7:
  3405. destination[property] = sourceProperty.clone();
  3406. break;
  3407. }
  3408. }
  3409. }
  3410. return destination;
  3411. };
  3412. return SerializationHelper;
  3413. })();
  3414. BABYLON.SerializationHelper = SerializationHelper;
  3415. })(BABYLON || (BABYLON = {}));
  3416. var BABYLON;
  3417. (function (BABYLON) {
  3418. /**
  3419. * A class serves as a medium between the observable and its observers
  3420. */
  3421. var EventState = (function () {
  3422. /**
  3423. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3424. */
  3425. function EventState(mask, skipNextObservers) {
  3426. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3427. this.initalize(mask, skipNextObservers);
  3428. }
  3429. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3430. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3431. this.mask = mask;
  3432. this.skipNextObservers = skipNextObservers;
  3433. return this;
  3434. };
  3435. return EventState;
  3436. })();
  3437. BABYLON.EventState = EventState;
  3438. /**
  3439. * Represent an Observer registered to a given Observable object.
  3440. */
  3441. var Observer = (function () {
  3442. function Observer(callback, mask) {
  3443. this.callback = callback;
  3444. this.mask = mask;
  3445. }
  3446. return Observer;
  3447. })();
  3448. BABYLON.Observer = Observer;
  3449. /**
  3450. * The Observable class is a simple implementation of the Observable pattern.
  3451. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  3452. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3453. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  3454. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  3455. */
  3456. var Observable = (function () {
  3457. function Observable() {
  3458. this._observers = new Array();
  3459. this._eventState = new EventState(0);
  3460. }
  3461. /**
  3462. * Create a new Observer with the specified callback
  3463. * @param callback the callback that will be executed for that Observer
  3464. * @param mask the mask used to filter observers
  3465. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  3466. */
  3467. Observable.prototype.add = function (callback, mask, insertFirst) {
  3468. if (mask === void 0) { mask = -1; }
  3469. if (insertFirst === void 0) { insertFirst = false; }
  3470. if (!callback) {
  3471. return null;
  3472. }
  3473. var observer = new Observer(callback, mask);
  3474. if (insertFirst) {
  3475. this._observers.unshift(observer);
  3476. }
  3477. else {
  3478. this._observers.push(observer);
  3479. }
  3480. return observer;
  3481. };
  3482. /**
  3483. * Remove an Observer from the Observable object
  3484. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3485. */
  3486. Observable.prototype.remove = function (observer) {
  3487. var index = this._observers.indexOf(observer);
  3488. if (index !== -1) {
  3489. this._observers.splice(index, 1);
  3490. return true;
  3491. }
  3492. return false;
  3493. };
  3494. /**
  3495. * Remove a callback from the Observable object
  3496. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3497. */
  3498. Observable.prototype.removeCallback = function (callback) {
  3499. for (var index = 0; index < this._observers.length; index++) {
  3500. if (this._observers[index].callback === callback) {
  3501. this._observers.splice(index, 1);
  3502. return true;
  3503. }
  3504. }
  3505. return false;
  3506. };
  3507. /**
  3508. * Notify all Observers by calling their respective callback with the given data
  3509. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3510. * @param eventData
  3511. * @param mask
  3512. */
  3513. Observable.prototype.notifyObservers = function (eventData, mask) {
  3514. if (mask === void 0) { mask = -1; }
  3515. var state = this._eventState;
  3516. state.mask = mask;
  3517. state.skipNextObservers = false;
  3518. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3519. var obs = _a[_i];
  3520. if (obs.mask & mask) {
  3521. obs.callback(eventData, state);
  3522. }
  3523. if (state.skipNextObservers) {
  3524. return false;
  3525. }
  3526. }
  3527. return true;
  3528. };
  3529. /**
  3530. * return true is the Observable has at least one Observer registered
  3531. */
  3532. Observable.prototype.hasObservers = function () {
  3533. return this._observers.length > 0;
  3534. };
  3535. /**
  3536. * Clear the list of observers
  3537. */
  3538. Observable.prototype.clear = function () {
  3539. this._observers = new Array();
  3540. };
  3541. /**
  3542. * Clone the current observable
  3543. */
  3544. Observable.prototype.clone = function () {
  3545. var result = new Observable();
  3546. result._observers = this._observers.slice(0);
  3547. return result;
  3548. };
  3549. return Observable;
  3550. })();
  3551. BABYLON.Observable = Observable;
  3552. })(BABYLON || (BABYLON = {}));
  3553. var BABYLON;
  3554. (function (BABYLON) {
  3555. var Database = (function () {
  3556. function Database(urlToScene, callbackManifestChecked) {
  3557. // Handling various flavors of prefixed version of IndexedDB
  3558. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3559. this.callbackManifestChecked = callbackManifestChecked;
  3560. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3561. this.db = null;
  3562. this.enableSceneOffline = false;
  3563. this.enableTexturesOffline = false;
  3564. this.manifestVersionFound = 0;
  3565. this.mustUpdateRessources = false;
  3566. this.hasReachedQuota = false;
  3567. if (!Database.IDBStorageEnabled) {
  3568. this.callbackManifestChecked(true);
  3569. }
  3570. else {
  3571. this.checkManifestFile();
  3572. }
  3573. }
  3574. Database.prototype.checkManifestFile = function () {
  3575. var _this = this;
  3576. function noManifestFile() {
  3577. that.enableSceneOffline = false;
  3578. that.enableTexturesOffline = false;
  3579. that.callbackManifestChecked(false);
  3580. }
  3581. var that = this;
  3582. var timeStampUsed = false;
  3583. var manifestURL = this.currentSceneUrl + ".manifest";
  3584. var xhr = new XMLHttpRequest();
  3585. if (navigator.onLine) {
  3586. // Adding a timestamp to by-pass browsers' cache
  3587. timeStampUsed = true;
  3588. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3589. }
  3590. xhr.open("GET", manifestURL, true);
  3591. xhr.addEventListener("load", function () {
  3592. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3593. try {
  3594. var manifestFile = JSON.parse(xhr.response);
  3595. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3596. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3597. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3598. _this.manifestVersionFound = manifestFile.version;
  3599. }
  3600. if (_this.callbackManifestChecked) {
  3601. _this.callbackManifestChecked(true);
  3602. }
  3603. }
  3604. catch (ex) {
  3605. noManifestFile();
  3606. }
  3607. }
  3608. else {
  3609. noManifestFile();
  3610. }
  3611. }, false);
  3612. xhr.addEventListener("error", function (event) {
  3613. if (timeStampUsed) {
  3614. timeStampUsed = false;
  3615. // Let's retry without the timeStamp
  3616. // It could fail when coupled with HTML5 Offline API
  3617. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3618. xhr.open("GET", retryManifestURL, true);
  3619. xhr.send();
  3620. }
  3621. else {
  3622. noManifestFile();
  3623. }
  3624. }, false);
  3625. try {
  3626. xhr.send();
  3627. }
  3628. catch (ex) {
  3629. BABYLON.Tools.Error("Error on XHR send request.");
  3630. that.callbackManifestChecked(false);
  3631. }
  3632. };
  3633. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3634. var _this = this;
  3635. function handleError() {
  3636. that.isSupported = false;
  3637. if (errorCallback)
  3638. errorCallback();
  3639. }
  3640. var that = this;
  3641. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3642. // Your browser doesn't support IndexedDB
  3643. this.isSupported = false;
  3644. if (errorCallback)
  3645. errorCallback();
  3646. }
  3647. else {
  3648. // If the DB hasn't been opened or created yet
  3649. if (!this.db) {
  3650. this.hasReachedQuota = false;
  3651. this.isSupported = true;
  3652. var request = this.idbFactory.open("babylonjs", 1);
  3653. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3654. request.onerror = function (event) {
  3655. handleError();
  3656. };
  3657. // executes when a version change transaction cannot complete due to other active transactions
  3658. request.onblocked = function (event) {
  3659. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3660. handleError();
  3661. };
  3662. // DB has been opened successfully
  3663. request.onsuccess = function (event) {
  3664. _this.db = request.result;
  3665. successCallback();
  3666. };
  3667. // Initialization of the DB. Creating Scenes & Textures stores
  3668. request.onupgradeneeded = function (event) {
  3669. _this.db = (event.target).result;
  3670. try {
  3671. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3672. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3673. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3674. }
  3675. catch (ex) {
  3676. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3677. handleError();
  3678. }
  3679. };
  3680. }
  3681. else {
  3682. if (successCallback)
  3683. successCallback();
  3684. }
  3685. }
  3686. };
  3687. Database.prototype.loadImageFromDB = function (url, image) {
  3688. var _this = this;
  3689. var completeURL = Database.ReturnFullUrlLocation(url);
  3690. var saveAndLoadImage = function () {
  3691. if (!_this.hasReachedQuota && _this.db !== null) {
  3692. // the texture is not yet in the DB, let's try to save it
  3693. _this._saveImageIntoDBAsync(completeURL, image);
  3694. }
  3695. else {
  3696. image.src = url;
  3697. }
  3698. };
  3699. if (!this.mustUpdateRessources) {
  3700. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3701. }
  3702. else {
  3703. saveAndLoadImage();
  3704. }
  3705. };
  3706. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3707. if (this.isSupported && this.db !== null) {
  3708. var texture;
  3709. var transaction = this.db.transaction(["textures"]);
  3710. transaction.onabort = function (event) {
  3711. image.src = url;
  3712. };
  3713. transaction.oncomplete = function (event) {
  3714. var blobTextureURL;
  3715. if (texture) {
  3716. var URL = window.URL || window.webkitURL;
  3717. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3718. image.onerror = function () {
  3719. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3720. image.src = url;
  3721. };
  3722. image.src = blobTextureURL;
  3723. }
  3724. else {
  3725. notInDBCallback();
  3726. }
  3727. };
  3728. var getRequest = transaction.objectStore("textures").get(url);
  3729. getRequest.onsuccess = function (event) {
  3730. texture = (event.target).result;
  3731. };
  3732. getRequest.onerror = function (event) {
  3733. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3734. image.src = url;
  3735. };
  3736. }
  3737. else {
  3738. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3739. image.src = url;
  3740. }
  3741. };
  3742. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3743. var _this = this;
  3744. if (this.isSupported) {
  3745. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3746. var generateBlobUrl = function () {
  3747. var blobTextureURL;
  3748. if (blob) {
  3749. var URL = window.URL || window.webkitURL;
  3750. try {
  3751. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3752. }
  3753. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3754. catch (ex) {
  3755. blobTextureURL = URL.createObjectURL(blob);
  3756. }
  3757. }
  3758. image.src = blobTextureURL;
  3759. };
  3760. if (Database.IsUASupportingBlobStorage) {
  3761. var xhr = new XMLHttpRequest(), blob;
  3762. xhr.open("GET", url, true);
  3763. xhr.responseType = "blob";
  3764. xhr.addEventListener("load", function () {
  3765. if (xhr.status === 200) {
  3766. // Blob as response (XHR2)
  3767. blob = xhr.response;
  3768. var transaction = _this.db.transaction(["textures"], "readwrite");
  3769. // the transaction could abort because of a QuotaExceededError error
  3770. transaction.onabort = function (event) {
  3771. try {
  3772. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3773. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3774. this.hasReachedQuota = true;
  3775. }
  3776. }
  3777. catch (ex) { }
  3778. generateBlobUrl();
  3779. };
  3780. transaction.oncomplete = function (event) {
  3781. generateBlobUrl();
  3782. };
  3783. var newTexture = { textureUrl: url, data: blob };
  3784. try {
  3785. // Put the blob into the dabase
  3786. var addRequest = transaction.objectStore("textures").put(newTexture);
  3787. addRequest.onsuccess = function (event) {
  3788. };
  3789. addRequest.onerror = function (event) {
  3790. generateBlobUrl();
  3791. };
  3792. }
  3793. catch (ex) {
  3794. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3795. if (ex.code === 25) {
  3796. Database.IsUASupportingBlobStorage = false;
  3797. }
  3798. image.src = url;
  3799. }
  3800. }
  3801. else {
  3802. image.src = url;
  3803. }
  3804. }, false);
  3805. xhr.addEventListener("error", function (event) {
  3806. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3807. image.src = url;
  3808. }, false);
  3809. xhr.send();
  3810. }
  3811. else {
  3812. image.src = url;
  3813. }
  3814. }
  3815. else {
  3816. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3817. image.src = url;
  3818. }
  3819. };
  3820. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3821. var _this = this;
  3822. var updateVersion = function (event) {
  3823. // the version is not yet in the DB or we need to update it
  3824. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3825. };
  3826. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3827. };
  3828. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3829. var _this = this;
  3830. if (this.isSupported) {
  3831. var version;
  3832. try {
  3833. var transaction = this.db.transaction(["versions"]);
  3834. transaction.oncomplete = function (event) {
  3835. if (version) {
  3836. // If the version in the JSON file is > than the version in DB
  3837. if (_this.manifestVersionFound > version.data) {
  3838. _this.mustUpdateRessources = true;
  3839. updateInDBCallback();
  3840. }
  3841. else {
  3842. callback(version.data);
  3843. }
  3844. }
  3845. else {
  3846. _this.mustUpdateRessources = true;
  3847. updateInDBCallback();
  3848. }
  3849. };
  3850. transaction.onabort = function (event) {
  3851. callback(-1);
  3852. };
  3853. var getRequest = transaction.objectStore("versions").get(url);
  3854. getRequest.onsuccess = function (event) {
  3855. version = (event.target).result;
  3856. };
  3857. getRequest.onerror = function (event) {
  3858. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3859. callback(-1);
  3860. };
  3861. }
  3862. catch (ex) {
  3863. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3864. callback(-1);
  3865. }
  3866. }
  3867. else {
  3868. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3869. callback(-1);
  3870. }
  3871. };
  3872. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3873. var _this = this;
  3874. if (this.isSupported && !this.hasReachedQuota) {
  3875. try {
  3876. // Open a transaction to the database
  3877. var transaction = this.db.transaction(["versions"], "readwrite");
  3878. // the transaction could abort because of a QuotaExceededError error
  3879. transaction.onabort = function (event) {
  3880. try {
  3881. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3882. _this.hasReachedQuota = true;
  3883. }
  3884. }
  3885. catch (ex) { }
  3886. callback(-1);
  3887. };
  3888. transaction.oncomplete = function (event) {
  3889. callback(_this.manifestVersionFound);
  3890. };
  3891. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3892. // Put the scene into the database
  3893. var addRequest = transaction.objectStore("versions").put(newVersion);
  3894. addRequest.onsuccess = function (event) {
  3895. };
  3896. addRequest.onerror = function (event) {
  3897. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3898. };
  3899. }
  3900. catch (ex) {
  3901. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3902. callback(-1);
  3903. }
  3904. }
  3905. else {
  3906. callback(-1);
  3907. }
  3908. };
  3909. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3910. var _this = this;
  3911. var completeUrl = Database.ReturnFullUrlLocation(url);
  3912. var saveAndLoadFile = function (event) {
  3913. // the scene is not yet in the DB, let's try to save it
  3914. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3915. };
  3916. this._checkVersionFromDB(completeUrl, function (version) {
  3917. if (version !== -1) {
  3918. if (!_this.mustUpdateRessources) {
  3919. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3920. }
  3921. else {
  3922. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3923. }
  3924. }
  3925. else {
  3926. errorCallback();
  3927. }
  3928. });
  3929. };
  3930. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3931. if (this.isSupported) {
  3932. var targetStore;
  3933. if (url.indexOf(".babylon") !== -1) {
  3934. targetStore = "scenes";
  3935. }
  3936. else {
  3937. targetStore = "textures";
  3938. }
  3939. var file;
  3940. var transaction = this.db.transaction([targetStore]);
  3941. transaction.oncomplete = function (event) {
  3942. if (file) {
  3943. callback(file.data);
  3944. }
  3945. else {
  3946. notInDBCallback();
  3947. }
  3948. };
  3949. transaction.onabort = function (event) {
  3950. notInDBCallback();
  3951. };
  3952. var getRequest = transaction.objectStore(targetStore).get(url);
  3953. getRequest.onsuccess = function (event) {
  3954. file = (event.target).result;
  3955. };
  3956. getRequest.onerror = function (event) {
  3957. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3958. notInDBCallback();
  3959. };
  3960. }
  3961. else {
  3962. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3963. callback();
  3964. }
  3965. };
  3966. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3967. var _this = this;
  3968. if (this.isSupported) {
  3969. var targetStore;
  3970. if (url.indexOf(".babylon") !== -1) {
  3971. targetStore = "scenes";
  3972. }
  3973. else {
  3974. targetStore = "textures";
  3975. }
  3976. // Create XHR
  3977. var xhr = new XMLHttpRequest(), fileData;
  3978. xhr.open("GET", url, true);
  3979. if (useArrayBuffer) {
  3980. xhr.responseType = "arraybuffer";
  3981. }
  3982. xhr.onprogress = progressCallback;
  3983. xhr.addEventListener("load", function () {
  3984. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3985. // Blob as response (XHR2)
  3986. //fileData = xhr.responseText;
  3987. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3988. if (!_this.hasReachedQuota) {
  3989. // Open a transaction to the database
  3990. var transaction = _this.db.transaction([targetStore], "readwrite");
  3991. // the transaction could abort because of a QuotaExceededError error
  3992. transaction.onabort = function (event) {
  3993. try {
  3994. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3995. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3996. this.hasReachedQuota = true;
  3997. }
  3998. }
  3999. catch (ex) { }
  4000. callback(fileData);
  4001. };
  4002. transaction.oncomplete = function (event) {
  4003. callback(fileData);
  4004. };
  4005. var newFile;
  4006. if (targetStore === "scenes") {
  4007. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4008. }
  4009. else {
  4010. newFile = { textureUrl: url, data: fileData };
  4011. }
  4012. try {
  4013. // Put the scene into the database
  4014. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4015. addRequest.onsuccess = function (event) {
  4016. };
  4017. addRequest.onerror = function (event) {
  4018. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4019. };
  4020. }
  4021. catch (ex) {
  4022. callback(fileData);
  4023. }
  4024. }
  4025. else {
  4026. callback(fileData);
  4027. }
  4028. }
  4029. else {
  4030. callback();
  4031. }
  4032. }, false);
  4033. xhr.addEventListener("error", function (event) {
  4034. BABYLON.Tools.Error("error on XHR request.");
  4035. callback();
  4036. }, false);
  4037. xhr.send();
  4038. }
  4039. else {
  4040. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4041. callback();
  4042. }
  4043. };
  4044. Database.IsUASupportingBlobStorage = true;
  4045. Database.IDBStorageEnabled = true;
  4046. Database.parseURL = function (url) {
  4047. var a = document.createElement('a');
  4048. a.href = url;
  4049. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4050. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4051. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4052. return absLocation;
  4053. };
  4054. Database.ReturnFullUrlLocation = function (url) {
  4055. if (url.indexOf("http:/") === -1) {
  4056. return (Database.parseURL(window.location.href) + url);
  4057. }
  4058. else {
  4059. return url;
  4060. }
  4061. };
  4062. return Database;
  4063. })();
  4064. BABYLON.Database = Database;
  4065. })(BABYLON || (BABYLON = {}));
  4066. var BABYLON;
  4067. (function (BABYLON) {
  4068. var Internals;
  4069. (function (Internals) {
  4070. /*
  4071. * Based on jsTGALoader - Javascript loader for TGA file
  4072. * By Vincent Thibault
  4073. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4074. */
  4075. var TGATools = (function () {
  4076. function TGATools() {
  4077. }
  4078. TGATools.GetTGAHeader = function (data) {
  4079. var offset = 0;
  4080. var header = {
  4081. id_length: data[offset++],
  4082. colormap_type: data[offset++],
  4083. image_type: data[offset++],
  4084. colormap_index: data[offset++] | data[offset++] << 8,
  4085. colormap_length: data[offset++] | data[offset++] << 8,
  4086. colormap_size: data[offset++],
  4087. origin: [
  4088. data[offset++] | data[offset++] << 8,
  4089. data[offset++] | data[offset++] << 8
  4090. ],
  4091. width: data[offset++] | data[offset++] << 8,
  4092. height: data[offset++] | data[offset++] << 8,
  4093. pixel_size: data[offset++],
  4094. flags: data[offset++]
  4095. };
  4096. return header;
  4097. };
  4098. TGATools.UploadContent = function (gl, data) {
  4099. // Not enough data to contain header ?
  4100. if (data.length < 19) {
  4101. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4102. return;
  4103. }
  4104. // Read Header
  4105. var offset = 18;
  4106. var header = TGATools.GetTGAHeader(data);
  4107. // Assume it's a valid Targa file.
  4108. if (header.id_length + offset > data.length) {
  4109. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4110. return;
  4111. }
  4112. // Skip not needed data
  4113. offset += header.id_length;
  4114. var use_rle = false;
  4115. var use_pal = false;
  4116. var use_rgb = false;
  4117. var use_grey = false;
  4118. // Get some informations.
  4119. switch (header.image_type) {
  4120. case TGATools._TYPE_RLE_INDEXED:
  4121. use_rle = true;
  4122. case TGATools._TYPE_INDEXED:
  4123. use_pal = true;
  4124. break;
  4125. case TGATools._TYPE_RLE_RGB:
  4126. use_rle = true;
  4127. case TGATools._TYPE_RGB:
  4128. use_rgb = true;
  4129. break;
  4130. case TGATools._TYPE_RLE_GREY:
  4131. use_rle = true;
  4132. case TGATools._TYPE_GREY:
  4133. use_grey = true;
  4134. break;
  4135. }
  4136. var pixel_data;
  4137. var numAlphaBits = header.flags & 0xf;
  4138. var pixel_size = header.pixel_size >> 3;
  4139. var pixel_total = header.width * header.height * pixel_size;
  4140. // Read palettes
  4141. var palettes;
  4142. if (use_pal) {
  4143. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4144. }
  4145. // Read LRE
  4146. if (use_rle) {
  4147. pixel_data = new Uint8Array(pixel_total);
  4148. var c, count, i;
  4149. var localOffset = 0;
  4150. var pixels = new Uint8Array(pixel_size);
  4151. while (offset < pixel_total && localOffset < pixel_total) {
  4152. c = data[offset++];
  4153. count = (c & 0x7f) + 1;
  4154. // RLE pixels
  4155. if (c & 0x80) {
  4156. // Bind pixel tmp array
  4157. for (i = 0; i < pixel_size; ++i) {
  4158. pixels[i] = data[offset++];
  4159. }
  4160. // Copy pixel array
  4161. for (i = 0; i < count; ++i) {
  4162. pixel_data.set(pixels, localOffset + i * pixel_size);
  4163. }
  4164. localOffset += pixel_size * count;
  4165. }
  4166. else {
  4167. count *= pixel_size;
  4168. for (i = 0; i < count; ++i) {
  4169. pixel_data[localOffset + i] = data[offset++];
  4170. }
  4171. localOffset += count;
  4172. }
  4173. }
  4174. }
  4175. else {
  4176. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4177. }
  4178. // Load to texture
  4179. var x_start, y_start, x_step, y_step, y_end, x_end;
  4180. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4181. default:
  4182. case TGATools._ORIGIN_UL:
  4183. x_start = 0;
  4184. x_step = 1;
  4185. x_end = header.width;
  4186. y_start = 0;
  4187. y_step = 1;
  4188. y_end = header.height;
  4189. break;
  4190. case TGATools._ORIGIN_BL:
  4191. x_start = 0;
  4192. x_step = 1;
  4193. x_end = header.width;
  4194. y_start = header.height - 1;
  4195. y_step = -1;
  4196. y_end = -1;
  4197. break;
  4198. case TGATools._ORIGIN_UR:
  4199. x_start = header.width - 1;
  4200. x_step = -1;
  4201. x_end = -1;
  4202. y_start = 0;
  4203. y_step = 1;
  4204. y_end = header.height;
  4205. break;
  4206. case TGATools._ORIGIN_BR:
  4207. x_start = header.width - 1;
  4208. x_step = -1;
  4209. x_end = -1;
  4210. y_start = header.height - 1;
  4211. y_step = -1;
  4212. y_end = -1;
  4213. break;
  4214. }
  4215. // Load the specify method
  4216. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4217. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4218. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4219. };
  4220. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4221. var image = pixel_data, colormap = palettes;
  4222. var width = header.width, height = header.height;
  4223. var color, i = 0, x, y;
  4224. var imageData = new Uint8Array(width * height * 4);
  4225. for (y = y_start; y !== y_end; y += y_step) {
  4226. for (x = x_start; x !== x_end; x += x_step, i++) {
  4227. color = image[i];
  4228. imageData[(x + width * y) * 4 + 3] = 255;
  4229. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4230. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4231. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4232. }
  4233. }
  4234. return imageData;
  4235. };
  4236. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4237. var image = pixel_data;
  4238. var width = header.width, height = header.height;
  4239. var color, i = 0, x, y;
  4240. var imageData = new Uint8Array(width * height * 4);
  4241. for (y = y_start; y !== y_end; y += y_step) {
  4242. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4243. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4244. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4245. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4246. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4247. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4248. }
  4249. }
  4250. return imageData;
  4251. };
  4252. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4253. var image = pixel_data;
  4254. var width = header.width, height = header.height;
  4255. var i = 0, x, y;
  4256. var imageData = new Uint8Array(width * height * 4);
  4257. for (y = y_start; y !== y_end; y += y_step) {
  4258. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4259. imageData[(x + width * y) * 4 + 3] = 255;
  4260. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4261. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4262. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4263. }
  4264. }
  4265. return imageData;
  4266. };
  4267. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4268. var image = pixel_data;
  4269. var width = header.width, height = header.height;
  4270. var i = 0, x, y;
  4271. var imageData = new Uint8Array(width * height * 4);
  4272. for (y = y_start; y !== y_end; y += y_step) {
  4273. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4274. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4275. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4276. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4277. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4278. }
  4279. }
  4280. return imageData;
  4281. };
  4282. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4283. var image = pixel_data;
  4284. var width = header.width, height = header.height;
  4285. var color, i = 0, x, y;
  4286. var imageData = new Uint8Array(width * height * 4);
  4287. for (y = y_start; y !== y_end; y += y_step) {
  4288. for (x = x_start; x !== x_end; x += x_step, i++) {
  4289. color = image[i];
  4290. imageData[(x + width * y) * 4 + 0] = color;
  4291. imageData[(x + width * y) * 4 + 1] = color;
  4292. imageData[(x + width * y) * 4 + 2] = color;
  4293. imageData[(x + width * y) * 4 + 3] = 255;
  4294. }
  4295. }
  4296. return imageData;
  4297. };
  4298. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4299. var image = pixel_data;
  4300. var width = header.width, height = header.height;
  4301. var i = 0, x, y;
  4302. var imageData = new Uint8Array(width * height * 4);
  4303. for (y = y_start; y !== y_end; y += y_step) {
  4304. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4305. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4306. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4307. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4308. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4309. }
  4310. }
  4311. return imageData;
  4312. };
  4313. TGATools._TYPE_NO_DATA = 0;
  4314. TGATools._TYPE_INDEXED = 1;
  4315. TGATools._TYPE_RGB = 2;
  4316. TGATools._TYPE_GREY = 3;
  4317. TGATools._TYPE_RLE_INDEXED = 9;
  4318. TGATools._TYPE_RLE_RGB = 10;
  4319. TGATools._TYPE_RLE_GREY = 11;
  4320. TGATools._ORIGIN_MASK = 0x30;
  4321. TGATools._ORIGIN_SHIFT = 0x04;
  4322. TGATools._ORIGIN_BL = 0x00;
  4323. TGATools._ORIGIN_BR = 0x01;
  4324. TGATools._ORIGIN_UL = 0x02;
  4325. TGATools._ORIGIN_UR = 0x03;
  4326. return TGATools;
  4327. })();
  4328. Internals.TGATools = TGATools;
  4329. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4330. })(BABYLON || (BABYLON = {}));
  4331. var BABYLON;
  4332. (function (BABYLON) {
  4333. var SmartArray = (function () {
  4334. function SmartArray(capacity) {
  4335. this.length = 0;
  4336. this._duplicateId = 0;
  4337. this.data = new Array(capacity);
  4338. this._id = SmartArray._GlobalId++;
  4339. }
  4340. SmartArray.prototype.push = function (value) {
  4341. this.data[this.length++] = value;
  4342. if (this.length > this.data.length) {
  4343. this.data.length *= 2;
  4344. }
  4345. if (!value.__smartArrayFlags) {
  4346. value.__smartArrayFlags = {};
  4347. }
  4348. value.__smartArrayFlags[this._id] = this._duplicateId;
  4349. };
  4350. SmartArray.prototype.pushNoDuplicate = function (value) {
  4351. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4352. return false;
  4353. }
  4354. this.push(value);
  4355. return true;
  4356. };
  4357. SmartArray.prototype.sort = function (compareFn) {
  4358. this.data.sort(compareFn);
  4359. };
  4360. SmartArray.prototype.reset = function () {
  4361. this.length = 0;
  4362. this._duplicateId++;
  4363. };
  4364. SmartArray.prototype.concat = function (array) {
  4365. if (array.length === 0) {
  4366. return;
  4367. }
  4368. if (this.length + array.length > this.data.length) {
  4369. this.data.length = (this.length + array.length) * 2;
  4370. }
  4371. for (var index = 0; index < array.length; index++) {
  4372. this.data[this.length++] = (array.data || array)[index];
  4373. }
  4374. };
  4375. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4376. if (array.length === 0) {
  4377. return;
  4378. }
  4379. if (this.length + array.length > this.data.length) {
  4380. this.data.length = (this.length + array.length) * 2;
  4381. }
  4382. for (var index = 0; index < array.length; index++) {
  4383. var item = (array.data || array)[index];
  4384. this.pushNoDuplicate(item);
  4385. }
  4386. };
  4387. SmartArray.prototype.indexOf = function (value) {
  4388. var position = this.data.indexOf(value);
  4389. if (position >= this.length) {
  4390. return -1;
  4391. }
  4392. return position;
  4393. };
  4394. // Statics
  4395. SmartArray._GlobalId = 0;
  4396. return SmartArray;
  4397. })();
  4398. BABYLON.SmartArray = SmartArray;
  4399. })(BABYLON || (BABYLON = {}));
  4400. var BABYLON;
  4401. (function (BABYLON) {
  4402. /**
  4403. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4404. * The underlying implementation relies on an associative array to ensure the best performances.
  4405. * The value can be anything including 'null' but except 'undefined'
  4406. */
  4407. var StringDictionary = (function () {
  4408. function StringDictionary() {
  4409. this._count = 0;
  4410. this._data = {};
  4411. }
  4412. /**
  4413. * Get a value based from its key
  4414. * @param key the given key to get the matching value from
  4415. * @return the value if found, otherwise undefined is returned
  4416. */
  4417. StringDictionary.prototype.get = function (key) {
  4418. var val = this._data[key];
  4419. if (val !== undefined) {
  4420. return val;
  4421. }
  4422. return undefined;
  4423. };
  4424. /**
  4425. * Get a value from its key or add it if it doesn't exist.
  4426. * This method will ensure you that a given key/data will be present in the dictionary.
  4427. * @param key the given key to get the matching value from
  4428. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4429. * The factory will only be invoked if there's no data for the given key.
  4430. * @return the value corresponding to the key.
  4431. */
  4432. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4433. var val = this.get(key);
  4434. if (val !== undefined) {
  4435. return val;
  4436. }
  4437. val = factory(key);
  4438. if (val) {
  4439. this.add(key, val);
  4440. }
  4441. return val;
  4442. };
  4443. /**
  4444. * Get a value from its key if present in the dictionary otherwise add it
  4445. * @param key the key to get the value from
  4446. * @param val if there's no such key/value pair in the dictionary add it with this value
  4447. * @return the value corresponding to the key
  4448. */
  4449. StringDictionary.prototype.getOrAdd = function (key, val) {
  4450. var curVal = this.get(key);
  4451. if (curVal !== undefined) {
  4452. return curVal;
  4453. }
  4454. this.add(key, val);
  4455. return val;
  4456. };
  4457. /**
  4458. * Check if there's a given key in the dictionary
  4459. * @param key the key to check for
  4460. * @return true if the key is present, false otherwise
  4461. */
  4462. StringDictionary.prototype.contains = function (key) {
  4463. return this._data[key] !== undefined;
  4464. };
  4465. /**
  4466. * Add a new key and its corresponding value
  4467. * @param key the key to add
  4468. * @param value the value corresponding to the key
  4469. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  4470. */
  4471. StringDictionary.prototype.add = function (key, value) {
  4472. if (this._data[key] !== undefined) {
  4473. return false;
  4474. }
  4475. this._data[key] = value;
  4476. ++this._count;
  4477. return true;
  4478. };
  4479. StringDictionary.prototype.set = function (key, value) {
  4480. if (this._data[key] === undefined) {
  4481. return false;
  4482. }
  4483. this._data[key] = value;
  4484. return true;
  4485. };
  4486. /**
  4487. * Remove a key/value from the dictionary.
  4488. * @param key the key to remove
  4489. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4490. */
  4491. StringDictionary.prototype.remove = function (key) {
  4492. if (this.contains(key)) {
  4493. delete this._data[key];
  4494. --this._count;
  4495. return true;
  4496. }
  4497. return false;
  4498. };
  4499. /**
  4500. * Clear the whole content of the dictionary
  4501. */
  4502. StringDictionary.prototype.clear = function () {
  4503. this._data = {};
  4504. this._count = 0;
  4505. };
  4506. Object.defineProperty(StringDictionary.prototype, "count", {
  4507. get: function () {
  4508. return this._count;
  4509. },
  4510. enumerable: true,
  4511. configurable: true
  4512. });
  4513. /**
  4514. * Execute a callback on each key/val of the dictionary.
  4515. * Note that you can remove any element in this dictionary in the callback implementation
  4516. * @param callback the callback to execute on a given key/value pair
  4517. */
  4518. StringDictionary.prototype.forEach = function (callback) {
  4519. for (var cur in this._data) {
  4520. var val = this._data[cur];
  4521. callback(cur, val);
  4522. }
  4523. };
  4524. /**
  4525. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4526. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4527. * Note that you can remove any element in this dictionary in the callback implementation
  4528. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4529. */
  4530. StringDictionary.prototype.first = function (callback) {
  4531. for (var cur in this._data) {
  4532. var val = this._data[cur];
  4533. var res = callback(cur, val);
  4534. if (res) {
  4535. return res;
  4536. }
  4537. }
  4538. return null;
  4539. };
  4540. return StringDictionary;
  4541. })();
  4542. BABYLON.StringDictionary = StringDictionary;
  4543. })(BABYLON || (BABYLON = {}));
  4544. var BABYLON;
  4545. (function (BABYLON) {
  4546. // Screenshots
  4547. var screenshotCanvas;
  4548. var cloneValue = function (source, destinationObject) {
  4549. if (!source)
  4550. return null;
  4551. if (source instanceof BABYLON.Mesh) {
  4552. return null;
  4553. }
  4554. if (source instanceof BABYLON.SubMesh) {
  4555. return source.clone(destinationObject);
  4556. }
  4557. else if (source.clone) {
  4558. return source.clone();
  4559. }
  4560. return null;
  4561. };
  4562. var Tools = (function () {
  4563. function Tools() {
  4564. }
  4565. Tools.Instantiate = function (className) {
  4566. var arr = className.split(".");
  4567. var fn = (window || this);
  4568. for (var i = 0, len = arr.length; i < len; i++) {
  4569. fn = fn[arr[i]];
  4570. }
  4571. if (typeof fn !== "function") {
  4572. return null;
  4573. }
  4574. return fn;
  4575. };
  4576. Tools.SetImmediate = function (action) {
  4577. if (window.setImmediate) {
  4578. window.setImmediate(action);
  4579. }
  4580. else {
  4581. setTimeout(action, 1);
  4582. }
  4583. };
  4584. Tools.IsExponentOfTwo = function (value) {
  4585. var count = 1;
  4586. do {
  4587. count *= 2;
  4588. } while (count < value);
  4589. return count === value;
  4590. };
  4591. Tools.GetExponentOfTwo = function (value, max) {
  4592. var count = 1;
  4593. do {
  4594. count *= 2;
  4595. } while (count < value);
  4596. if (count > max)
  4597. count = max;
  4598. return count;
  4599. };
  4600. Tools.GetFilename = function (path) {
  4601. var index = path.lastIndexOf("/");
  4602. if (index < 0)
  4603. return path;
  4604. return path.substring(index + 1);
  4605. };
  4606. Tools.GetDOMTextContent = function (element) {
  4607. var result = "";
  4608. var child = element.firstChild;
  4609. while (child) {
  4610. if (child.nodeType === 3) {
  4611. result += child.textContent;
  4612. }
  4613. child = child.nextSibling;
  4614. }
  4615. return result;
  4616. };
  4617. Tools.ToDegrees = function (angle) {
  4618. return angle * 180 / Math.PI;
  4619. };
  4620. Tools.ToRadians = function (angle) {
  4621. return angle * Math.PI / 180;
  4622. };
  4623. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4624. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4625. var output = "";
  4626. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4627. var i = 0;
  4628. var bytes = new Uint8Array(buffer);
  4629. while (i < bytes.length) {
  4630. chr1 = bytes[i++];
  4631. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4632. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4633. enc1 = chr1 >> 2;
  4634. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4635. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4636. enc4 = chr3 & 63;
  4637. if (isNaN(chr2)) {
  4638. enc3 = enc4 = 64;
  4639. }
  4640. else if (isNaN(chr3)) {
  4641. enc4 = 64;
  4642. }
  4643. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4644. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4645. }
  4646. return "data:image/png;base64," + output;
  4647. };
  4648. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4649. if (bias === void 0) { bias = null; }
  4650. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4651. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4652. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4653. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4654. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4655. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4656. }
  4657. if (bias) {
  4658. minimum.x -= minimum.x * bias.x + bias.y;
  4659. minimum.y -= minimum.y * bias.x + bias.y;
  4660. minimum.z -= minimum.z * bias.x + bias.y;
  4661. maximum.x += maximum.x * bias.x + bias.y;
  4662. maximum.y += maximum.y * bias.x + bias.y;
  4663. maximum.z += maximum.z * bias.x + bias.y;
  4664. }
  4665. return {
  4666. minimum: minimum,
  4667. maximum: maximum
  4668. };
  4669. };
  4670. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4671. if (bias === void 0) { bias = null; }
  4672. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4673. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4674. if (!stride) {
  4675. stride = 3;
  4676. }
  4677. for (var index = start; index < start + count; index++) {
  4678. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4679. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4680. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4681. }
  4682. if (bias) {
  4683. minimum.x -= minimum.x * bias.x + bias.y;
  4684. minimum.y -= minimum.y * bias.x + bias.y;
  4685. minimum.z -= minimum.z * bias.x + bias.y;
  4686. maximum.x += maximum.x * bias.x + bias.y;
  4687. maximum.y += maximum.y * bias.x + bias.y;
  4688. maximum.z += maximum.z * bias.x + bias.y;
  4689. }
  4690. return {
  4691. minimum: minimum,
  4692. maximum: maximum
  4693. };
  4694. };
  4695. Tools.Vector2ArrayFeeder = function (array) {
  4696. return function (index) {
  4697. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4698. var length = isFloatArray ? array.length / 2 : array.length;
  4699. if (index >= length) {
  4700. return null;
  4701. }
  4702. if (isFloatArray) {
  4703. var fa = array;
  4704. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4705. }
  4706. var a = array;
  4707. return a[index];
  4708. };
  4709. };
  4710. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4711. if (bias === void 0) { bias = null; }
  4712. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4713. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4714. var i = 0;
  4715. var cur = feeder(i++);
  4716. while (cur) {
  4717. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4718. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4719. cur = feeder(i++);
  4720. }
  4721. if (bias) {
  4722. minimum.x -= minimum.x * bias.x + bias.y;
  4723. minimum.y -= minimum.y * bias.x + bias.y;
  4724. maximum.x += maximum.x * bias.x + bias.y;
  4725. maximum.y += maximum.y * bias.x + bias.y;
  4726. }
  4727. return {
  4728. minimum: minimum,
  4729. maximum: maximum
  4730. };
  4731. };
  4732. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4733. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4734. return undefined;
  4735. return Array.isArray(obj) ? obj : [obj];
  4736. };
  4737. // Misc.
  4738. Tools.GetPointerPrefix = function () {
  4739. var eventPrefix = "pointer";
  4740. // Check if pointer events are supported
  4741. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4742. eventPrefix = "mouse";
  4743. }
  4744. return eventPrefix;
  4745. };
  4746. /**
  4747. * @param func - the function to be called
  4748. * @param requester - the object that will request the next frame. Falls back to window.
  4749. */
  4750. Tools.QueueNewFrame = function (func, requester) {
  4751. if (requester === void 0) { requester = window; }
  4752. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4753. /*if(requester.isPresenting) {
  4754. return;
  4755. } else*/ if (requester.requestAnimationFrame)
  4756. requester.requestAnimationFrame(func);
  4757. else if (requester.msRequestAnimationFrame)
  4758. requester.msRequestAnimationFrame(func);
  4759. else if (requester.webkitRequestAnimationFrame)
  4760. requester.webkitRequestAnimationFrame(func);
  4761. else if (requester.mozRequestAnimationFrame)
  4762. requester.mozRequestAnimationFrame(func);
  4763. else if (requester.oRequestAnimationFrame)
  4764. requester.oRequestAnimationFrame(func);
  4765. else {
  4766. window.setTimeout(func, 16);
  4767. }
  4768. };
  4769. Tools.RequestFullscreen = function (element) {
  4770. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4771. if (!requestFunction)
  4772. return;
  4773. requestFunction.call(element);
  4774. };
  4775. Tools.ExitFullscreen = function () {
  4776. if (document.exitFullscreen) {
  4777. document.exitFullscreen();
  4778. }
  4779. else if (document.mozCancelFullScreen) {
  4780. document.mozCancelFullScreen();
  4781. }
  4782. else if (document.webkitCancelFullScreen) {
  4783. document.webkitCancelFullScreen();
  4784. }
  4785. else if (document.msCancelFullScreen) {
  4786. document.msCancelFullScreen();
  4787. }
  4788. };
  4789. Tools.SetCorsBehavior = function (url, img) {
  4790. if (Tools.CorsBehavior) {
  4791. switch (typeof (Tools.CorsBehavior)) {
  4792. case "function":
  4793. var result = Tools.CorsBehavior(url);
  4794. if (result) {
  4795. return result;
  4796. }
  4797. break;
  4798. case "string":
  4799. default:
  4800. img.crossOrigin = Tools.CorsBehavior;
  4801. break;
  4802. }
  4803. }
  4804. };
  4805. // External files
  4806. Tools.CleanUrl = function (url) {
  4807. url = url.replace(/#/mg, "%23");
  4808. return url;
  4809. };
  4810. Tools.LoadImage = function (url, onload, onerror, database) {
  4811. if (url instanceof ArrayBuffer) {
  4812. url = Tools.EncodeArrayBufferTobase64(url);
  4813. }
  4814. url = Tools.CleanUrl(url);
  4815. var img = new Image();
  4816. if (url.substr(0, 5) !== "data:") {
  4817. Tools.SetCorsBehavior(url, img);
  4818. }
  4819. img.onload = function () {
  4820. onload(img);
  4821. };
  4822. img.onerror = function (err) {
  4823. Tools.Error("Error while trying to load texture: " + url);
  4824. if (Tools.UseFallbackTexture) {
  4825. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4826. onload(img);
  4827. }
  4828. else {
  4829. onerror();
  4830. }
  4831. };
  4832. var noIndexedDB = function () {
  4833. img.src = url;
  4834. };
  4835. var loadFromIndexedDB = function () {
  4836. database.loadImageFromDB(url, img);
  4837. };
  4838. //ANY database to do!
  4839. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4840. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4841. }
  4842. else {
  4843. if (url.indexOf("file:") === -1) {
  4844. noIndexedDB();
  4845. }
  4846. else {
  4847. try {
  4848. var textureName = url.substring(5).toLowerCase();
  4849. var blobURL;
  4850. try {
  4851. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4852. }
  4853. catch (ex) {
  4854. // Chrome doesn't support oneTimeOnly parameter
  4855. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4856. }
  4857. img.src = blobURL;
  4858. }
  4859. catch (e) {
  4860. img.src = null;
  4861. }
  4862. }
  4863. }
  4864. return img;
  4865. };
  4866. //ANY
  4867. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4868. url = Tools.CleanUrl(url);
  4869. var noIndexedDB = function () {
  4870. var request = new XMLHttpRequest();
  4871. var loadUrl = Tools.BaseUrl + url;
  4872. request.open('GET', loadUrl, true);
  4873. if (useArrayBuffer) {
  4874. request.responseType = "arraybuffer";
  4875. }
  4876. request.onprogress = progressCallBack;
  4877. request.onreadystatechange = function () {
  4878. if (request.readyState === 4) {
  4879. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4880. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4881. callback(!useArrayBuffer ? request.responseText : request.response);
  4882. }
  4883. else {
  4884. if (onError) {
  4885. onError();
  4886. }
  4887. else {
  4888. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4889. }
  4890. }
  4891. }
  4892. };
  4893. request.send(null);
  4894. };
  4895. var loadFromIndexedDB = function () {
  4896. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4897. };
  4898. if (url.indexOf("file:") !== -1) {
  4899. var fileName = url.substring(5).toLowerCase();
  4900. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4901. }
  4902. else {
  4903. // Caching all files
  4904. if (database && database.enableSceneOffline) {
  4905. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4906. }
  4907. else {
  4908. noIndexedDB();
  4909. }
  4910. }
  4911. };
  4912. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4913. var reader = new FileReader();
  4914. reader.onload = function (e) {
  4915. //target doesn't have result from ts 1.3
  4916. callback(e.target['result']);
  4917. };
  4918. reader.onprogress = progressCallback;
  4919. reader.readAsDataURL(fileToLoad);
  4920. };
  4921. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4922. var reader = new FileReader();
  4923. reader.onerror = function (e) {
  4924. Tools.Log("Error while reading file: " + fileToLoad.name);
  4925. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4926. };
  4927. reader.onload = function (e) {
  4928. //target doesn't have result from ts 1.3
  4929. callback(e.target['result']);
  4930. };
  4931. reader.onprogress = progressCallBack;
  4932. if (!useArrayBuffer) {
  4933. // Asynchronous read
  4934. reader.readAsText(fileToLoad);
  4935. }
  4936. else {
  4937. reader.readAsArrayBuffer(fileToLoad);
  4938. }
  4939. };
  4940. //returns a downloadable url to a file content.
  4941. Tools.FileAsURL = function (content) {
  4942. var fileBlob = new Blob([content]);
  4943. var url = window.URL || window.webkitURL;
  4944. var link = url.createObjectURL(fileBlob);
  4945. return link;
  4946. };
  4947. // Misc.
  4948. Tools.Format = function (value, decimals) {
  4949. if (decimals === void 0) { decimals = 2; }
  4950. return value.toFixed(decimals);
  4951. };
  4952. Tools.CheckExtends = function (v, min, max) {
  4953. if (v.x < min.x)
  4954. min.x = v.x;
  4955. if (v.y < min.y)
  4956. min.y = v.y;
  4957. if (v.z < min.z)
  4958. min.z = v.z;
  4959. if (v.x > max.x)
  4960. max.x = v.x;
  4961. if (v.y > max.y)
  4962. max.y = v.y;
  4963. if (v.z > max.z)
  4964. max.z = v.z;
  4965. };
  4966. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4967. for (var prop in source) {
  4968. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4969. continue;
  4970. }
  4971. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4972. continue;
  4973. }
  4974. var sourceValue = source[prop];
  4975. var typeOfSourceValue = typeof sourceValue;
  4976. if (typeOfSourceValue === "function") {
  4977. continue;
  4978. }
  4979. if (typeOfSourceValue === "object") {
  4980. if (sourceValue instanceof Array) {
  4981. destination[prop] = [];
  4982. if (sourceValue.length > 0) {
  4983. if (typeof sourceValue[0] == "object") {
  4984. for (var index = 0; index < sourceValue.length; index++) {
  4985. var clonedValue = cloneValue(sourceValue[index], destination);
  4986. if (destination[prop].indexOf(clonedValue) === -1) {
  4987. destination[prop].push(clonedValue);
  4988. }
  4989. }
  4990. }
  4991. else {
  4992. destination[prop] = sourceValue.slice(0);
  4993. }
  4994. }
  4995. }
  4996. else {
  4997. destination[prop] = cloneValue(sourceValue, destination);
  4998. }
  4999. }
  5000. else {
  5001. destination[prop] = sourceValue;
  5002. }
  5003. }
  5004. };
  5005. Tools.IsEmpty = function (obj) {
  5006. for (var i in obj) {
  5007. return false;
  5008. }
  5009. return true;
  5010. };
  5011. Tools.RegisterTopRootEvents = function (events) {
  5012. for (var index = 0; index < events.length; index++) {
  5013. var event = events[index];
  5014. window.addEventListener(event.name, event.handler, false);
  5015. try {
  5016. if (window.parent) {
  5017. window.parent.addEventListener(event.name, event.handler, false);
  5018. }
  5019. }
  5020. catch (e) {
  5021. }
  5022. }
  5023. };
  5024. Tools.UnregisterTopRootEvents = function (events) {
  5025. for (var index = 0; index < events.length; index++) {
  5026. var event = events[index];
  5027. window.removeEventListener(event.name, event.handler);
  5028. try {
  5029. if (window.parent) {
  5030. window.parent.removeEventListener(event.name, event.handler);
  5031. }
  5032. }
  5033. catch (e) {
  5034. }
  5035. }
  5036. };
  5037. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5038. if (mimeType === void 0) { mimeType = "image/png"; }
  5039. // Read the contents of the framebuffer
  5040. var numberOfChannelsByLine = width * 4;
  5041. var halfHeight = height / 2;
  5042. //Reading datas from WebGL
  5043. var data = engine.readPixels(0, 0, width, height);
  5044. //To flip image on Y axis.
  5045. for (var i = 0; i < halfHeight; i++) {
  5046. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5047. var currentCell = j + i * numberOfChannelsByLine;
  5048. var targetLine = height - i - 1;
  5049. var targetCell = j + targetLine * numberOfChannelsByLine;
  5050. var temp = data[currentCell];
  5051. data[currentCell] = data[targetCell];
  5052. data[targetCell] = temp;
  5053. }
  5054. }
  5055. // Create a 2D canvas to store the result
  5056. if (!screenshotCanvas) {
  5057. screenshotCanvas = document.createElement('canvas');
  5058. }
  5059. screenshotCanvas.width = width;
  5060. screenshotCanvas.height = height;
  5061. var context = screenshotCanvas.getContext('2d');
  5062. // Copy the pixels to a 2D canvas
  5063. var imageData = context.createImageData(width, height);
  5064. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  5065. var castData = imageData.data;
  5066. castData.set(data);
  5067. context.putImageData(imageData, 0, 0);
  5068. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5069. if (successCallback) {
  5070. successCallback(base64Image);
  5071. }
  5072. else {
  5073. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5074. if (("download" in document.createElement("a"))) {
  5075. var a = window.document.createElement("a");
  5076. a.href = base64Image;
  5077. var date = new Date();
  5078. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5079. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5080. window.document.body.appendChild(a);
  5081. a.addEventListener("click", function () {
  5082. a.parentElement.removeChild(a);
  5083. });
  5084. a.click();
  5085. }
  5086. else {
  5087. var newWindow = window.open("");
  5088. var img = newWindow.document.createElement("img");
  5089. img.src = base64Image;
  5090. newWindow.document.body.appendChild(img);
  5091. }
  5092. }
  5093. };
  5094. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5095. if (mimeType === void 0) { mimeType = "image/png"; }
  5096. var width;
  5097. var height;
  5098. //If a precision value is specified
  5099. if (size.precision) {
  5100. width = Math.round(engine.getRenderWidth() * size.precision);
  5101. height = Math.round(width / engine.getAspectRatio(camera));
  5102. size = { width: width, height: height };
  5103. }
  5104. else if (size.width && size.height) {
  5105. width = size.width;
  5106. height = size.height;
  5107. }
  5108. else if (size.width && !size.height) {
  5109. width = size.width;
  5110. height = Math.round(width / engine.getAspectRatio(camera));
  5111. size = { width: width, height: height };
  5112. }
  5113. else if (size.height && !size.width) {
  5114. height = size.height;
  5115. width = Math.round(height * engine.getAspectRatio(camera));
  5116. size = { width: width, height: height };
  5117. }
  5118. else if (!isNaN(size)) {
  5119. height = size;
  5120. width = size;
  5121. }
  5122. else {
  5123. Tools.Error("Invalid 'size' parameter !");
  5124. return;
  5125. }
  5126. var scene = camera.getScene();
  5127. var previousCamera = null;
  5128. if (scene.activeCamera !== camera) {
  5129. previousCamera = scene.activeCamera;
  5130. scene.activeCamera = camera;
  5131. }
  5132. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5133. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5134. texture.renderList = scene.meshes;
  5135. texture.onAfterRenderObservable.add(function () {
  5136. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5137. });
  5138. scene.incrementRenderId();
  5139. scene.resetCachedMaterial();
  5140. texture.render(true);
  5141. texture.dispose();
  5142. if (previousCamera) {
  5143. scene.activeCamera = previousCamera;
  5144. }
  5145. camera.getProjectionMatrix(true); // Force cache refresh;
  5146. };
  5147. // XHR response validator for local file scenario
  5148. Tools.ValidateXHRData = function (xhr, dataType) {
  5149. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5150. if (dataType === void 0) { dataType = 7; }
  5151. try {
  5152. if (dataType & 1) {
  5153. if (xhr.responseText && xhr.responseText.length > 0) {
  5154. return true;
  5155. }
  5156. else if (dataType === 1) {
  5157. return false;
  5158. }
  5159. }
  5160. if (dataType & 2) {
  5161. // Check header width and height since there is no "TGA" magic number
  5162. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5163. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5164. return true;
  5165. }
  5166. else if (dataType === 2) {
  5167. return false;
  5168. }
  5169. }
  5170. if (dataType & 4) {
  5171. // Check for the "DDS" magic number
  5172. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5173. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5174. return true;
  5175. }
  5176. else {
  5177. return false;
  5178. }
  5179. }
  5180. }
  5181. catch (e) {
  5182. }
  5183. return false;
  5184. };
  5185. /**
  5186. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5187. * Be aware Math.random() could cause collisions, but:
  5188. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  5189. */
  5190. Tools.RandomId = function () {
  5191. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5192. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5193. return v.toString(16);
  5194. });
  5195. };
  5196. Object.defineProperty(Tools, "NoneLogLevel", {
  5197. get: function () {
  5198. return Tools._NoneLogLevel;
  5199. },
  5200. enumerable: true,
  5201. configurable: true
  5202. });
  5203. Object.defineProperty(Tools, "MessageLogLevel", {
  5204. get: function () {
  5205. return Tools._MessageLogLevel;
  5206. },
  5207. enumerable: true,
  5208. configurable: true
  5209. });
  5210. Object.defineProperty(Tools, "WarningLogLevel", {
  5211. get: function () {
  5212. return Tools._WarningLogLevel;
  5213. },
  5214. enumerable: true,
  5215. configurable: true
  5216. });
  5217. Object.defineProperty(Tools, "ErrorLogLevel", {
  5218. get: function () {
  5219. return Tools._ErrorLogLevel;
  5220. },
  5221. enumerable: true,
  5222. configurable: true
  5223. });
  5224. Object.defineProperty(Tools, "AllLogLevel", {
  5225. get: function () {
  5226. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5227. },
  5228. enumerable: true,
  5229. configurable: true
  5230. });
  5231. Tools._AddLogEntry = function (entry) {
  5232. Tools._LogCache = entry + Tools._LogCache;
  5233. if (Tools.OnNewCacheEntry) {
  5234. Tools.OnNewCacheEntry(entry);
  5235. }
  5236. };
  5237. Tools._FormatMessage = function (message) {
  5238. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5239. var date = new Date();
  5240. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5241. };
  5242. Tools._LogDisabled = function (message) {
  5243. // nothing to do
  5244. };
  5245. Tools._LogEnabled = function (message) {
  5246. var formattedMessage = Tools._FormatMessage(message);
  5247. console.log("BJS - " + formattedMessage);
  5248. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5249. Tools._AddLogEntry(entry);
  5250. };
  5251. Tools._WarnDisabled = function (message) {
  5252. // nothing to do
  5253. };
  5254. Tools._WarnEnabled = function (message) {
  5255. var formattedMessage = Tools._FormatMessage(message);
  5256. console.warn("BJS - " + formattedMessage);
  5257. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5258. Tools._AddLogEntry(entry);
  5259. };
  5260. Tools._ErrorDisabled = function (message) {
  5261. // nothing to do
  5262. };
  5263. Tools._ErrorEnabled = function (message) {
  5264. Tools.errorsCount++;
  5265. var formattedMessage = Tools._FormatMessage(message);
  5266. console.error("BJS - " + formattedMessage);
  5267. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5268. Tools._AddLogEntry(entry);
  5269. };
  5270. Object.defineProperty(Tools, "LogCache", {
  5271. get: function () {
  5272. return Tools._LogCache;
  5273. },
  5274. enumerable: true,
  5275. configurable: true
  5276. });
  5277. Tools.ClearLogCache = function () {
  5278. Tools._LogCache = "";
  5279. Tools.errorsCount = 0;
  5280. };
  5281. Object.defineProperty(Tools, "LogLevels", {
  5282. set: function (level) {
  5283. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5284. Tools.Log = Tools._LogEnabled;
  5285. }
  5286. else {
  5287. Tools.Log = Tools._LogDisabled;
  5288. }
  5289. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5290. Tools.Warn = Tools._WarnEnabled;
  5291. }
  5292. else {
  5293. Tools.Warn = Tools._WarnDisabled;
  5294. }
  5295. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5296. Tools.Error = Tools._ErrorEnabled;
  5297. }
  5298. else {
  5299. Tools.Error = Tools._ErrorDisabled;
  5300. }
  5301. },
  5302. enumerable: true,
  5303. configurable: true
  5304. });
  5305. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5306. get: function () {
  5307. return Tools._PerformanceNoneLogLevel;
  5308. },
  5309. enumerable: true,
  5310. configurable: true
  5311. });
  5312. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5313. get: function () {
  5314. return Tools._PerformanceUserMarkLogLevel;
  5315. },
  5316. enumerable: true,
  5317. configurable: true
  5318. });
  5319. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5320. get: function () {
  5321. return Tools._PerformanceConsoleLogLevel;
  5322. },
  5323. enumerable: true,
  5324. configurable: true
  5325. });
  5326. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5327. set: function (level) {
  5328. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5329. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5330. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5331. return;
  5332. }
  5333. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5334. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5335. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5336. return;
  5337. }
  5338. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5339. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5340. },
  5341. enumerable: true,
  5342. configurable: true
  5343. });
  5344. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5345. };
  5346. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5347. };
  5348. Tools._StartUserMark = function (counterName, condition) {
  5349. if (condition === void 0) { condition = true; }
  5350. if (!condition || !Tools._performance.mark) {
  5351. return;
  5352. }
  5353. Tools._performance.mark(counterName + "-Begin");
  5354. };
  5355. Tools._EndUserMark = function (counterName, condition) {
  5356. if (condition === void 0) { condition = true; }
  5357. if (!condition || !Tools._performance.mark) {
  5358. return;
  5359. }
  5360. Tools._performance.mark(counterName + "-End");
  5361. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5362. };
  5363. Tools._StartPerformanceConsole = function (counterName, condition) {
  5364. if (condition === void 0) { condition = true; }
  5365. if (!condition) {
  5366. return;
  5367. }
  5368. Tools._StartUserMark(counterName, condition);
  5369. if (console.time) {
  5370. console.time(counterName);
  5371. }
  5372. };
  5373. Tools._EndPerformanceConsole = function (counterName, condition) {
  5374. if (condition === void 0) { condition = true; }
  5375. if (!condition) {
  5376. return;
  5377. }
  5378. Tools._EndUserMark(counterName, condition);
  5379. if (console.time) {
  5380. console.timeEnd(counterName);
  5381. }
  5382. };
  5383. Object.defineProperty(Tools, "Now", {
  5384. get: function () {
  5385. if (window.performance && window.performance.now) {
  5386. return window.performance.now();
  5387. }
  5388. return new Date().getTime();
  5389. },
  5390. enumerable: true,
  5391. configurable: true
  5392. });
  5393. /**
  5394. * This method will return the name of the class used to create the instance of the given object.
  5395. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5396. * @param object the object to get the class name from
  5397. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5398. */
  5399. Tools.getClassName = function (object, isType) {
  5400. if (isType === void 0) { isType = false; }
  5401. var name = null;
  5402. if (!isType && object.getClassName) {
  5403. name = object.getClassName();
  5404. }
  5405. else {
  5406. if (object instanceof Object) {
  5407. var classObj = isType ? object : Object.getPrototypeOf(object);
  5408. name = classObj.constructor["__bjsclassName__"];
  5409. }
  5410. if (!name) {
  5411. name = typeof object;
  5412. }
  5413. }
  5414. return name;
  5415. };
  5416. Tools.first = function (array, predicate) {
  5417. for (var _i = 0; _i < array.length; _i++) {
  5418. var el = array[_i];
  5419. if (predicate(el)) {
  5420. return el;
  5421. }
  5422. }
  5423. };
  5424. /**
  5425. * 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.
  5426. * @param array
  5427. */
  5428. Tools.arrayOrStringFeeder = function (array) {
  5429. return function (index) {
  5430. if (index >= array.length) {
  5431. return null;
  5432. }
  5433. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5434. if (val && val.getHashCode) {
  5435. val = val.getHashCode();
  5436. }
  5437. if (typeof val === "string") {
  5438. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5439. }
  5440. return val;
  5441. };
  5442. };
  5443. /**
  5444. * Compute the hashCode of a stream of number
  5445. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5446. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5447. * @return the hash code computed
  5448. */
  5449. Tools.hashCodeFromStream = function (feeder) {
  5450. // Based from here: http://stackoverflow.com/a/7616484/802124
  5451. var hash = 0;
  5452. var index = 0;
  5453. var chr = feeder(index++);
  5454. while (chr != null) {
  5455. hash = ((hash << 5) - hash) + chr;
  5456. hash |= 0; // Convert to 32bit integer
  5457. chr = feeder(index++);
  5458. }
  5459. return hash;
  5460. };
  5461. Tools.BaseUrl = "";
  5462. Tools.CorsBehavior = "anonymous";
  5463. Tools.UseFallbackTexture = true;
  5464. // Logs
  5465. Tools._NoneLogLevel = 0;
  5466. Tools._MessageLogLevel = 1;
  5467. Tools._WarningLogLevel = 2;
  5468. Tools._ErrorLogLevel = 4;
  5469. Tools._LogCache = "";
  5470. Tools.errorsCount = 0;
  5471. Tools.Log = Tools._LogEnabled;
  5472. Tools.Warn = Tools._WarnEnabled;
  5473. Tools.Error = Tools._ErrorEnabled;
  5474. // Performances
  5475. Tools._PerformanceNoneLogLevel = 0;
  5476. Tools._PerformanceUserMarkLogLevel = 1;
  5477. Tools._PerformanceConsoleLogLevel = 2;
  5478. Tools._performance = window.performance;
  5479. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5480. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5481. return Tools;
  5482. })();
  5483. BABYLON.Tools = Tools;
  5484. /**
  5485. * This class is used to track a performance counter which is number based.
  5486. * The user has access to many properties which give statistics of different nature
  5487. *
  5488. * The implementer can track two kinds of Performance Counter: time and count
  5489. * 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.
  5490. * 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.
  5491. */
  5492. var PerfCounter = (function () {
  5493. function PerfCounter() {
  5494. this._startMonitoringTime = 0;
  5495. this._min = 0;
  5496. this._max = 0;
  5497. this._average = 0;
  5498. this._lastSecAverage = 0;
  5499. this._current = 0;
  5500. this._totalValueCount = 0;
  5501. this._totalAccumulated = 0;
  5502. this._lastSecAccumulated = 0;
  5503. this._lastSecTime = 0;
  5504. this._lastSecValueCount = 0;
  5505. }
  5506. Object.defineProperty(PerfCounter.prototype, "min", {
  5507. /**
  5508. * Returns the smallest value ever
  5509. */
  5510. get: function () {
  5511. return this._min;
  5512. },
  5513. enumerable: true,
  5514. configurable: true
  5515. });
  5516. Object.defineProperty(PerfCounter.prototype, "max", {
  5517. /**
  5518. * Returns the biggest value ever
  5519. */
  5520. get: function () {
  5521. return this._max;
  5522. },
  5523. enumerable: true,
  5524. configurable: true
  5525. });
  5526. Object.defineProperty(PerfCounter.prototype, "average", {
  5527. /**
  5528. * Returns the average value since the performance counter is running
  5529. */
  5530. get: function () {
  5531. return this._average;
  5532. },
  5533. enumerable: true,
  5534. configurable: true
  5535. });
  5536. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5537. /**
  5538. * Returns the average value of the last second the counter was monitored
  5539. */
  5540. get: function () {
  5541. return this._lastSecAverage;
  5542. },
  5543. enumerable: true,
  5544. configurable: true
  5545. });
  5546. Object.defineProperty(PerfCounter.prototype, "current", {
  5547. /**
  5548. * Returns the current value
  5549. */
  5550. get: function () {
  5551. return this._current;
  5552. },
  5553. enumerable: true,
  5554. configurable: true
  5555. });
  5556. Object.defineProperty(PerfCounter.prototype, "total", {
  5557. get: function () {
  5558. return this._totalAccumulated;
  5559. },
  5560. enumerable: true,
  5561. configurable: true
  5562. });
  5563. /**
  5564. * Call this method to start monitoring a new frame.
  5565. * 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.
  5566. */
  5567. PerfCounter.prototype.fetchNewFrame = function () {
  5568. this._totalValueCount++;
  5569. this._current = 0;
  5570. this._lastSecValueCount++;
  5571. };
  5572. /**
  5573. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5574. * @param newCount the count value to add to the monitored count
  5575. * @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.
  5576. */
  5577. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5578. this._current += newCount;
  5579. if (fetchResult) {
  5580. this._fetchResult();
  5581. }
  5582. };
  5583. /**
  5584. * Start monitoring this performance counter
  5585. */
  5586. PerfCounter.prototype.beginMonitoring = function () {
  5587. this._startMonitoringTime = Tools.Now;
  5588. };
  5589. /**
  5590. * Compute the time lapsed since the previous beginMonitoring() call.
  5591. * @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
  5592. */
  5593. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5594. if (newFrame === void 0) { newFrame = true; }
  5595. if (newFrame) {
  5596. this.fetchNewFrame();
  5597. }
  5598. var currentTime = Tools.Now;
  5599. this._current = currentTime - this._startMonitoringTime;
  5600. if (newFrame) {
  5601. this._fetchResult();
  5602. }
  5603. };
  5604. PerfCounter.prototype._fetchResult = function () {
  5605. this._totalAccumulated += this._current;
  5606. this._lastSecAccumulated += this._current;
  5607. // Min/Max update
  5608. this._min = Math.min(this._min, this._current);
  5609. this._max = Math.max(this._max, this._current);
  5610. this._average = this._totalAccumulated / this._totalValueCount;
  5611. // Reset last sec?
  5612. var now = Tools.Now;
  5613. if ((now - this._lastSecTime) > 1000) {
  5614. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5615. this._lastSecTime = now;
  5616. this._lastSecAccumulated = 0;
  5617. this._lastSecValueCount = 0;
  5618. }
  5619. };
  5620. return PerfCounter;
  5621. })();
  5622. BABYLON.PerfCounter = PerfCounter;
  5623. /**
  5624. * Use this className as a decorator on a given class definition to add it a name.
  5625. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5626. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5627. * @param name
  5628. */
  5629. function className(name) {
  5630. return function (target) {
  5631. target["__bjsclassName__"] = name;
  5632. };
  5633. }
  5634. BABYLON.className = className;
  5635. /**
  5636. * An implementation of a loop for asynchronous functions.
  5637. */
  5638. var AsyncLoop = (function () {
  5639. /**
  5640. * Constroctor.
  5641. * @param iterations the number of iterations.
  5642. * @param _fn the function to run each iteration
  5643. * @param _successCallback the callback that will be called upon succesful execution
  5644. * @param offset starting offset.
  5645. */
  5646. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5647. if (offset === void 0) { offset = 0; }
  5648. this.iterations = iterations;
  5649. this._fn = _fn;
  5650. this._successCallback = _successCallback;
  5651. this.index = offset - 1;
  5652. this._done = false;
  5653. }
  5654. /**
  5655. * Execute the next iteration. Must be called after the last iteration was finished.
  5656. */
  5657. AsyncLoop.prototype.executeNext = function () {
  5658. if (!this._done) {
  5659. if (this.index + 1 < this.iterations) {
  5660. ++this.index;
  5661. this._fn(this);
  5662. }
  5663. else {
  5664. this.breakLoop();
  5665. }
  5666. }
  5667. };
  5668. /**
  5669. * Break the loop and run the success callback.
  5670. */
  5671. AsyncLoop.prototype.breakLoop = function () {
  5672. this._done = true;
  5673. this._successCallback();
  5674. };
  5675. /**
  5676. * Helper function
  5677. */
  5678. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5679. if (offset === void 0) { offset = 0; }
  5680. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5681. loop.executeNext();
  5682. return loop;
  5683. };
  5684. /**
  5685. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5686. * @param iterations total number of iterations
  5687. * @param syncedIterations number of synchronous iterations in each async iteration.
  5688. * @param fn the function to call each iteration.
  5689. * @param callback a success call back that will be called when iterating stops.
  5690. * @param breakFunction a break condition (optional)
  5691. * @param timeout timeout settings for the setTimeout function. default - 0.
  5692. * @constructor
  5693. */
  5694. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5695. if (timeout === void 0) { timeout = 0; }
  5696. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5697. if (breakFunction && breakFunction())
  5698. loop.breakLoop();
  5699. else {
  5700. setTimeout(function () {
  5701. for (var i = 0; i < syncedIterations; ++i) {
  5702. var iteration = (loop.index * syncedIterations) + i;
  5703. if (iteration >= iterations)
  5704. break;
  5705. fn(iteration);
  5706. if (breakFunction && breakFunction()) {
  5707. loop.breakLoop();
  5708. break;
  5709. }
  5710. }
  5711. loop.executeNext();
  5712. }, timeout);
  5713. }
  5714. }, callback);
  5715. };
  5716. return AsyncLoop;
  5717. })();
  5718. BABYLON.AsyncLoop = AsyncLoop;
  5719. })(BABYLON || (BABYLON = {}));
  5720. var BABYLON;
  5721. (function (BABYLON) {
  5722. var Internals;
  5723. (function (Internals) {
  5724. var _AlphaState = (function () {
  5725. function _AlphaState() {
  5726. this._isAlphaBlendDirty = false;
  5727. this._isBlendFunctionParametersDirty = false;
  5728. this._alphaBlend = false;
  5729. this._blendFunctionParameters = new Array(4);
  5730. }
  5731. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5732. get: function () {
  5733. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5734. },
  5735. enumerable: true,
  5736. configurable: true
  5737. });
  5738. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5739. get: function () {
  5740. return this._alphaBlend;
  5741. },
  5742. set: function (value) {
  5743. if (this._alphaBlend === value) {
  5744. return;
  5745. }
  5746. this._alphaBlend = value;
  5747. this._isAlphaBlendDirty = true;
  5748. },
  5749. enumerable: true,
  5750. configurable: true
  5751. });
  5752. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5753. if (this._blendFunctionParameters[0] === value0 &&
  5754. this._blendFunctionParameters[1] === value1 &&
  5755. this._blendFunctionParameters[2] === value2 &&
  5756. this._blendFunctionParameters[3] === value3) {
  5757. return;
  5758. }
  5759. this._blendFunctionParameters[0] = value0;
  5760. this._blendFunctionParameters[1] = value1;
  5761. this._blendFunctionParameters[2] = value2;
  5762. this._blendFunctionParameters[3] = value3;
  5763. this._isBlendFunctionParametersDirty = true;
  5764. };
  5765. _AlphaState.prototype.reset = function () {
  5766. this._alphaBlend = false;
  5767. this._blendFunctionParameters[0] = null;
  5768. this._blendFunctionParameters[1] = null;
  5769. this._blendFunctionParameters[2] = null;
  5770. this._blendFunctionParameters[3] = null;
  5771. this._isAlphaBlendDirty = true;
  5772. this._isBlendFunctionParametersDirty = false;
  5773. };
  5774. _AlphaState.prototype.apply = function (gl) {
  5775. if (!this.isDirty) {
  5776. return;
  5777. }
  5778. // Alpha blend
  5779. if (this._isAlphaBlendDirty) {
  5780. if (this._alphaBlend) {
  5781. gl.enable(gl.BLEND);
  5782. }
  5783. else {
  5784. gl.disable(gl.BLEND);
  5785. }
  5786. this._isAlphaBlendDirty = false;
  5787. }
  5788. // Alpha function
  5789. if (this._isBlendFunctionParametersDirty) {
  5790. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5791. this._isBlendFunctionParametersDirty = false;
  5792. }
  5793. };
  5794. return _AlphaState;
  5795. })();
  5796. Internals._AlphaState = _AlphaState;
  5797. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5798. })(BABYLON || (BABYLON = {}));
  5799. var BABYLON;
  5800. (function (BABYLON) {
  5801. var Internals;
  5802. (function (Internals) {
  5803. var _DepthCullingState = (function () {
  5804. function _DepthCullingState() {
  5805. this._isDepthTestDirty = false;
  5806. this._isDepthMaskDirty = false;
  5807. this._isDepthFuncDirty = false;
  5808. this._isCullFaceDirty = false;
  5809. this._isCullDirty = false;
  5810. this._isZOffsetDirty = false;
  5811. }
  5812. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5813. get: function () {
  5814. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5815. },
  5816. enumerable: true,
  5817. configurable: true
  5818. });
  5819. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5820. get: function () {
  5821. return this._zOffset;
  5822. },
  5823. set: function (value) {
  5824. if (this._zOffset === value) {
  5825. return;
  5826. }
  5827. this._zOffset = value;
  5828. this._isZOffsetDirty = true;
  5829. },
  5830. enumerable: true,
  5831. configurable: true
  5832. });
  5833. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5834. get: function () {
  5835. return this._cullFace;
  5836. },
  5837. set: function (value) {
  5838. if (this._cullFace === value) {
  5839. return;
  5840. }
  5841. this._cullFace = value;
  5842. this._isCullFaceDirty = true;
  5843. },
  5844. enumerable: true,
  5845. configurable: true
  5846. });
  5847. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5848. get: function () {
  5849. return this._cull;
  5850. },
  5851. set: function (value) {
  5852. if (this._cull === value) {
  5853. return;
  5854. }
  5855. this._cull = value;
  5856. this._isCullDirty = true;
  5857. },
  5858. enumerable: true,
  5859. configurable: true
  5860. });
  5861. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5862. get: function () {
  5863. return this._depthFunc;
  5864. },
  5865. set: function (value) {
  5866. if (this._depthFunc === value) {
  5867. return;
  5868. }
  5869. this._depthFunc = value;
  5870. this._isDepthFuncDirty = true;
  5871. },
  5872. enumerable: true,
  5873. configurable: true
  5874. });
  5875. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5876. get: function () {
  5877. return this._depthMask;
  5878. },
  5879. set: function (value) {
  5880. if (this._depthMask === value) {
  5881. return;
  5882. }
  5883. this._depthMask = value;
  5884. this._isDepthMaskDirty = true;
  5885. },
  5886. enumerable: true,
  5887. configurable: true
  5888. });
  5889. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5890. get: function () {
  5891. return this._depthTest;
  5892. },
  5893. set: function (value) {
  5894. if (this._depthTest === value) {
  5895. return;
  5896. }
  5897. this._depthTest = value;
  5898. this._isDepthTestDirty = true;
  5899. },
  5900. enumerable: true,
  5901. configurable: true
  5902. });
  5903. _DepthCullingState.prototype.reset = function () {
  5904. this._depthMask = true;
  5905. this._depthTest = true;
  5906. this._depthFunc = null;
  5907. this._cullFace = null;
  5908. this._cull = null;
  5909. this._zOffset = 0;
  5910. this._isDepthTestDirty = true;
  5911. this._isDepthMaskDirty = true;
  5912. this._isDepthFuncDirty = false;
  5913. this._isCullFaceDirty = false;
  5914. this._isCullDirty = false;
  5915. this._isZOffsetDirty = false;
  5916. };
  5917. _DepthCullingState.prototype.apply = function (gl) {
  5918. if (!this.isDirty) {
  5919. return;
  5920. }
  5921. // Cull
  5922. if (this._isCullDirty) {
  5923. if (this.cull) {
  5924. gl.enable(gl.CULL_FACE);
  5925. }
  5926. else {
  5927. gl.disable(gl.CULL_FACE);
  5928. }
  5929. this._isCullDirty = false;
  5930. }
  5931. // Cull face
  5932. if (this._isCullFaceDirty) {
  5933. gl.cullFace(this.cullFace);
  5934. this._isCullFaceDirty = false;
  5935. }
  5936. // Depth mask
  5937. if (this._isDepthMaskDirty) {
  5938. gl.depthMask(this.depthMask);
  5939. this._isDepthMaskDirty = false;
  5940. }
  5941. // Depth test
  5942. if (this._isDepthTestDirty) {
  5943. if (this.depthTest) {
  5944. gl.enable(gl.DEPTH_TEST);
  5945. }
  5946. else {
  5947. gl.disable(gl.DEPTH_TEST);
  5948. }
  5949. this._isDepthTestDirty = false;
  5950. }
  5951. // Depth func
  5952. if (this._isDepthFuncDirty) {
  5953. gl.depthFunc(this.depthFunc);
  5954. this._isDepthFuncDirty = false;
  5955. }
  5956. // zOffset
  5957. if (this._isZOffsetDirty) {
  5958. if (this.zOffset) {
  5959. gl.enable(gl.POLYGON_OFFSET_FILL);
  5960. gl.polygonOffset(this.zOffset, 0);
  5961. }
  5962. else {
  5963. gl.disable(gl.POLYGON_OFFSET_FILL);
  5964. }
  5965. this._isZOffsetDirty = false;
  5966. }
  5967. };
  5968. return _DepthCullingState;
  5969. })();
  5970. Internals._DepthCullingState = _DepthCullingState;
  5971. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5972. })(BABYLON || (BABYLON = {}));
  5973. var BABYLON;
  5974. (function (BABYLON) {
  5975. var Internals;
  5976. (function (Internals) {
  5977. var _StencilState = (function () {
  5978. function _StencilState() {
  5979. this._isStencilTestDirty = false;
  5980. this._isStencilMaskDirty = false;
  5981. this._isStencilFuncDirty = false;
  5982. this._isStencilOpDirty = false;
  5983. this.reset();
  5984. }
  5985. Object.defineProperty(_StencilState.prototype, "isDirty", {
  5986. get: function () {
  5987. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  5988. },
  5989. enumerable: true,
  5990. configurable: true
  5991. });
  5992. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  5993. get: function () {
  5994. return this._stencilFunc;
  5995. },
  5996. set: function (value) {
  5997. if (this._stencilFunc === value) {
  5998. return;
  5999. }
  6000. this._stencilFunc = value;
  6001. this._isStencilFuncDirty = true;
  6002. },
  6003. enumerable: true,
  6004. configurable: true
  6005. });
  6006. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6007. get: function () {
  6008. return this._stencilFuncRef;
  6009. },
  6010. set: function (value) {
  6011. if (this._stencilFuncRef === value) {
  6012. return;
  6013. }
  6014. this._stencilFuncRef = value;
  6015. this._isStencilFuncDirty = true;
  6016. },
  6017. enumerable: true,
  6018. configurable: true
  6019. });
  6020. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6021. get: function () {
  6022. return this._stencilFuncMask;
  6023. },
  6024. set: function (value) {
  6025. if (this._stencilFuncMask === value) {
  6026. return;
  6027. }
  6028. this._stencilFuncMask = value;
  6029. this._isStencilFuncDirty = true;
  6030. },
  6031. enumerable: true,
  6032. configurable: true
  6033. });
  6034. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6035. get: function () {
  6036. return this._stencilOpStencilFail;
  6037. },
  6038. set: function (value) {
  6039. if (this._stencilOpStencilFail === value) {
  6040. return;
  6041. }
  6042. this._stencilOpStencilFail = value;
  6043. this._isStencilOpDirty = true;
  6044. },
  6045. enumerable: true,
  6046. configurable: true
  6047. });
  6048. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6049. get: function () {
  6050. return this._stencilOpDepthFail;
  6051. },
  6052. set: function (value) {
  6053. if (this._stencilOpDepthFail === value) {
  6054. return;
  6055. }
  6056. this._stencilOpDepthFail = value;
  6057. this._isStencilOpDirty = true;
  6058. },
  6059. enumerable: true,
  6060. configurable: true
  6061. });
  6062. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6063. get: function () {
  6064. return this._stencilOpStencilDepthPass;
  6065. },
  6066. set: function (value) {
  6067. if (this._stencilOpStencilDepthPass === value) {
  6068. return;
  6069. }
  6070. this._stencilOpStencilDepthPass = value;
  6071. this._isStencilOpDirty = true;
  6072. },
  6073. enumerable: true,
  6074. configurable: true
  6075. });
  6076. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6077. get: function () {
  6078. return this._stencilMask;
  6079. },
  6080. set: function (value) {
  6081. if (this._stencilMask === value) {
  6082. return;
  6083. }
  6084. this._stencilMask = value;
  6085. this._isStencilMaskDirty = true;
  6086. },
  6087. enumerable: true,
  6088. configurable: true
  6089. });
  6090. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6091. get: function () {
  6092. return this._stencilTest;
  6093. },
  6094. set: function (value) {
  6095. if (this._stencilTest === value) {
  6096. return;
  6097. }
  6098. this._stencilTest = value;
  6099. this._isStencilTestDirty = true;
  6100. },
  6101. enumerable: true,
  6102. configurable: true
  6103. });
  6104. _StencilState.prototype.reset = function () {
  6105. this._stencilTest = false;
  6106. this._stencilMask = 0xFF;
  6107. this._stencilFunc = 0x0207; //WebGLRenderingContext.ALWAYS;
  6108. this._stencilFuncRef = 1;
  6109. this._stencilFuncMask = 0xFF;
  6110. this._stencilOpStencilFail = 0x1E00; //WebGLRenderingContext.KEEP;
  6111. this._stencilOpDepthFail = 0x1E00; //WebGLRenderingContext.KEEP;
  6112. this._stencilOpStencilDepthPass = 0x1E01; //WebGLRenderingContext.REPLACE;
  6113. this._isStencilTestDirty = true;
  6114. this._isStencilMaskDirty = true;
  6115. this._isStencilFuncDirty = true;
  6116. this._isStencilOpDirty = true;
  6117. };
  6118. _StencilState.prototype.apply = function (gl) {
  6119. if (!this.isDirty) {
  6120. return;
  6121. }
  6122. // Stencil test
  6123. if (this._isStencilTestDirty) {
  6124. if (this.stencilTest) {
  6125. gl.enable(gl.STENCIL_TEST);
  6126. }
  6127. else {
  6128. gl.disable(gl.STENCIL_TEST);
  6129. }
  6130. this._isStencilTestDirty = false;
  6131. }
  6132. // Stencil mask
  6133. if (this._isStencilMaskDirty) {
  6134. gl.stencilMask(this.stencilMask);
  6135. this._isStencilMaskDirty = false;
  6136. }
  6137. // Stencil func
  6138. if (this._isStencilFuncDirty) {
  6139. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6140. this._isStencilFuncDirty = false;
  6141. }
  6142. // Stencil op
  6143. if (this._isStencilOpDirty) {
  6144. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6145. this._isStencilOpDirty = false;
  6146. }
  6147. };
  6148. return _StencilState;
  6149. })();
  6150. Internals._StencilState = _StencilState;
  6151. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6152. })(BABYLON || (BABYLON = {}));
  6153. var BABYLON;
  6154. (function (BABYLON) {
  6155. var compileShader = function (gl, source, type, defines) {
  6156. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6157. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6158. gl.compileShader(shader);
  6159. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6160. throw new Error(gl.getShaderInfoLog(shader));
  6161. }
  6162. return shader;
  6163. };
  6164. var HALF_FLOAT_OES = 0x8D61;
  6165. var getWebGLTextureType = function (gl, type) {
  6166. if (type === Engine.TEXTURETYPE_FLOAT) {
  6167. return gl.FLOAT;
  6168. }
  6169. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6170. // Add Half Float Constant.
  6171. return HALF_FLOAT_OES;
  6172. }
  6173. return gl.UNSIGNED_BYTE;
  6174. };
  6175. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6176. var magFilter = gl.NEAREST;
  6177. var minFilter = gl.NEAREST;
  6178. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6179. magFilter = gl.LINEAR;
  6180. if (generateMipMaps) {
  6181. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6182. }
  6183. else {
  6184. minFilter = gl.LINEAR;
  6185. }
  6186. }
  6187. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6188. magFilter = gl.LINEAR;
  6189. if (generateMipMaps) {
  6190. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6191. }
  6192. else {
  6193. minFilter = gl.LINEAR;
  6194. }
  6195. }
  6196. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6197. magFilter = gl.NEAREST;
  6198. if (generateMipMaps) {
  6199. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6200. }
  6201. else {
  6202. minFilter = gl.NEAREST;
  6203. }
  6204. }
  6205. return {
  6206. min: minFilter,
  6207. mag: magFilter
  6208. };
  6209. };
  6210. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6211. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6212. var engine = scene.getEngine();
  6213. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6214. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6215. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6216. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6217. texture._baseWidth = width;
  6218. texture._baseHeight = height;
  6219. texture._width = potWidth;
  6220. texture._height = potHeight;
  6221. texture.isReady = true;
  6222. processFunction(potWidth, potHeight);
  6223. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6224. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6225. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6226. if (!noMipmap && !isCompressed) {
  6227. gl.generateMipmap(gl.TEXTURE_2D);
  6228. }
  6229. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6230. engine.resetTextureCache();
  6231. scene._removePendingData(texture);
  6232. texture.onLoadedCallbacks.forEach(function (callback) {
  6233. callback();
  6234. });
  6235. texture.onLoadedCallbacks = [];
  6236. };
  6237. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  6238. var img;
  6239. var onload = function () {
  6240. loadedImages[index] = img;
  6241. loadedImages._internalCount++;
  6242. scene._removePendingData(img);
  6243. if (loadedImages._internalCount === 6) {
  6244. onfinish(loadedImages);
  6245. }
  6246. };
  6247. var onerror = function () {
  6248. scene._removePendingData(img);
  6249. };
  6250. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6251. scene._addPendingData(img);
  6252. };
  6253. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  6254. var loadedImages = [];
  6255. loadedImages._internalCount = 0;
  6256. for (var index = 0; index < 6; index++) {
  6257. partialLoad(files[index], index, loadedImages, scene, onfinish);
  6258. }
  6259. };
  6260. var InstancingAttributeInfo = (function () {
  6261. function InstancingAttributeInfo() {
  6262. }
  6263. return InstancingAttributeInfo;
  6264. })();
  6265. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6266. var EngineCapabilities = (function () {
  6267. function EngineCapabilities() {
  6268. }
  6269. return EngineCapabilities;
  6270. })();
  6271. BABYLON.EngineCapabilities = EngineCapabilities;
  6272. /**
  6273. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6274. */
  6275. var Engine = (function () {
  6276. /**
  6277. * @constructor
  6278. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6279. * @param {boolean} [antialias] - enable antialias
  6280. * @param options - further options to be sent to the getContext function
  6281. */
  6282. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6283. var _this = this;
  6284. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6285. // Public members
  6286. this.isFullscreen = false;
  6287. this.isPointerLock = false;
  6288. this.cullBackFaces = true;
  6289. this.renderEvenInBackground = true;
  6290. // To enable/disable IDB support and avoid XHR on .manifest
  6291. this.enableOfflineSupport = true;
  6292. this.scenes = new Array();
  6293. this._windowIsBackground = false;
  6294. this._webGLVersion = "1.0";
  6295. this._drawCalls = new BABYLON.PerfCounter();
  6296. this._renderingQueueLaunched = false;
  6297. this._activeRenderLoops = [];
  6298. // FPS
  6299. this.fpsRange = 60;
  6300. this.previousFramesDuration = [];
  6301. this.fps = 60;
  6302. this.deltaTime = 0;
  6303. // States
  6304. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6305. this._stencilState = new BABYLON.Internals._StencilState();
  6306. this._alphaState = new BABYLON.Internals._AlphaState();
  6307. this._alphaMode = Engine.ALPHA_DISABLE;
  6308. // Cache
  6309. this._loadedTexturesCache = new Array();
  6310. this._maxTextureChannels = 16;
  6311. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6312. this._compiledEffects = {};
  6313. this._vertexAttribArraysEnabled = [];
  6314. this._uintIndicesCurrentlySet = false;
  6315. this._currentBoundBuffer = new Array();
  6316. this._currentBufferPointers = [];
  6317. this._currentInstanceLocations = new Array();
  6318. this._currentInstanceBuffers = new Array();
  6319. this._onVRFullScreenTriggered = function () {
  6320. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6321. //get the old size before we change
  6322. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6323. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6324. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6325. //But actually, no browser follow the specs...
  6326. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6327. //get the width and height, change the render size
  6328. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6329. var width, height;
  6330. _this.setHardwareScalingLevel(1);
  6331. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6332. }
  6333. else {
  6334. //When the specs are implemented, need to uncomment this.
  6335. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6336. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6337. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6338. _this._vrDisplayEnabled = undefined;
  6339. }
  6340. };
  6341. this._renderingCanvas = canvas;
  6342. this._externalData = new BABYLON.StringDictionary();
  6343. options = options || {};
  6344. if (antialias != null) {
  6345. options.antialias = antialias;
  6346. }
  6347. if (options.preserveDrawingBuffer === undefined) {
  6348. options.preserveDrawingBuffer = false;
  6349. }
  6350. // Checks if some of the format renders first to allow the use of webgl inspector.
  6351. var renderToFullFloat = this._canRenderToFloatTexture();
  6352. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6353. // GL
  6354. //try {
  6355. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6356. // if (this._gl) {
  6357. // this._webGLVersion = "2.0";
  6358. // }
  6359. //} catch (e) {
  6360. // // Do nothing
  6361. //}
  6362. if (!this._gl) {
  6363. try {
  6364. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6365. }
  6366. catch (e) {
  6367. throw new Error("WebGL not supported");
  6368. }
  6369. }
  6370. if (!this._gl) {
  6371. throw new Error("WebGL not supported");
  6372. }
  6373. this._onBlur = function () {
  6374. _this._windowIsBackground = true;
  6375. };
  6376. this._onFocus = function () {
  6377. _this._windowIsBackground = false;
  6378. };
  6379. window.addEventListener("blur", this._onBlur);
  6380. window.addEventListener("focus", this._onFocus);
  6381. // Viewport
  6382. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6383. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6384. this.resize();
  6385. // Caps
  6386. this._isStencilEnable = options.stencil;
  6387. this._caps = new EngineCapabilities();
  6388. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6389. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6390. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6391. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6392. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6393. // Infos
  6394. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6395. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6396. if (rendererInfo != null) {
  6397. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6398. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6399. }
  6400. if (!this._glVendor) {
  6401. this._glVendor = "Unknown vendor";
  6402. }
  6403. if (!this._glRenderer) {
  6404. this._glRenderer = "Unknown renderer";
  6405. }
  6406. // Extensions
  6407. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6408. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6409. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6410. 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');
  6411. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6412. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6413. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6414. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6415. this._caps.highPrecisionShaderSupported = true;
  6416. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6417. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6418. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6419. this._caps.textureFloatRender = renderToFullFloat;
  6420. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6421. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6422. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6423. if (this._gl.getShaderPrecisionFormat) {
  6424. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6425. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6426. }
  6427. // Depth buffer
  6428. this.setDepthBuffer(true);
  6429. this.setDepthFunctionToLessOrEqual();
  6430. this.setDepthWrite(true);
  6431. // Fullscreen
  6432. this._onFullscreenChange = function () {
  6433. if (document.fullscreen !== undefined) {
  6434. _this.isFullscreen = document.fullscreen;
  6435. }
  6436. else if (document.mozFullScreen !== undefined) {
  6437. _this.isFullscreen = document.mozFullScreen;
  6438. }
  6439. else if (document.webkitIsFullScreen !== undefined) {
  6440. _this.isFullscreen = document.webkitIsFullScreen;
  6441. }
  6442. else if (document.msIsFullScreen !== undefined) {
  6443. _this.isFullscreen = document.msIsFullScreen;
  6444. }
  6445. // Pointer lock
  6446. if (_this.isFullscreen && _this._pointerLockRequested) {
  6447. canvas.requestPointerLock = canvas.requestPointerLock ||
  6448. canvas.msRequestPointerLock ||
  6449. canvas.mozRequestPointerLock ||
  6450. canvas.webkitRequestPointerLock;
  6451. if (canvas.requestPointerLock) {
  6452. canvas.requestPointerLock();
  6453. }
  6454. }
  6455. };
  6456. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6457. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6458. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6459. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6460. // Pointer lock
  6461. this._onPointerLockChange = function () {
  6462. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6463. document.webkitPointerLockElement === canvas ||
  6464. document.msPointerLockElement === canvas ||
  6465. document.pointerLockElement === canvas);
  6466. };
  6467. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6468. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6469. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6470. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6471. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6472. Engine.audioEngine = new BABYLON.AudioEngine();
  6473. }
  6474. //default loading screen
  6475. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6476. //Load WebVR Devices
  6477. if (options.autoEnableWebVR) {
  6478. this.initWebVR();
  6479. }
  6480. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6481. }
  6482. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6483. get: function () {
  6484. return Engine._ALPHA_DISABLE;
  6485. },
  6486. enumerable: true,
  6487. configurable: true
  6488. });
  6489. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6490. get: function () {
  6491. return Engine._ALPHA_ONEONE;
  6492. },
  6493. enumerable: true,
  6494. configurable: true
  6495. });
  6496. Object.defineProperty(Engine, "ALPHA_ADD", {
  6497. get: function () {
  6498. return Engine._ALPHA_ADD;
  6499. },
  6500. enumerable: true,
  6501. configurable: true
  6502. });
  6503. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6504. get: function () {
  6505. return Engine._ALPHA_COMBINE;
  6506. },
  6507. enumerable: true,
  6508. configurable: true
  6509. });
  6510. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6511. get: function () {
  6512. return Engine._ALPHA_SUBTRACT;
  6513. },
  6514. enumerable: true,
  6515. configurable: true
  6516. });
  6517. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6518. get: function () {
  6519. return Engine._ALPHA_MULTIPLY;
  6520. },
  6521. enumerable: true,
  6522. configurable: true
  6523. });
  6524. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6525. get: function () {
  6526. return Engine._ALPHA_MAXIMIZED;
  6527. },
  6528. enumerable: true,
  6529. configurable: true
  6530. });
  6531. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6532. get: function () {
  6533. return Engine._DELAYLOADSTATE_NONE;
  6534. },
  6535. enumerable: true,
  6536. configurable: true
  6537. });
  6538. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6539. get: function () {
  6540. return Engine._DELAYLOADSTATE_LOADED;
  6541. },
  6542. enumerable: true,
  6543. configurable: true
  6544. });
  6545. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6546. get: function () {
  6547. return Engine._DELAYLOADSTATE_LOADING;
  6548. },
  6549. enumerable: true,
  6550. configurable: true
  6551. });
  6552. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6553. get: function () {
  6554. return Engine._DELAYLOADSTATE_NOTLOADED;
  6555. },
  6556. enumerable: true,
  6557. configurable: true
  6558. });
  6559. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6560. get: function () {
  6561. return Engine._TEXTUREFORMAT_ALPHA;
  6562. },
  6563. enumerable: true,
  6564. configurable: true
  6565. });
  6566. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6567. get: function () {
  6568. return Engine._TEXTUREFORMAT_LUMINANCE;
  6569. },
  6570. enumerable: true,
  6571. configurable: true
  6572. });
  6573. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6574. get: function () {
  6575. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6576. },
  6577. enumerable: true,
  6578. configurable: true
  6579. });
  6580. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6581. get: function () {
  6582. return Engine._TEXTUREFORMAT_RGB;
  6583. },
  6584. enumerable: true,
  6585. configurable: true
  6586. });
  6587. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6588. get: function () {
  6589. return Engine._TEXTUREFORMAT_RGBA;
  6590. },
  6591. enumerable: true,
  6592. configurable: true
  6593. });
  6594. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6595. get: function () {
  6596. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6597. },
  6598. enumerable: true,
  6599. configurable: true
  6600. });
  6601. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6602. get: function () {
  6603. return Engine._TEXTURETYPE_FLOAT;
  6604. },
  6605. enumerable: true,
  6606. configurable: true
  6607. });
  6608. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6609. get: function () {
  6610. return Engine._TEXTURETYPE_HALF_FLOAT;
  6611. },
  6612. enumerable: true,
  6613. configurable: true
  6614. });
  6615. Object.defineProperty(Engine, "Version", {
  6616. get: function () {
  6617. return "2.5-alpha";
  6618. },
  6619. enumerable: true,
  6620. configurable: true
  6621. });
  6622. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6623. get: function () {
  6624. return this._webGLVersion;
  6625. },
  6626. enumerable: true,
  6627. configurable: true
  6628. });
  6629. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6630. /**
  6631. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6632. */
  6633. get: function () {
  6634. return this._isStencilEnable;
  6635. },
  6636. enumerable: true,
  6637. configurable: true
  6638. });
  6639. Engine.prototype._prepareWorkingCanvas = function () {
  6640. if (this._workingCanvas) {
  6641. return;
  6642. }
  6643. this._workingCanvas = document.createElement("canvas");
  6644. this._workingContext = this._workingCanvas.getContext("2d");
  6645. };
  6646. Engine.prototype.resetTextureCache = function () {
  6647. for (var index = 0; index < this._maxTextureChannels; index++) {
  6648. this._activeTexturesCache[index] = null;
  6649. }
  6650. };
  6651. Engine.prototype.getGlInfo = function () {
  6652. return {
  6653. vendor: this._glVendor,
  6654. renderer: this._glRenderer,
  6655. version: this._glVersion
  6656. };
  6657. };
  6658. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6659. if (useScreen === void 0) { useScreen = false; }
  6660. var viewport = camera.viewport;
  6661. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6662. };
  6663. Engine.prototype.getRenderWidth = function (useScreen) {
  6664. if (useScreen === void 0) { useScreen = false; }
  6665. if (!useScreen && this._currentRenderTarget) {
  6666. return this._currentRenderTarget._width;
  6667. }
  6668. return this._renderingCanvas.width;
  6669. };
  6670. Engine.prototype.getRenderHeight = function (useScreen) {
  6671. if (useScreen === void 0) { useScreen = false; }
  6672. if (!useScreen && this._currentRenderTarget) {
  6673. return this._currentRenderTarget._height;
  6674. }
  6675. return this._renderingCanvas.height;
  6676. };
  6677. Engine.prototype.getRenderingCanvas = function () {
  6678. return this._renderingCanvas;
  6679. };
  6680. Engine.prototype.getRenderingCanvasClientRect = function () {
  6681. return this._renderingCanvas.getBoundingClientRect();
  6682. };
  6683. Engine.prototype.setHardwareScalingLevel = function (level) {
  6684. this._hardwareScalingLevel = level;
  6685. this.resize();
  6686. };
  6687. Engine.prototype.getHardwareScalingLevel = function () {
  6688. return this._hardwareScalingLevel;
  6689. };
  6690. Engine.prototype.getLoadedTexturesCache = function () {
  6691. return this._loadedTexturesCache;
  6692. };
  6693. Engine.prototype.getCaps = function () {
  6694. return this._caps;
  6695. };
  6696. Object.defineProperty(Engine.prototype, "drawCalls", {
  6697. get: function () {
  6698. return this._drawCalls.current;
  6699. },
  6700. enumerable: true,
  6701. configurable: true
  6702. });
  6703. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6704. get: function () {
  6705. return this._drawCalls;
  6706. },
  6707. enumerable: true,
  6708. configurable: true
  6709. });
  6710. Engine.prototype.getDepthFunction = function () {
  6711. return this._depthCullingState.depthFunc;
  6712. };
  6713. Engine.prototype.setDepthFunction = function (depthFunc) {
  6714. this._depthCullingState.depthFunc = depthFunc;
  6715. };
  6716. Engine.prototype.setDepthFunctionToGreater = function () {
  6717. this._depthCullingState.depthFunc = this._gl.GREATER;
  6718. };
  6719. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6720. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6721. };
  6722. Engine.prototype.setDepthFunctionToLess = function () {
  6723. this._depthCullingState.depthFunc = this._gl.LESS;
  6724. };
  6725. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6726. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6727. };
  6728. Engine.prototype.getStencilBuffer = function () {
  6729. return this._stencilState.stencilTest;
  6730. };
  6731. Engine.prototype.setStencilBuffer = function (enable) {
  6732. this._stencilState.stencilTest = enable;
  6733. };
  6734. Engine.prototype.getStencilMask = function () {
  6735. return this._stencilState.stencilMask;
  6736. };
  6737. Engine.prototype.setStencilMask = function (mask) {
  6738. this._stencilState.stencilMask = mask;
  6739. };
  6740. Engine.prototype.getStencilFunction = function () {
  6741. return this._stencilState.stencilFunc;
  6742. };
  6743. Engine.prototype.getStencilFunctionReference = function () {
  6744. return this._stencilState.stencilFuncRef;
  6745. };
  6746. Engine.prototype.getStencilFunctionMask = function () {
  6747. return this._stencilState.stencilFuncMask;
  6748. };
  6749. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6750. this._stencilState.stencilFunc = stencilFunc;
  6751. };
  6752. Engine.prototype.setStencilFunctionReference = function (reference) {
  6753. this._stencilState.stencilFuncRef = reference;
  6754. };
  6755. Engine.prototype.setStencilFunctionMask = function (mask) {
  6756. this._stencilState.stencilFuncMask = mask;
  6757. };
  6758. Engine.prototype.getStencilOperationFail = function () {
  6759. return this._stencilState.stencilOpStencilFail;
  6760. };
  6761. Engine.prototype.getStencilOperationDepthFail = function () {
  6762. return this._stencilState.stencilOpDepthFail;
  6763. };
  6764. Engine.prototype.getStencilOperationPass = function () {
  6765. return this._stencilState.stencilOpStencilDepthPass;
  6766. };
  6767. Engine.prototype.setStencilOperationFail = function (operation) {
  6768. this._stencilState.stencilOpStencilFail = operation;
  6769. };
  6770. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  6771. this._stencilState.stencilOpDepthFail = operation;
  6772. };
  6773. Engine.prototype.setStencilOperationPass = function (operation) {
  6774. this._stencilState.stencilOpStencilDepthPass = operation;
  6775. };
  6776. /**
  6777. * stop executing a render loop function and remove it from the execution array
  6778. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6779. */
  6780. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6781. if (!renderFunction) {
  6782. this._activeRenderLoops = [];
  6783. return;
  6784. }
  6785. var index = this._activeRenderLoops.indexOf(renderFunction);
  6786. if (index >= 0) {
  6787. this._activeRenderLoops.splice(index, 1);
  6788. }
  6789. };
  6790. Engine.prototype._renderLoop = function () {
  6791. var shouldRender = true;
  6792. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6793. shouldRender = false;
  6794. }
  6795. if (shouldRender) {
  6796. // Start new frame
  6797. this.beginFrame();
  6798. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6799. var renderFunction = this._activeRenderLoops[index];
  6800. renderFunction();
  6801. }
  6802. // Present
  6803. this.endFrame();
  6804. }
  6805. if (this._activeRenderLoops.length > 0) {
  6806. // Register new frame
  6807. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  6808. }
  6809. else {
  6810. this._renderingQueueLaunched = false;
  6811. }
  6812. };
  6813. /**
  6814. * Register and execute a render loop. The engine can have more than one render function.
  6815. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6816. * @example
  6817. * engine.runRenderLoop(function () {
  6818. * scene.render()
  6819. * })
  6820. */
  6821. Engine.prototype.runRenderLoop = function (renderFunction) {
  6822. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6823. return;
  6824. }
  6825. this._activeRenderLoops.push(renderFunction);
  6826. if (!this._renderingQueueLaunched) {
  6827. this._renderingQueueLaunched = true;
  6828. this._bindedRenderFunction = this._renderLoop.bind(this);
  6829. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6830. }
  6831. };
  6832. /**
  6833. * Toggle full screen mode.
  6834. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6835. * @param {any} options - an options object to be sent to the requestFullscreen function
  6836. */
  6837. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  6838. if (this.isFullscreen) {
  6839. BABYLON.Tools.ExitFullscreen();
  6840. }
  6841. else {
  6842. this._pointerLockRequested = requestPointerLock;
  6843. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  6844. }
  6845. };
  6846. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  6847. if (stencil === void 0) { stencil = false; }
  6848. this.applyStates();
  6849. var mode = 0;
  6850. if (backBuffer) {
  6851. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6852. mode |= this._gl.COLOR_BUFFER_BIT;
  6853. }
  6854. if (depth) {
  6855. this._gl.clearDepth(1.0);
  6856. mode |= this._gl.DEPTH_BUFFER_BIT;
  6857. }
  6858. if (stencil) {
  6859. this._gl.clearStencil(0);
  6860. mode |= this._gl.STENCIL_BUFFER_BIT;
  6861. }
  6862. this._gl.clear(mode);
  6863. };
  6864. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6865. var gl = this._gl;
  6866. // Save state
  6867. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6868. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6869. // Change state
  6870. gl.enable(gl.SCISSOR_TEST);
  6871. gl.scissor(x, y, width, height);
  6872. // Clear
  6873. this.clear(clearColor, true, true, true);
  6874. // Restore state
  6875. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6876. if (curScissor === true) {
  6877. gl.enable(gl.SCISSOR_TEST);
  6878. }
  6879. else {
  6880. gl.disable(gl.SCISSOR_TEST);
  6881. }
  6882. };
  6883. /**
  6884. * Set the WebGL's viewport
  6885. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6886. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6887. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6888. */
  6889. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6890. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6891. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6892. var x = viewport.x || 0;
  6893. var y = viewport.y || 0;
  6894. this._cachedViewport = viewport;
  6895. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6896. };
  6897. /**
  6898. * Directly set the WebGL Viewport
  6899. * The x, y, width & height are directly passed to the WebGL call
  6900. * @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.
  6901. */
  6902. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6903. var currentViewport = this._cachedViewport;
  6904. this._cachedViewport = null;
  6905. this._gl.viewport(x, y, width, height);
  6906. return currentViewport;
  6907. };
  6908. Engine.prototype.beginFrame = function () {
  6909. this._measureFps();
  6910. };
  6911. Engine.prototype.endFrame = function () {
  6912. //this.flushFramebuffer();
  6913. //submit frame to the vr device, if enabled
  6914. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  6915. this._vrDisplayEnabled.submitFrame();
  6916. }
  6917. };
  6918. /**
  6919. * resize the view according to the canvas' size.
  6920. * @example
  6921. * window.addEventListener("resize", function () {
  6922. * engine.resize();
  6923. * });
  6924. */
  6925. Engine.prototype.resize = function () {
  6926. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6927. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6928. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6929. for (var index = 0; index < this.scenes.length; index++) {
  6930. var scene = this.scenes[index];
  6931. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  6932. scene.debugLayer._syncPositions();
  6933. }
  6934. }
  6935. };
  6936. /**
  6937. * force a specific size of the canvas
  6938. * @param {number} width - the new canvas' width
  6939. * @param {number} height - the new canvas' height
  6940. */
  6941. Engine.prototype.setSize = function (width, height) {
  6942. this._renderingCanvas.width = width;
  6943. this._renderingCanvas.height = height;
  6944. for (var index = 0; index < this.scenes.length; index++) {
  6945. var scene = this.scenes[index];
  6946. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6947. var cam = scene.cameras[camIndex];
  6948. cam._currentRenderId = 0;
  6949. }
  6950. }
  6951. };
  6952. //WebVR functions
  6953. Engine.prototype.initWebVR = function () {
  6954. if (!this.vrDisplaysPromise) {
  6955. this._getVRDisplays();
  6956. }
  6957. };
  6958. Engine.prototype.enableVR = function (vrDevice) {
  6959. this._vrDisplayEnabled = vrDevice;
  6960. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  6961. };
  6962. Engine.prototype.disableVR = function () {
  6963. if (this._vrDisplayEnabled) {
  6964. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  6965. }
  6966. };
  6967. Engine.prototype._getVRDisplays = function () {
  6968. var _this = this;
  6969. var getWebVRDevices = function (devices) {
  6970. var size = devices.length;
  6971. var i = 0;
  6972. _this._vrDisplays = devices.filter(function (device) {
  6973. return devices[i] instanceof VRDisplay;
  6974. });
  6975. return _this._vrDisplays;
  6976. };
  6977. //using a key due to typescript
  6978. if (navigator.getVRDisplays) {
  6979. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  6980. }
  6981. };
  6982. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6983. this._currentRenderTarget = texture;
  6984. this.bindUnboundFramebuffer(texture._framebuffer);
  6985. var gl = this._gl;
  6986. if (texture.isCube) {
  6987. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6988. }
  6989. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6990. this.wipeCaches();
  6991. };
  6992. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  6993. if (this._currentFramebuffer !== framebuffer) {
  6994. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  6995. this._currentFramebuffer = framebuffer;
  6996. }
  6997. };
  6998. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6999. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7000. this._currentRenderTarget = null;
  7001. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7002. var gl = this._gl;
  7003. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7004. gl.generateMipmap(gl.TEXTURE_2D);
  7005. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7006. }
  7007. this.bindUnboundFramebuffer(null);
  7008. };
  7009. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7010. if (texture.generateMipMaps) {
  7011. var gl = this._gl;
  7012. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7013. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7014. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7015. }
  7016. };
  7017. Engine.prototype.flushFramebuffer = function () {
  7018. this._gl.flush();
  7019. };
  7020. Engine.prototype.restoreDefaultFramebuffer = function () {
  7021. this._currentRenderTarget = null;
  7022. this.bindUnboundFramebuffer(null);
  7023. this.setViewport(this._cachedViewport);
  7024. this.wipeCaches();
  7025. };
  7026. // VBOs
  7027. Engine.prototype._resetVertexBufferBinding = function () {
  7028. this.bindArrayBuffer(null);
  7029. this._cachedVertexBuffers = null;
  7030. };
  7031. Engine.prototype.createVertexBuffer = function (vertices) {
  7032. var vbo = this._gl.createBuffer();
  7033. this.bindArrayBuffer(vbo);
  7034. if (vertices instanceof Float32Array) {
  7035. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7036. }
  7037. else {
  7038. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7039. }
  7040. this._resetVertexBufferBinding();
  7041. vbo.references = 1;
  7042. return vbo;
  7043. };
  7044. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7045. var vbo = this._gl.createBuffer();
  7046. this.bindArrayBuffer(vbo);
  7047. if (vertices instanceof Float32Array) {
  7048. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7049. }
  7050. else {
  7051. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7052. }
  7053. this._resetVertexBufferBinding();
  7054. vbo.references = 1;
  7055. return vbo;
  7056. };
  7057. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7058. this.bindArrayBuffer(vertexBuffer);
  7059. if (offset === undefined) {
  7060. offset = 0;
  7061. }
  7062. if (count === undefined) {
  7063. if (vertices instanceof Float32Array) {
  7064. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7065. }
  7066. else {
  7067. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7068. }
  7069. }
  7070. else {
  7071. if (vertices instanceof Float32Array) {
  7072. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7073. }
  7074. else {
  7075. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7076. }
  7077. }
  7078. this._resetVertexBufferBinding();
  7079. };
  7080. Engine.prototype._resetIndexBufferBinding = function () {
  7081. this.bindIndexBuffer(null);
  7082. this._cachedIndexBuffer = null;
  7083. };
  7084. Engine.prototype.createIndexBuffer = function (indices) {
  7085. var vbo = this._gl.createBuffer();
  7086. this.bindIndexBuffer(vbo);
  7087. // Check for 32 bits indices
  7088. var arrayBuffer;
  7089. var need32Bits = false;
  7090. if (this._caps.uintIndices) {
  7091. for (var index = 0; index < indices.length; index++) {
  7092. if (indices[index] > 65535) {
  7093. need32Bits = true;
  7094. break;
  7095. }
  7096. }
  7097. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7098. }
  7099. else {
  7100. arrayBuffer = new Uint16Array(indices);
  7101. }
  7102. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7103. this._resetIndexBufferBinding();
  7104. vbo.references = 1;
  7105. vbo.is32Bits = need32Bits;
  7106. return vbo;
  7107. };
  7108. Engine.prototype.bindArrayBuffer = function (buffer) {
  7109. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7110. };
  7111. Engine.prototype.bindIndexBuffer = function (buffer) {
  7112. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7113. };
  7114. Engine.prototype.bindBuffer = function (buffer, target) {
  7115. if (this._currentBoundBuffer[target] !== buffer) {
  7116. this._gl.bindBuffer(target, buffer);
  7117. this._currentBoundBuffer[target] = buffer;
  7118. }
  7119. };
  7120. Engine.prototype.updateArrayBuffer = function (data) {
  7121. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7122. };
  7123. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7124. var pointer = this._currentBufferPointers[indx];
  7125. var changed = false;
  7126. if (!pointer) {
  7127. changed = true;
  7128. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7129. }
  7130. else {
  7131. if (pointer.buffer !== buffer) {
  7132. pointer.buffer = buffer;
  7133. changed = true;
  7134. }
  7135. if (pointer.size !== size) {
  7136. pointer.size = size;
  7137. changed = true;
  7138. }
  7139. if (pointer.type !== type) {
  7140. pointer.type = type;
  7141. changed = true;
  7142. }
  7143. if (pointer.normalized !== normalized) {
  7144. pointer.normalized = normalized;
  7145. changed = true;
  7146. }
  7147. if (pointer.stride !== stride) {
  7148. pointer.stride = stride;
  7149. changed = true;
  7150. }
  7151. if (pointer.offset !== offset) {
  7152. pointer.offset = offset;
  7153. changed = true;
  7154. }
  7155. }
  7156. if (changed) {
  7157. this.bindArrayBuffer(buffer);
  7158. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7159. }
  7160. };
  7161. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7162. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7163. this._cachedVertexBuffers = vertexBuffer;
  7164. this._cachedEffectForVertexBuffers = effect;
  7165. var attributesCount = effect.getAttributesCount();
  7166. var offset = 0;
  7167. for (var index = 0; index < attributesCount; index++) {
  7168. if (index < vertexDeclaration.length) {
  7169. var order = effect.getAttributeLocation(index);
  7170. if (order >= 0) {
  7171. if (!this._vertexAttribArraysEnabled[order]) {
  7172. this._gl.enableVertexAttribArray(order);
  7173. this._vertexAttribArraysEnabled[order] = true;
  7174. }
  7175. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7176. }
  7177. offset += vertexDeclaration[index] * 4;
  7178. }
  7179. else {
  7180. //disable effect attributes that have no data
  7181. var order = effect.getAttributeLocation(index);
  7182. if (this._vertexAttribArraysEnabled[order]) {
  7183. this._gl.disableVertexAttribArray(order);
  7184. this._vertexAttribArraysEnabled[order] = false;
  7185. }
  7186. }
  7187. }
  7188. }
  7189. if (this._cachedIndexBuffer !== indexBuffer) {
  7190. this._cachedIndexBuffer = indexBuffer;
  7191. this.bindIndexBuffer(indexBuffer);
  7192. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7193. }
  7194. };
  7195. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7196. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7197. this._cachedVertexBuffers = vertexBuffers;
  7198. this._cachedEffectForVertexBuffers = effect;
  7199. var attributes = effect.getAttributesNames();
  7200. for (var index = 0; index < attributes.length; index++) {
  7201. var order = effect.getAttributeLocation(index);
  7202. if (order >= 0) {
  7203. var vertexBuffer = vertexBuffers[attributes[index]];
  7204. if (!vertexBuffer) {
  7205. if (this._vertexAttribArraysEnabled[order]) {
  7206. this._gl.disableVertexAttribArray(order);
  7207. this._vertexAttribArraysEnabled[order] = false;
  7208. }
  7209. continue;
  7210. }
  7211. if (!this._vertexAttribArraysEnabled[order]) {
  7212. this._gl.enableVertexAttribArray(order);
  7213. this._vertexAttribArraysEnabled[order] = true;
  7214. }
  7215. var buffer = vertexBuffer.getBuffer();
  7216. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7217. if (vertexBuffer.getIsInstanced()) {
  7218. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7219. this._currentInstanceLocations.push(order);
  7220. this._currentInstanceBuffers.push(buffer);
  7221. }
  7222. }
  7223. }
  7224. }
  7225. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7226. this._cachedIndexBuffer = indexBuffer;
  7227. this.bindIndexBuffer(indexBuffer);
  7228. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7229. }
  7230. };
  7231. Engine.prototype.unbindInstanceAttributes = function () {
  7232. var boundBuffer;
  7233. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7234. var instancesBuffer = this._currentInstanceBuffers[i];
  7235. if (boundBuffer != instancesBuffer) {
  7236. boundBuffer = instancesBuffer;
  7237. this.bindArrayBuffer(instancesBuffer);
  7238. }
  7239. var offsetLocation = this._currentInstanceLocations[i];
  7240. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7241. }
  7242. this._currentInstanceBuffers.length = 0;
  7243. this._currentInstanceLocations.length = 0;
  7244. };
  7245. Engine.prototype._releaseBuffer = function (buffer) {
  7246. buffer.references--;
  7247. if (buffer.references === 0) {
  7248. this._gl.deleteBuffer(buffer);
  7249. return true;
  7250. }
  7251. return false;
  7252. };
  7253. Engine.prototype.createInstancesBuffer = function (capacity) {
  7254. var buffer = this._gl.createBuffer();
  7255. buffer.capacity = capacity;
  7256. this.bindArrayBuffer(buffer);
  7257. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7258. return buffer;
  7259. };
  7260. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7261. this._gl.deleteBuffer(buffer);
  7262. };
  7263. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7264. this.bindArrayBuffer(instancesBuffer);
  7265. if (data) {
  7266. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7267. }
  7268. if (offsetLocations[0].index !== undefined) {
  7269. var stride = 0;
  7270. for (var i = 0; i < offsetLocations.length; i++) {
  7271. var ai = offsetLocations[i];
  7272. stride += ai.attributeSize * 4;
  7273. }
  7274. for (var i = 0; i < offsetLocations.length; i++) {
  7275. var ai = offsetLocations[i];
  7276. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7277. this._gl.enableVertexAttribArray(ai.index);
  7278. this._vertexAttribArraysEnabled[ai.index] = true;
  7279. }
  7280. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7281. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7282. this._currentInstanceLocations.push(ai.index);
  7283. this._currentInstanceBuffers.push(instancesBuffer);
  7284. }
  7285. }
  7286. else {
  7287. for (var index = 0; index < 4; index++) {
  7288. var offsetLocation = offsetLocations[index];
  7289. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7290. this._gl.enableVertexAttribArray(offsetLocation);
  7291. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7292. }
  7293. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7294. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7295. this._currentInstanceLocations.push(offsetLocation);
  7296. this._currentInstanceBuffers.push(instancesBuffer);
  7297. }
  7298. }
  7299. };
  7300. Engine.prototype.applyStates = function () {
  7301. this._depthCullingState.apply(this._gl);
  7302. this._stencilState.apply(this._gl);
  7303. this._alphaState.apply(this._gl);
  7304. };
  7305. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7306. // Apply states
  7307. this.applyStates();
  7308. this._drawCalls.addCount(1, false);
  7309. // Render
  7310. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7311. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7312. if (instancesCount) {
  7313. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7314. return;
  7315. }
  7316. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7317. };
  7318. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7319. // Apply states
  7320. this.applyStates();
  7321. this._drawCalls.addCount(1, false);
  7322. if (instancesCount) {
  7323. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7324. return;
  7325. }
  7326. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7327. };
  7328. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7329. // Apply states
  7330. this.applyStates();
  7331. this._drawCalls.addCount(1, false);
  7332. if (instancesCount) {
  7333. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7334. return;
  7335. }
  7336. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7337. };
  7338. // Shaders
  7339. Engine.prototype._releaseEffect = function (effect) {
  7340. if (this._compiledEffects[effect._key]) {
  7341. delete this._compiledEffects[effect._key];
  7342. if (effect.getProgram()) {
  7343. this._gl.deleteProgram(effect.getProgram());
  7344. }
  7345. }
  7346. };
  7347. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7348. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7349. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7350. var name = vertex + "+" + fragment + "@" + defines;
  7351. if (this._compiledEffects[name]) {
  7352. return this._compiledEffects[name];
  7353. }
  7354. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7355. effect._key = name;
  7356. this._compiledEffects[name] = effect;
  7357. return effect;
  7358. };
  7359. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7360. if (uniformsNames === void 0) { uniformsNames = []; }
  7361. if (samplers === void 0) { samplers = []; }
  7362. if (defines === void 0) { defines = ""; }
  7363. return this.createEffect({
  7364. vertex: "particles",
  7365. fragmentElement: fragmentName
  7366. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7367. };
  7368. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7369. context = context || this._gl;
  7370. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7371. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7372. var shaderProgram = context.createProgram();
  7373. context.attachShader(shaderProgram, vertexShader);
  7374. context.attachShader(shaderProgram, fragmentShader);
  7375. context.linkProgram(shaderProgram);
  7376. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7377. if (!linked) {
  7378. var error = context.getProgramInfoLog(shaderProgram);
  7379. if (error) {
  7380. throw new Error(error);
  7381. }
  7382. }
  7383. context.deleteShader(vertexShader);
  7384. context.deleteShader(fragmentShader);
  7385. return shaderProgram;
  7386. };
  7387. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7388. var results = [];
  7389. for (var index = 0; index < uniformsNames.length; index++) {
  7390. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7391. }
  7392. return results;
  7393. };
  7394. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7395. var results = [];
  7396. for (var index = 0; index < attributesNames.length; index++) {
  7397. try {
  7398. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7399. }
  7400. catch (e) {
  7401. results.push(-1);
  7402. }
  7403. }
  7404. return results;
  7405. };
  7406. Engine.prototype.enableEffect = function (effect) {
  7407. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7408. if (effect && effect.onBind) {
  7409. effect.onBind(effect);
  7410. }
  7411. return;
  7412. }
  7413. // Use program
  7414. this.setProgram(effect.getProgram());
  7415. this._currentEffect = effect;
  7416. if (effect.onBind) {
  7417. effect.onBind(effect);
  7418. }
  7419. };
  7420. Engine.prototype.setIntArray = function (uniform, array) {
  7421. if (!uniform)
  7422. return;
  7423. this._gl.uniform1iv(uniform, array);
  7424. };
  7425. Engine.prototype.setIntArray2 = function (uniform, array) {
  7426. if (!uniform || array.length % 2 !== 0)
  7427. return;
  7428. this._gl.uniform2iv(uniform, array);
  7429. };
  7430. Engine.prototype.setIntArray3 = function (uniform, array) {
  7431. if (!uniform || array.length % 3 !== 0)
  7432. return;
  7433. this._gl.uniform3iv(uniform, array);
  7434. };
  7435. Engine.prototype.setIntArray4 = function (uniform, array) {
  7436. if (!uniform || array.length % 4 !== 0)
  7437. return;
  7438. this._gl.uniform4iv(uniform, array);
  7439. };
  7440. Engine.prototype.setFloatArray = function (uniform, array) {
  7441. if (!uniform)
  7442. return;
  7443. this._gl.uniform1fv(uniform, array);
  7444. };
  7445. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7446. if (!uniform || array.length % 2 !== 0)
  7447. return;
  7448. this._gl.uniform2fv(uniform, array);
  7449. };
  7450. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7451. if (!uniform || array.length % 3 !== 0)
  7452. return;
  7453. this._gl.uniform3fv(uniform, array);
  7454. };
  7455. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7456. if (!uniform || array.length % 4 !== 0)
  7457. return;
  7458. this._gl.uniform4fv(uniform, array);
  7459. };
  7460. Engine.prototype.setArray = function (uniform, array) {
  7461. if (!uniform)
  7462. return;
  7463. this._gl.uniform1fv(uniform, array);
  7464. };
  7465. Engine.prototype.setArray2 = function (uniform, array) {
  7466. if (!uniform || array.length % 2 !== 0)
  7467. return;
  7468. this._gl.uniform2fv(uniform, array);
  7469. };
  7470. Engine.prototype.setArray3 = function (uniform, array) {
  7471. if (!uniform || array.length % 3 !== 0)
  7472. return;
  7473. this._gl.uniform3fv(uniform, array);
  7474. };
  7475. Engine.prototype.setArray4 = function (uniform, array) {
  7476. if (!uniform || array.length % 4 !== 0)
  7477. return;
  7478. this._gl.uniform4fv(uniform, array);
  7479. };
  7480. Engine.prototype.setMatrices = function (uniform, matrices) {
  7481. if (!uniform)
  7482. return;
  7483. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7484. };
  7485. Engine.prototype.setMatrix = function (uniform, matrix) {
  7486. if (!uniform)
  7487. return;
  7488. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7489. };
  7490. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7491. if (!uniform)
  7492. return;
  7493. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7494. };
  7495. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7496. if (!uniform)
  7497. return;
  7498. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7499. };
  7500. Engine.prototype.setFloat = function (uniform, value) {
  7501. if (!uniform)
  7502. return;
  7503. this._gl.uniform1f(uniform, value);
  7504. };
  7505. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7506. if (!uniform)
  7507. return;
  7508. this._gl.uniform2f(uniform, x, y);
  7509. };
  7510. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7511. if (!uniform)
  7512. return;
  7513. this._gl.uniform3f(uniform, x, y, z);
  7514. };
  7515. Engine.prototype.setBool = function (uniform, bool) {
  7516. if (!uniform)
  7517. return;
  7518. this._gl.uniform1i(uniform, bool);
  7519. };
  7520. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7521. if (!uniform)
  7522. return;
  7523. this._gl.uniform4f(uniform, x, y, z, w);
  7524. };
  7525. Engine.prototype.setColor3 = function (uniform, color3) {
  7526. if (!uniform)
  7527. return;
  7528. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7529. };
  7530. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7531. if (!uniform)
  7532. return;
  7533. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7534. };
  7535. // States
  7536. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7537. if (zOffset === void 0) { zOffset = 0; }
  7538. if (reverseSide === void 0) { reverseSide = false; }
  7539. // Culling
  7540. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7541. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7542. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7543. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7544. if (culling) {
  7545. this._depthCullingState.cullFace = cullFace;
  7546. this._depthCullingState.cull = true;
  7547. }
  7548. else {
  7549. this._depthCullingState.cull = false;
  7550. }
  7551. }
  7552. // Z offset
  7553. this._depthCullingState.zOffset = zOffset;
  7554. };
  7555. Engine.prototype.setDepthBuffer = function (enable) {
  7556. this._depthCullingState.depthTest = enable;
  7557. };
  7558. Engine.prototype.getDepthWrite = function () {
  7559. return this._depthCullingState.depthMask;
  7560. };
  7561. Engine.prototype.setDepthWrite = function (enable) {
  7562. this._depthCullingState.depthMask = enable;
  7563. };
  7564. Engine.prototype.setColorWrite = function (enable) {
  7565. this._gl.colorMask(enable, enable, enable, enable);
  7566. };
  7567. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7568. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7569. if (this._alphaMode === mode) {
  7570. return;
  7571. }
  7572. switch (mode) {
  7573. case Engine.ALPHA_DISABLE:
  7574. this._alphaState.alphaBlend = false;
  7575. break;
  7576. case Engine.ALPHA_COMBINE:
  7577. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7578. this._alphaState.alphaBlend = true;
  7579. break;
  7580. case Engine.ALPHA_ONEONE:
  7581. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7582. this._alphaState.alphaBlend = true;
  7583. break;
  7584. case Engine.ALPHA_ADD:
  7585. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7586. this._alphaState.alphaBlend = true;
  7587. break;
  7588. case Engine.ALPHA_SUBTRACT:
  7589. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7590. this._alphaState.alphaBlend = true;
  7591. break;
  7592. case Engine.ALPHA_MULTIPLY:
  7593. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7594. this._alphaState.alphaBlend = true;
  7595. break;
  7596. case Engine.ALPHA_MAXIMIZED:
  7597. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7598. this._alphaState.alphaBlend = true;
  7599. break;
  7600. }
  7601. if (!noDepthWriteChange) {
  7602. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7603. }
  7604. this._alphaMode = mode;
  7605. };
  7606. Engine.prototype.getAlphaMode = function () {
  7607. return this._alphaMode;
  7608. };
  7609. Engine.prototype.setAlphaTesting = function (enable) {
  7610. this._alphaTest = enable;
  7611. };
  7612. Engine.prototype.getAlphaTesting = function () {
  7613. return this._alphaTest;
  7614. };
  7615. // Textures
  7616. Engine.prototype.wipeCaches = function () {
  7617. this.resetTextureCache();
  7618. this._currentEffect = null;
  7619. this._stencilState.reset();
  7620. this._depthCullingState.reset();
  7621. this.setDepthFunctionToLessOrEqual();
  7622. this._alphaState.reset();
  7623. this._cachedVertexBuffers = null;
  7624. this._cachedIndexBuffer = null;
  7625. this._cachedEffectForVertexBuffers = null;
  7626. };
  7627. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7628. var gl = this._gl;
  7629. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7630. var magFilter = gl.NEAREST;
  7631. var minFilter = gl.NEAREST;
  7632. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7633. magFilter = gl.LINEAR;
  7634. minFilter = gl.LINEAR;
  7635. }
  7636. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7637. magFilter = gl.LINEAR;
  7638. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7639. }
  7640. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7641. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7642. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7643. texture.samplingMode = samplingMode;
  7644. };
  7645. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7646. var _this = this;
  7647. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7648. if (onLoad === void 0) { onLoad = null; }
  7649. if (onError === void 0) { onError = null; }
  7650. if (buffer === void 0) { buffer = null; }
  7651. var texture = this._gl.createTexture();
  7652. var extension;
  7653. var fromData = false;
  7654. if (url.substr(0, 5) === "data:") {
  7655. fromData = true;
  7656. }
  7657. if (!fromData)
  7658. extension = url.substr(url.length - 4, 4).toLowerCase();
  7659. else {
  7660. var oldUrl = url;
  7661. fromData = oldUrl.split(':');
  7662. url = oldUrl;
  7663. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7664. }
  7665. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7666. var isTGA = (extension === ".tga");
  7667. scene._addPendingData(texture);
  7668. texture.url = url;
  7669. texture.noMipmap = noMipmap;
  7670. texture.references = 1;
  7671. texture.samplingMode = samplingMode;
  7672. texture.onLoadedCallbacks = [onLoad];
  7673. this._loadedTexturesCache.push(texture);
  7674. var onerror = function () {
  7675. scene._removePendingData(texture);
  7676. if (onError) {
  7677. onError();
  7678. }
  7679. };
  7680. var callback;
  7681. if (isTGA) {
  7682. callback = function (arrayBuffer) {
  7683. var data = new Uint8Array(arrayBuffer);
  7684. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7685. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7686. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7687. }, samplingMode);
  7688. };
  7689. if (!(fromData instanceof Array))
  7690. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7691. callback(arrayBuffer);
  7692. }, null, scene.database, true, onerror);
  7693. else
  7694. callback(buffer);
  7695. }
  7696. else if (isDDS) {
  7697. callback = function (data) {
  7698. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7699. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7700. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7701. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7702. }, samplingMode);
  7703. };
  7704. if (!(fromData instanceof Array))
  7705. BABYLON.Tools.LoadFile(url, function (data) {
  7706. callback(data);
  7707. }, null, scene.database, true, onerror);
  7708. else
  7709. callback(buffer);
  7710. }
  7711. else {
  7712. var onload = function (img) {
  7713. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7714. var isPot = (img.width === potWidth && img.height === potHeight);
  7715. if (!isPot) {
  7716. _this._prepareWorkingCanvas();
  7717. _this._workingCanvas.width = potWidth;
  7718. _this._workingCanvas.height = potHeight;
  7719. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7720. _this._workingContext.imageSmoothingEnabled = false;
  7721. _this._workingContext.mozImageSmoothingEnabled = false;
  7722. _this._workingContext.oImageSmoothingEnabled = false;
  7723. _this._workingContext.webkitImageSmoothingEnabled = false;
  7724. _this._workingContext.msImageSmoothingEnabled = false;
  7725. }
  7726. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7727. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7728. _this._workingContext.imageSmoothingEnabled = true;
  7729. _this._workingContext.mozImageSmoothingEnabled = true;
  7730. _this._workingContext.oImageSmoothingEnabled = true;
  7731. _this._workingContext.webkitImageSmoothingEnabled = true;
  7732. _this._workingContext.msImageSmoothingEnabled = true;
  7733. }
  7734. }
  7735. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7736. }, samplingMode);
  7737. };
  7738. if (!(fromData instanceof Array))
  7739. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7740. else
  7741. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7742. }
  7743. return texture;
  7744. };
  7745. Engine.prototype._getInternalFormat = function (format) {
  7746. var internalFormat = this._gl.RGBA;
  7747. switch (format) {
  7748. case Engine.TEXTUREFORMAT_ALPHA:
  7749. internalFormat = this._gl.ALPHA;
  7750. break;
  7751. case Engine.TEXTUREFORMAT_LUMINANCE:
  7752. internalFormat = this._gl.LUMINANCE;
  7753. break;
  7754. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7755. internalFormat = this._gl.LUMINANCE_ALPHA;
  7756. break;
  7757. case Engine.TEXTUREFORMAT_RGB:
  7758. internalFormat = this._gl.RGB;
  7759. break;
  7760. case Engine.TEXTUREFORMAT_RGBA:
  7761. internalFormat = this._gl.RGBA;
  7762. break;
  7763. }
  7764. return internalFormat;
  7765. };
  7766. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7767. if (compression === void 0) { compression = null; }
  7768. var internalFormat = this._getInternalFormat(format);
  7769. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7770. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7771. if (texture._width % 4 !== 0) {
  7772. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7773. }
  7774. if (compression) {
  7775. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7776. }
  7777. else {
  7778. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7779. }
  7780. if (texture.generateMipMaps) {
  7781. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7782. }
  7783. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7784. this.resetTextureCache();
  7785. texture.isReady = true;
  7786. };
  7787. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7788. if (compression === void 0) { compression = null; }
  7789. var texture = this._gl.createTexture();
  7790. texture._baseWidth = width;
  7791. texture._baseHeight = height;
  7792. texture._width = width;
  7793. texture._height = height;
  7794. texture.references = 1;
  7795. this.updateRawTexture(texture, data, format, invertY, compression);
  7796. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7797. // Filters
  7798. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7799. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7800. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7801. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7802. texture.samplingMode = samplingMode;
  7803. this._loadedTexturesCache.push(texture);
  7804. return texture;
  7805. };
  7806. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7807. var texture = this._gl.createTexture();
  7808. texture._baseWidth = width;
  7809. texture._baseHeight = height;
  7810. if (generateMipMaps) {
  7811. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7812. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7813. }
  7814. this.resetTextureCache();
  7815. texture._width = width;
  7816. texture._height = height;
  7817. texture.isReady = false;
  7818. texture.generateMipMaps = generateMipMaps;
  7819. texture.references = 1;
  7820. texture.samplingMode = samplingMode;
  7821. this.updateTextureSamplingMode(samplingMode, texture);
  7822. this._loadedTexturesCache.push(texture);
  7823. return texture;
  7824. };
  7825. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7826. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7827. if (texture.isCube) {
  7828. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7829. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7830. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7831. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7832. }
  7833. else {
  7834. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7835. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7836. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7837. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7838. }
  7839. };
  7840. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7841. if (premulAlpha === void 0) { premulAlpha = false; }
  7842. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7843. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7844. if (premulAlpha) {
  7845. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7846. }
  7847. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7848. if (texture.generateMipMaps) {
  7849. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7850. }
  7851. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7852. this.resetTextureCache();
  7853. texture.isReady = true;
  7854. };
  7855. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7856. if (texture._isDisabled) {
  7857. return;
  7858. }
  7859. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7860. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7861. try {
  7862. // Testing video texture support
  7863. if (this._videoTextureSupported === undefined) {
  7864. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7865. if (this._gl.getError() !== 0) {
  7866. this._videoTextureSupported = false;
  7867. }
  7868. else {
  7869. this._videoTextureSupported = true;
  7870. }
  7871. }
  7872. // Copy video through the current working canvas if video texture is not supported
  7873. if (!this._videoTextureSupported) {
  7874. if (!texture._workingCanvas) {
  7875. texture._workingCanvas = document.createElement("canvas");
  7876. texture._workingContext = texture._workingCanvas.getContext("2d");
  7877. texture._workingCanvas.width = texture._width;
  7878. texture._workingCanvas.height = texture._height;
  7879. }
  7880. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7881. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7882. }
  7883. else {
  7884. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7885. }
  7886. if (texture.generateMipMaps) {
  7887. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7888. }
  7889. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7890. this.resetTextureCache();
  7891. texture.isReady = true;
  7892. }
  7893. catch (ex) {
  7894. // Something unexpected
  7895. // Let's disable the texture
  7896. texture._isDisabled = true;
  7897. }
  7898. };
  7899. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7900. // old version had a "generateMipMaps" arg instead of options.
  7901. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7902. // in the same way, generateDepthBuffer is defaulted to true
  7903. var generateMipMaps = false;
  7904. var generateDepthBuffer = true;
  7905. var generateStencilBuffer = false;
  7906. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7907. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7908. if (options !== undefined) {
  7909. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7910. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7911. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  7912. type = options.type === undefined ? type : options.type;
  7913. if (options.samplingMode !== undefined) {
  7914. samplingMode = options.samplingMode;
  7915. }
  7916. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  7917. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7918. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7919. }
  7920. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  7921. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  7922. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7923. }
  7924. }
  7925. var gl = this._gl;
  7926. var texture = gl.createTexture();
  7927. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7928. var width = size.width || size;
  7929. var height = size.height || size;
  7930. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7931. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7932. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7933. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7934. }
  7935. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7937. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7938. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7939. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7940. var depthStencilBuffer;
  7941. // Create the depth/stencil buffer
  7942. if (generateStencilBuffer) {
  7943. depthStencilBuffer = gl.createRenderbuffer();
  7944. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7945. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  7946. }
  7947. else if (generateDepthBuffer) {
  7948. depthStencilBuffer = gl.createRenderbuffer();
  7949. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7950. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7951. }
  7952. // Create the framebuffer
  7953. var framebuffer = gl.createFramebuffer();
  7954. this.bindUnboundFramebuffer(framebuffer);
  7955. // Manage attachments
  7956. if (generateStencilBuffer) {
  7957. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7958. }
  7959. else if (generateDepthBuffer) {
  7960. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7961. }
  7962. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  7963. if (generateMipMaps) {
  7964. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7965. }
  7966. // Unbind
  7967. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7968. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7969. this.bindUnboundFramebuffer(null);
  7970. texture._framebuffer = framebuffer;
  7971. if (generateDepthBuffer) {
  7972. texture._depthBuffer = depthStencilBuffer;
  7973. }
  7974. texture._baseWidth = width;
  7975. texture._baseHeight = height;
  7976. texture._width = width;
  7977. texture._height = height;
  7978. texture.isReady = true;
  7979. texture.generateMipMaps = generateMipMaps;
  7980. texture.references = 1;
  7981. texture.samplingMode = samplingMode;
  7982. texture.type = type;
  7983. this.resetTextureCache();
  7984. this._loadedTexturesCache.push(texture);
  7985. return texture;
  7986. };
  7987. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7988. var gl = this._gl;
  7989. var texture = gl.createTexture();
  7990. var generateMipMaps = true;
  7991. var generateDepthBuffer = true;
  7992. var generateStencilBuffer = false;
  7993. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7994. if (options !== undefined) {
  7995. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7996. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7997. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  7998. if (options.samplingMode !== undefined) {
  7999. samplingMode = options.samplingMode;
  8000. }
  8001. }
  8002. texture.isCube = true;
  8003. texture.references = 1;
  8004. texture.generateMipMaps = generateMipMaps;
  8005. texture.references = 1;
  8006. texture.samplingMode = samplingMode;
  8007. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8008. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8009. for (var face = 0; face < 6; face++) {
  8010. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8011. }
  8012. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8013. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8014. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8015. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8016. // Create the depth buffer
  8017. var depthStencilBuffer;
  8018. // Create the depth/stencil buffer
  8019. if (generateStencilBuffer) {
  8020. depthStencilBuffer = gl.createRenderbuffer();
  8021. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8022. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8023. }
  8024. else if (generateDepthBuffer) {
  8025. depthStencilBuffer = gl.createRenderbuffer();
  8026. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8027. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8028. }
  8029. // Create the framebuffer
  8030. var framebuffer = gl.createFramebuffer();
  8031. this.bindUnboundFramebuffer(framebuffer);
  8032. // Manage attachments
  8033. if (generateStencilBuffer) {
  8034. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8035. }
  8036. else if (generateDepthBuffer) {
  8037. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8038. }
  8039. // Mipmaps
  8040. if (texture.generateMipMaps) {
  8041. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8042. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8043. }
  8044. // Unbind
  8045. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8046. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8047. this.bindUnboundFramebuffer(null);
  8048. texture._framebuffer = framebuffer;
  8049. if (generateDepthBuffer) {
  8050. texture._depthBuffer = depthStencilBuffer;
  8051. }
  8052. texture._width = size;
  8053. texture._height = size;
  8054. texture.isReady = true;
  8055. this.resetTextureCache();
  8056. this._loadedTexturesCache.push(texture);
  8057. return texture;
  8058. };
  8059. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  8060. var _this = this;
  8061. var gl = this._gl;
  8062. var texture = gl.createTexture();
  8063. texture.isCube = true;
  8064. texture.url = rootUrl;
  8065. texture.references = 1;
  8066. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8067. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8068. if (isDDS) {
  8069. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8070. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8071. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8072. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8073. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8074. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8075. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8076. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8077. }
  8078. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8080. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8081. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8082. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8083. _this.resetTextureCache();
  8084. texture._width = info.width;
  8085. texture._height = info.height;
  8086. texture.isReady = true;
  8087. }, null, null, true);
  8088. }
  8089. else {
  8090. cascadeLoad(rootUrl, scene, function (imgs) {
  8091. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8092. var height = width;
  8093. _this._prepareWorkingCanvas();
  8094. _this._workingCanvas.width = width;
  8095. _this._workingCanvas.height = height;
  8096. var faces = [
  8097. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8098. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8099. ];
  8100. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8101. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8102. for (var index = 0; index < faces.length; index++) {
  8103. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8104. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8105. }
  8106. if (!noMipmap) {
  8107. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8108. }
  8109. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8110. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8111. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8113. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8114. _this.resetTextureCache();
  8115. texture._width = width;
  8116. texture._height = height;
  8117. texture.isReady = true;
  8118. }, files);
  8119. }
  8120. this._loadedTexturesCache.push(texture);
  8121. return texture;
  8122. };
  8123. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8124. texture._width = width;
  8125. texture._height = height;
  8126. texture._size = width * height;
  8127. texture._baseWidth = width;
  8128. texture._baseHeight = height;
  8129. };
  8130. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8131. var _this = this;
  8132. var gl = this._gl;
  8133. var texture = gl.createTexture();
  8134. scene._addPendingData(texture);
  8135. texture.isCube = true;
  8136. texture.references = 1;
  8137. texture.url = url;
  8138. var internalFormat = this._getInternalFormat(format);
  8139. var textureType = gl.UNSIGNED_BYTE;
  8140. if (type === Engine.TEXTURETYPE_FLOAT) {
  8141. textureType = gl.FLOAT;
  8142. }
  8143. var width = size;
  8144. var height = width;
  8145. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8146. texture._width = width;
  8147. texture._height = height;
  8148. var onerror = function () {
  8149. scene._removePendingData(texture);
  8150. };
  8151. var internalCallback = function (data) {
  8152. var rgbeDataArrays = callback(data);
  8153. var facesIndex = [
  8154. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8155. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8156. ];
  8157. width = texture._width;
  8158. height = texture._height;
  8159. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8160. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8161. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8162. if (!noMipmap && isPot) {
  8163. if (mipmmapGenerator) {
  8164. var arrayTemp = [];
  8165. // Data are known to be in +X +Y +Z -X -Y -Z
  8166. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8167. arrayTemp.push(rgbeDataArrays[0]); // +X
  8168. arrayTemp.push(rgbeDataArrays[3]); // -X
  8169. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8170. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8171. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8172. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8173. var mipData = mipmmapGenerator(arrayTemp);
  8174. for (var level = 0; level < mipData.length; level++) {
  8175. var mipSize = width >> level;
  8176. // mipData is order in +X -X +Y -Y +Z -Z
  8177. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8178. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8179. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8180. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8181. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8182. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8183. }
  8184. }
  8185. else {
  8186. // Data are known to be in +X +Y +Z -X -Y -Z
  8187. for (var index = 0; index < facesIndex.length; index++) {
  8188. var faceData = rgbeDataArrays[index];
  8189. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8190. }
  8191. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8192. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8193. // By following the webgl standard changes from Revision 7, 2014/11/24
  8194. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8195. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8196. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8197. // Data are known to be in +X +Y +Z -X -Y -Z
  8198. for (var index = 0; index < facesIndex.length; index++) {
  8199. var faceData = rgbeDataArrays[index];
  8200. // Create a new RGBA Face.
  8201. var newFaceData = new Float32Array(width * height * 4);
  8202. for (var x = 0; x < width; x++) {
  8203. for (var y = 0; y < height; y++) {
  8204. var index_1 = (y * width + x) * 3;
  8205. var newIndex = (y * width + x) * 4;
  8206. // Map Old Value to new value.
  8207. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8208. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8209. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8210. // Add fully opaque alpha channel.
  8211. newFaceData[newIndex + 3] = 1;
  8212. }
  8213. }
  8214. // Reupload the face.
  8215. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8216. }
  8217. // Try to generate mipmap again.
  8218. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8219. }
  8220. }
  8221. }
  8222. else {
  8223. noMipmap = true;
  8224. }
  8225. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8228. }
  8229. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8230. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8231. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8232. }
  8233. else {
  8234. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8235. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8236. }
  8237. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8238. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8239. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8240. texture.isReady = true;
  8241. _this.resetTextureCache();
  8242. scene._removePendingData(texture);
  8243. };
  8244. BABYLON.Tools.LoadFile(url, function (data) {
  8245. internalCallback(data);
  8246. }, onerror, scene.database, true);
  8247. return texture;
  8248. };
  8249. ;
  8250. Engine.prototype._releaseTexture = function (texture) {
  8251. var gl = this._gl;
  8252. if (texture._framebuffer) {
  8253. gl.deleteFramebuffer(texture._framebuffer);
  8254. }
  8255. if (texture._depthBuffer) {
  8256. gl.deleteRenderbuffer(texture._depthBuffer);
  8257. }
  8258. gl.deleteTexture(texture);
  8259. // Unbind channels
  8260. this.unbindAllTextures();
  8261. var index = this._loadedTexturesCache.indexOf(texture);
  8262. if (index !== -1) {
  8263. this._loadedTexturesCache.splice(index, 1);
  8264. }
  8265. };
  8266. Engine.prototype.setProgram = function (program) {
  8267. if (this._currentProgram !== program) {
  8268. this._gl.useProgram(program);
  8269. this._currentProgram = program;
  8270. }
  8271. };
  8272. Engine.prototype.bindSamplers = function (effect) {
  8273. this.setProgram(effect.getProgram());
  8274. var samplers = effect.getSamplers();
  8275. for (var index = 0; index < samplers.length; index++) {
  8276. var uniform = effect.getUniform(samplers[index]);
  8277. this._gl.uniform1i(uniform, index);
  8278. }
  8279. this._currentEffect = null;
  8280. };
  8281. Engine.prototype.activateTexture = function (texture) {
  8282. if (this._activeTexture !== texture) {
  8283. this._gl.activeTexture(texture);
  8284. this._activeTexture = texture;
  8285. }
  8286. };
  8287. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8288. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8289. this._gl.bindTexture(target, texture);
  8290. this._activeTexturesCache[this._activeTexture] = texture;
  8291. }
  8292. };
  8293. Engine.prototype._bindTexture = function (channel, texture) {
  8294. if (channel < 0) {
  8295. return;
  8296. }
  8297. this.activateTexture(this._gl["TEXTURE" + channel]);
  8298. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8299. };
  8300. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8301. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8302. };
  8303. Engine.prototype.unbindAllTextures = function () {
  8304. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8305. this.activateTexture(this._gl["TEXTURE" + channel]);
  8306. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8307. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8308. }
  8309. };
  8310. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8311. if (channel < 0) {
  8312. return;
  8313. }
  8314. this._gl.uniform1i(uniform, channel);
  8315. this._setTexture(channel, texture);
  8316. };
  8317. Engine.prototype._setTexture = function (channel, texture) {
  8318. // Not ready?
  8319. if (!texture || !texture.isReady()) {
  8320. if (this._activeTexturesCache[channel] != null) {
  8321. this.activateTexture(this._gl["TEXTURE" + channel]);
  8322. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8323. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8324. }
  8325. return;
  8326. }
  8327. // Video
  8328. var alreadyActivated = false;
  8329. if (texture instanceof BABYLON.VideoTexture) {
  8330. this.activateTexture(this._gl["TEXTURE" + channel]);
  8331. alreadyActivated = true;
  8332. texture.update();
  8333. }
  8334. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8335. texture.delayLoad();
  8336. return;
  8337. }
  8338. var internalTexture = texture.getInternalTexture();
  8339. if (this._activeTexturesCache[channel] === internalTexture) {
  8340. return;
  8341. }
  8342. if (!alreadyActivated) {
  8343. this.activateTexture(this._gl["TEXTURE" + channel]);
  8344. }
  8345. if (internalTexture.isCube) {
  8346. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8347. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8348. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8349. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8350. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8351. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8352. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8353. }
  8354. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8355. }
  8356. else {
  8357. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8358. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8359. internalTexture._cachedWrapU = texture.wrapU;
  8360. switch (texture.wrapU) {
  8361. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8362. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8363. break;
  8364. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8365. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8366. break;
  8367. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8368. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8369. break;
  8370. }
  8371. }
  8372. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8373. internalTexture._cachedWrapV = texture.wrapV;
  8374. switch (texture.wrapV) {
  8375. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8376. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8377. break;
  8378. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8379. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8380. break;
  8381. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8382. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8383. break;
  8384. }
  8385. }
  8386. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8387. }
  8388. };
  8389. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8390. if (channel < 0) {
  8391. return;
  8392. }
  8393. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8394. this._textureUnits = new Int32Array(textures.length);
  8395. }
  8396. for (var i = 0; i < textures.length; i++) {
  8397. this._textureUnits[i] = channel + i;
  8398. }
  8399. this._gl.uniform1iv(uniform, this._textureUnits);
  8400. for (var index = 0; index < textures.length; index++) {
  8401. this._setTexture(channel + index, textures[index]);
  8402. }
  8403. };
  8404. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8405. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8406. var value = texture.anisotropicFilteringLevel;
  8407. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8408. value = 1;
  8409. }
  8410. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8411. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8412. texture._cachedAnisotropicFilteringLevel = value;
  8413. }
  8414. };
  8415. Engine.prototype.readPixels = function (x, y, width, height) {
  8416. var data = new Uint8Array(height * width * 4);
  8417. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8418. return data;
  8419. };
  8420. /**
  8421. * Add an externaly attached data from its key.
  8422. * This method call will fail and return false, if such key already exists.
  8423. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8424. * @param key the unique key that identifies the data
  8425. * @param data the data object to associate to the key for this Engine instance
  8426. * @return true if no such key were already present and the data was added successfully, false otherwise
  8427. */
  8428. Engine.prototype.addExternalData = function (key, data) {
  8429. return this._externalData.add(key, data);
  8430. };
  8431. /**
  8432. * Get an externaly attached data from its key
  8433. * @param key the unique key that identifies the data
  8434. * @return the associated data, if present (can be null), or undefined if not present
  8435. */
  8436. Engine.prototype.getExternalData = function (key) {
  8437. return this._externalData.get(key);
  8438. };
  8439. /**
  8440. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8441. * @param key the unique key that identifies the data
  8442. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8443. * @return the associated data, can be null if the factory returned null.
  8444. */
  8445. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8446. return this._externalData.getOrAddWithFactory(key, factory);
  8447. };
  8448. /**
  8449. * Remove an externaly attached data from the Engine instance
  8450. * @param key the unique key that identifies the data
  8451. * @return true if the data was successfully removed, false if it doesn't exist
  8452. */
  8453. Engine.prototype.removeExternalData = function (key) {
  8454. return this._externalData.remove(key);
  8455. };
  8456. Engine.prototype.releaseInternalTexture = function (texture) {
  8457. if (!texture) {
  8458. return;
  8459. }
  8460. texture.references--;
  8461. // Final reference ?
  8462. if (texture.references === 0) {
  8463. var texturesCache = this.getLoadedTexturesCache();
  8464. var index = texturesCache.indexOf(texture);
  8465. if (index > -1) {
  8466. texturesCache.splice(index, 1);
  8467. }
  8468. this._releaseTexture(texture);
  8469. }
  8470. };
  8471. // Dispose
  8472. Engine.prototype.dispose = function () {
  8473. this.hideLoadingUI();
  8474. this.stopRenderLoop();
  8475. // Release scenes
  8476. while (this.scenes.length) {
  8477. this.scenes[0].dispose();
  8478. }
  8479. // Release audio engine
  8480. Engine.audioEngine.dispose();
  8481. // Release effects
  8482. for (var name in this._compiledEffects) {
  8483. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8484. }
  8485. // Unbind
  8486. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8487. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8488. continue;
  8489. }
  8490. this._gl.disableVertexAttribArray(i);
  8491. }
  8492. this._gl = null;
  8493. //WebVR
  8494. this.disableVR();
  8495. // Events
  8496. window.removeEventListener("blur", this._onBlur);
  8497. window.removeEventListener("focus", this._onFocus);
  8498. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8499. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8500. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8501. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8502. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8503. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8504. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8505. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8506. };
  8507. // Loading screen
  8508. Engine.prototype.displayLoadingUI = function () {
  8509. this._loadingScreen.displayLoadingUI();
  8510. };
  8511. Engine.prototype.hideLoadingUI = function () {
  8512. this._loadingScreen.hideLoadingUI();
  8513. };
  8514. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8515. get: function () {
  8516. return this._loadingScreen;
  8517. },
  8518. set: function (loadingScreen) {
  8519. this._loadingScreen = loadingScreen;
  8520. },
  8521. enumerable: true,
  8522. configurable: true
  8523. });
  8524. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8525. set: function (text) {
  8526. this._loadingScreen.loadingUIText = text;
  8527. },
  8528. enumerable: true,
  8529. configurable: true
  8530. });
  8531. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8532. set: function (color) {
  8533. this._loadingScreen.loadingUIBackgroundColor = color;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Engine.prototype.attachContextLostEvent = function (callback) {
  8539. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8540. };
  8541. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8542. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8543. };
  8544. // FPS
  8545. Engine.prototype.getFps = function () {
  8546. return this.fps;
  8547. };
  8548. Engine.prototype.getDeltaTime = function () {
  8549. return this.deltaTime;
  8550. };
  8551. Engine.prototype._measureFps = function () {
  8552. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8553. var length = this.previousFramesDuration.length;
  8554. if (length >= 2) {
  8555. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8556. }
  8557. if (length >= this.fpsRange) {
  8558. if (length > this.fpsRange) {
  8559. this.previousFramesDuration.splice(0, 1);
  8560. length = this.previousFramesDuration.length;
  8561. }
  8562. var sum = 0;
  8563. for (var id = 0; id < length - 1; id++) {
  8564. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8565. }
  8566. this.fps = 1000.0 / (sum / (length - 1));
  8567. }
  8568. };
  8569. Engine.prototype._canRenderToFloatTexture = function () {
  8570. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8571. };
  8572. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8573. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8574. };
  8575. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8576. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8577. var tempcanvas = document.createElement("canvas");
  8578. tempcanvas.height = 16;
  8579. tempcanvas.width = 16;
  8580. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8581. // extension.
  8582. var ext = gl.getExtension(extension);
  8583. if (!ext) {
  8584. return false;
  8585. }
  8586. // setup GLSL program
  8587. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8588. 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 }";
  8589. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8590. gl.useProgram(program);
  8591. // look up where the vertex data needs to go.
  8592. var positionLocation = gl.getAttribLocation(program, "a_position");
  8593. var colorLoc = gl.getUniformLocation(program, "u_color");
  8594. // provide texture coordinates for the rectangle.
  8595. var positionBuffer = gl.createBuffer();
  8596. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8597. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8598. -1.0, -1.0,
  8599. 1.0, -1.0,
  8600. -1.0, 1.0,
  8601. -1.0, 1.0,
  8602. 1.0, -1.0,
  8603. 1.0, 1.0]), gl.STATIC_DRAW);
  8604. gl.enableVertexAttribArray(positionLocation);
  8605. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8606. var whiteTex = gl.createTexture();
  8607. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8608. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8609. var tex = gl.createTexture();
  8610. gl.bindTexture(gl.TEXTURE_2D, tex);
  8611. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8612. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8613. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8614. var fb = gl.createFramebuffer();
  8615. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8616. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8617. var cleanup = function () {
  8618. gl.deleteProgram(program);
  8619. gl.disableVertexAttribArray(positionLocation);
  8620. gl.deleteBuffer(positionBuffer);
  8621. gl.deleteFramebuffer(fb);
  8622. gl.deleteTexture(whiteTex);
  8623. gl.deleteTexture(tex);
  8624. };
  8625. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8626. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8627. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8628. cleanup();
  8629. return false;
  8630. }
  8631. // Draw the rectangle.
  8632. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8633. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8634. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8635. gl.bindTexture(gl.TEXTURE_2D, tex);
  8636. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8637. gl.clearColor(1, 0, 0, 1);
  8638. gl.clear(gl.COLOR_BUFFER_BIT);
  8639. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8640. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8641. var pixel = new Uint8Array(4);
  8642. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8643. if (pixel[0] !== 0 ||
  8644. pixel[1] < 248 ||
  8645. pixel[2] < 248 ||
  8646. pixel[3] < 254) {
  8647. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8648. cleanup();
  8649. return false;
  8650. }
  8651. // Succesfully rendered to "format" texture.
  8652. cleanup();
  8653. return true;
  8654. };
  8655. // Statics
  8656. Engine.isSupported = function () {
  8657. try {
  8658. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8659. if (navigator.isCocoonJS) {
  8660. return true;
  8661. }
  8662. var tempcanvas = document.createElement("canvas");
  8663. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8664. return gl != null && !!window.WebGLRenderingContext;
  8665. }
  8666. catch (e) {
  8667. return false;
  8668. }
  8669. };
  8670. // Const statics
  8671. Engine._ALPHA_DISABLE = 0;
  8672. Engine._ALPHA_ADD = 1;
  8673. Engine._ALPHA_COMBINE = 2;
  8674. Engine._ALPHA_SUBTRACT = 3;
  8675. Engine._ALPHA_MULTIPLY = 4;
  8676. Engine._ALPHA_MAXIMIZED = 5;
  8677. Engine._ALPHA_ONEONE = 6;
  8678. Engine._DELAYLOADSTATE_NONE = 0;
  8679. Engine._DELAYLOADSTATE_LOADED = 1;
  8680. Engine._DELAYLOADSTATE_LOADING = 2;
  8681. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8682. Engine._TEXTUREFORMAT_ALPHA = 0;
  8683. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8684. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8685. Engine._TEXTUREFORMAT_RGB = 4;
  8686. Engine._TEXTUREFORMAT_RGBA = 5;
  8687. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8688. Engine._TEXTURETYPE_FLOAT = 1;
  8689. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8690. // Updatable statics so stick with vars here
  8691. Engine.CollisionsEpsilon = 0.001;
  8692. Engine.CodeRepository = "src/";
  8693. Engine.ShadersRepository = "src/Shaders/";
  8694. return Engine;
  8695. })();
  8696. BABYLON.Engine = Engine;
  8697. })(BABYLON || (BABYLON = {}));
  8698. var BABYLON;
  8699. (function (BABYLON) {
  8700. /**
  8701. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8702. */
  8703. var Node = (function () {
  8704. /**
  8705. * @constructor
  8706. * @param {string} name - the name and id to be given to this node
  8707. * @param {BABYLON.Scene} the scene this node will be added to
  8708. */
  8709. function Node(name, scene) {
  8710. this.state = "";
  8711. this.animations = new Array();
  8712. this._ranges = {};
  8713. this._childrenFlag = -1;
  8714. this._isEnabled = true;
  8715. this._isReady = true;
  8716. this._currentRenderId = -1;
  8717. this._parentRenderId = -1;
  8718. this.name = name;
  8719. this.id = name;
  8720. this._scene = scene;
  8721. this._initCache();
  8722. }
  8723. Object.defineProperty(Node.prototype, "parent", {
  8724. get: function () {
  8725. return this._parentNode;
  8726. },
  8727. set: function (parent) {
  8728. if (this._parentNode === parent) {
  8729. return;
  8730. }
  8731. if (this._parentNode) {
  8732. var index = this._parentNode._children.indexOf(this);
  8733. if (index !== -1) {
  8734. this._parentNode._children.splice(index, 1);
  8735. }
  8736. }
  8737. this._parentNode = parent;
  8738. if (this._parentNode) {
  8739. if (!this._parentNode._children) {
  8740. this._parentNode._children = new Array();
  8741. }
  8742. this._parentNode._children.push(this);
  8743. }
  8744. },
  8745. enumerable: true,
  8746. configurable: true
  8747. });
  8748. Node.prototype.getScene = function () {
  8749. return this._scene;
  8750. };
  8751. Node.prototype.getEngine = function () {
  8752. return this._scene.getEngine();
  8753. };
  8754. // override it in derived class
  8755. Node.prototype.getWorldMatrix = function () {
  8756. return BABYLON.Matrix.Identity();
  8757. };
  8758. // override it in derived class if you add new variables to the cache
  8759. // and call the parent class method
  8760. Node.prototype._initCache = function () {
  8761. this._cache = {};
  8762. this._cache.parent = undefined;
  8763. };
  8764. Node.prototype.updateCache = function (force) {
  8765. if (!force && this.isSynchronized())
  8766. return;
  8767. this._cache.parent = this.parent;
  8768. this._updateCache();
  8769. };
  8770. // override it in derived class if you add new variables to the cache
  8771. // and call the parent class method if !ignoreParentClass
  8772. Node.prototype._updateCache = function (ignoreParentClass) {
  8773. };
  8774. // override it in derived class if you add new variables to the cache
  8775. Node.prototype._isSynchronized = function () {
  8776. return true;
  8777. };
  8778. Node.prototype._markSyncedWithParent = function () {
  8779. this._parentRenderId = this.parent._currentRenderId;
  8780. };
  8781. Node.prototype.isSynchronizedWithParent = function () {
  8782. if (!this.parent) {
  8783. return true;
  8784. }
  8785. if (this._parentRenderId !== this.parent._currentRenderId) {
  8786. return false;
  8787. }
  8788. return this.parent.isSynchronized();
  8789. };
  8790. Node.prototype.isSynchronized = function (updateCache) {
  8791. var check = this.hasNewParent();
  8792. check = check || !this.isSynchronizedWithParent();
  8793. check = check || !this._isSynchronized();
  8794. if (updateCache)
  8795. this.updateCache(true);
  8796. return !check;
  8797. };
  8798. Node.prototype.hasNewParent = function (update) {
  8799. if (this._cache.parent === this.parent)
  8800. return false;
  8801. if (update)
  8802. this._cache.parent = this.parent;
  8803. return true;
  8804. };
  8805. /**
  8806. * Is this node ready to be used/rendered
  8807. * @return {boolean} is it ready
  8808. */
  8809. Node.prototype.isReady = function () {
  8810. return this._isReady;
  8811. };
  8812. /**
  8813. * Is this node enabled.
  8814. * If the node has a parent and is enabled, the parent will be inspected as well.
  8815. * @return {boolean} whether this node (and its parent) is enabled.
  8816. * @see setEnabled
  8817. */
  8818. Node.prototype.isEnabled = function () {
  8819. if (!this._isEnabled) {
  8820. return false;
  8821. }
  8822. if (this.parent) {
  8823. return this.parent.isEnabled();
  8824. }
  8825. return true;
  8826. };
  8827. /**
  8828. * Set the enabled state of this node.
  8829. * @param {boolean} value - the new enabled state
  8830. * @see isEnabled
  8831. */
  8832. Node.prototype.setEnabled = function (value) {
  8833. this._isEnabled = value;
  8834. };
  8835. /**
  8836. * Is this node a descendant of the given node.
  8837. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  8838. * @param {BABYLON.Node} ancestor - The parent node to inspect
  8839. * @see parent
  8840. */
  8841. Node.prototype.isDescendantOf = function (ancestor) {
  8842. if (this.parent) {
  8843. if (this.parent === ancestor) {
  8844. return true;
  8845. }
  8846. return this.parent.isDescendantOf(ancestor);
  8847. }
  8848. return false;
  8849. };
  8850. /**
  8851. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  8852. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  8853. * @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.
  8854. * @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.
  8855. */
  8856. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  8857. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  8858. if (!this._children) {
  8859. return;
  8860. }
  8861. for (var index = 0; index < this._children.length; index++) {
  8862. var item = this._children[index];
  8863. if (!predicate || predicate(item)) {
  8864. results.push(item);
  8865. }
  8866. if (!directDescendantsOnly) {
  8867. item._getDescendants(results, false, predicate);
  8868. }
  8869. }
  8870. };
  8871. /**
  8872. * Will return all nodes that have this node as ascendant.
  8873. * @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.
  8874. * @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.
  8875. * @return {BABYLON.Node[]} all children nodes of all types.
  8876. */
  8877. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8878. var results = [];
  8879. this._getDescendants(results, directDescendantsOnly, predicate);
  8880. return results;
  8881. };
  8882. /**
  8883. * @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.
  8884. * @Deprecated, legacy support.
  8885. * use getDecendants instead.
  8886. */
  8887. Node.prototype.getChildren = function (predicate) {
  8888. return this.getDescendants(true, predicate);
  8889. };
  8890. /**
  8891. * Get all child-meshes of this node.
  8892. */
  8893. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8894. var results = [];
  8895. this._getDescendants(results, directDecendantsOnly, function (node) {
  8896. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8897. });
  8898. return results;
  8899. };
  8900. Node.prototype._setReady = function (state) {
  8901. if (state === this._isReady) {
  8902. return;
  8903. }
  8904. if (!state) {
  8905. this._isReady = false;
  8906. return;
  8907. }
  8908. this._isReady = true;
  8909. if (this.onReady) {
  8910. this.onReady(this);
  8911. }
  8912. };
  8913. Node.prototype.getAnimationByName = function (name) {
  8914. for (var i = 0; i < this.animations.length; i++) {
  8915. var animation = this.animations[i];
  8916. if (animation.name === name) {
  8917. return animation;
  8918. }
  8919. }
  8920. return null;
  8921. };
  8922. Node.prototype.createAnimationRange = function (name, from, to) {
  8923. // check name not already in use
  8924. if (!this._ranges[name]) {
  8925. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8926. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8927. if (this.animations[i]) {
  8928. this.animations[i].createRange(name, from, to);
  8929. }
  8930. }
  8931. }
  8932. };
  8933. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8934. if (deleteFrames === void 0) { deleteFrames = true; }
  8935. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8936. if (this.animations[i]) {
  8937. this.animations[i].deleteRange(name, deleteFrames);
  8938. }
  8939. }
  8940. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8941. };
  8942. Node.prototype.getAnimationRange = function (name) {
  8943. return this._ranges[name];
  8944. };
  8945. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8946. var range = this.getAnimationRange(name);
  8947. if (!range) {
  8948. return null;
  8949. }
  8950. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8951. };
  8952. Node.prototype.serializeAnimationRanges = function () {
  8953. var serializationRanges = [];
  8954. for (var name in this._ranges) {
  8955. var range = {};
  8956. range.name = name;
  8957. range.from = this._ranges[name].from;
  8958. range.to = this._ranges[name].to;
  8959. serializationRanges.push(range);
  8960. }
  8961. return serializationRanges;
  8962. };
  8963. Node.prototype.dispose = function () {
  8964. this.parent = null;
  8965. };
  8966. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8967. if (parsedNode.ranges) {
  8968. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8969. var data = parsedNode.ranges[index];
  8970. node.createAnimationRange(data.name, data.from, data.to);
  8971. }
  8972. }
  8973. };
  8974. __decorate([
  8975. BABYLON.serialize()
  8976. ], Node.prototype, "name", void 0);
  8977. __decorate([
  8978. BABYLON.serialize()
  8979. ], Node.prototype, "id", void 0);
  8980. __decorate([
  8981. BABYLON.serialize()
  8982. ], Node.prototype, "uniqueId", void 0);
  8983. __decorate([
  8984. BABYLON.serialize()
  8985. ], Node.prototype, "state", void 0);
  8986. return Node;
  8987. })();
  8988. BABYLON.Node = Node;
  8989. })(BABYLON || (BABYLON = {}));
  8990. var BABYLON;
  8991. (function (BABYLON) {
  8992. var FilesInput = (function () {
  8993. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8994. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8995. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8996. this._engine = p_engine;
  8997. this._canvas = p_canvas;
  8998. this._currentScene = p_scene;
  8999. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9000. this._progressCallback = p_progressCallback;
  9001. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9002. this._textureLoadingCallback = p_textureLoadingCallback;
  9003. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9004. }
  9005. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9006. var _this = this;
  9007. if (p_elementToMonitor) {
  9008. this._elementToMonitor = p_elementToMonitor;
  9009. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9010. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9011. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9012. }
  9013. };
  9014. FilesInput.prototype.renderFunction = function () {
  9015. if (this._additionnalRenderLoopLogicCallback) {
  9016. this._additionnalRenderLoopLogicCallback();
  9017. }
  9018. if (this._currentScene) {
  9019. if (this._textureLoadingCallback) {
  9020. var remaining = this._currentScene.getWaitingItemsCount();
  9021. if (remaining > 0) {
  9022. this._textureLoadingCallback(remaining);
  9023. }
  9024. }
  9025. this._currentScene.render();
  9026. }
  9027. };
  9028. FilesInput.prototype.drag = function (e) {
  9029. e.stopPropagation();
  9030. e.preventDefault();
  9031. };
  9032. FilesInput.prototype.drop = function (eventDrop) {
  9033. eventDrop.stopPropagation();
  9034. eventDrop.preventDefault();
  9035. this.loadFiles(eventDrop);
  9036. };
  9037. FilesInput.prototype.loadFiles = function (event) {
  9038. if (this._startingProcessingFilesCallback)
  9039. this._startingProcessingFilesCallback();
  9040. // Handling data transfer via drag'n'drop
  9041. if (event && event.dataTransfer && event.dataTransfer.files) {
  9042. this._filesToLoad = event.dataTransfer.files;
  9043. }
  9044. // Handling files from input files
  9045. if (event && event.target && event.target.files) {
  9046. this._filesToLoad = event.target.files;
  9047. }
  9048. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9049. for (var i = 0; i < this._filesToLoad.length; i++) {
  9050. switch (this._filesToLoad[i].type) {
  9051. case "image/jpeg":
  9052. case "image/png":
  9053. case "image/bmp":
  9054. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9055. break;
  9056. case "image/targa":
  9057. case "image/vnd.ms-dds":
  9058. case "audio/wav":
  9059. case "audio/x-wav":
  9060. case "audio/mp3":
  9061. case "audio/mpeg":
  9062. case "audio/mpeg3":
  9063. case "audio/x-mpeg-3":
  9064. case "audio/ogg":
  9065. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9066. break;
  9067. default:
  9068. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9069. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9070. }
  9071. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9072. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9073. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9074. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9075. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9076. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9077. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9078. this._sceneFileToLoad = this._filesToLoad[i];
  9079. }
  9080. break;
  9081. }
  9082. }
  9083. this.reload();
  9084. }
  9085. };
  9086. FilesInput.prototype.reload = function () {
  9087. var _this = this;
  9088. var that = this;
  9089. // If a ".babylon" file has been provided
  9090. if (this._sceneFileToLoad) {
  9091. if (this._currentScene) {
  9092. if (BABYLON.Tools.errorsCount > 0) {
  9093. BABYLON.Tools.ClearLogCache();
  9094. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9095. }
  9096. this._engine.stopRenderLoop();
  9097. this._currentScene.dispose();
  9098. }
  9099. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9100. that._currentScene = newScene;
  9101. // Wait for textures and shaders to be ready
  9102. that._currentScene.executeWhenReady(function () {
  9103. // Attach camera to canvas inputs
  9104. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9105. that._currentScene.createDefaultCameraOrLight();
  9106. }
  9107. that._currentScene.activeCamera.attachControl(that._canvas);
  9108. if (that._sceneLoadedCallback) {
  9109. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9110. }
  9111. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9112. });
  9113. }, function (progress) {
  9114. if (_this._progressCallback) {
  9115. _this._progressCallback(progress);
  9116. }
  9117. });
  9118. }
  9119. else {
  9120. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9121. }
  9122. };
  9123. FilesInput.FilesTextures = new Array();
  9124. FilesInput.FilesToLoad = new Array();
  9125. return FilesInput;
  9126. })();
  9127. BABYLON.FilesInput = FilesInput;
  9128. })(BABYLON || (BABYLON = {}));
  9129. var BABYLON;
  9130. (function (BABYLON) {
  9131. var IntersectionInfo = (function () {
  9132. function IntersectionInfo(bu, bv, distance) {
  9133. this.bu = bu;
  9134. this.bv = bv;
  9135. this.distance = distance;
  9136. this.faceId = 0;
  9137. this.subMeshId = 0;
  9138. }
  9139. return IntersectionInfo;
  9140. })();
  9141. BABYLON.IntersectionInfo = IntersectionInfo;
  9142. var PickingInfo = (function () {
  9143. function PickingInfo() {
  9144. this.hit = false;
  9145. this.distance = 0;
  9146. this.pickedPoint = null;
  9147. this.pickedMesh = null;
  9148. this.bu = 0;
  9149. this.bv = 0;
  9150. this.faceId = -1;
  9151. this.subMeshId = 0;
  9152. this.pickedSprite = null;
  9153. }
  9154. // Methods
  9155. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9156. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9157. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9158. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9159. return null;
  9160. }
  9161. var indices = this.pickedMesh.getIndices();
  9162. var result;
  9163. if (useVerticesNormals) {
  9164. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9165. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9166. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9167. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9168. normal0 = normal0.scale(this.bu);
  9169. normal1 = normal1.scale(this.bv);
  9170. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9171. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9172. }
  9173. else {
  9174. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9175. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9176. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9177. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9178. var p1p2 = vertex1.subtract(vertex2);
  9179. var p3p2 = vertex3.subtract(vertex2);
  9180. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9181. }
  9182. if (useWorldCoordinates) {
  9183. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9184. }
  9185. return BABYLON.Vector3.Normalize(result);
  9186. };
  9187. PickingInfo.prototype.getTextureCoordinates = function () {
  9188. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9189. return null;
  9190. }
  9191. var indices = this.pickedMesh.getIndices();
  9192. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9193. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9194. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9195. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9196. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9197. uv1 = uv1.scale(this.bu);
  9198. uv2 = uv2.scale(this.bv);
  9199. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9200. };
  9201. return PickingInfo;
  9202. })();
  9203. BABYLON.PickingInfo = PickingInfo;
  9204. })(BABYLON || (BABYLON = {}));
  9205. var BABYLON;
  9206. (function (BABYLON) {
  9207. var BoundingSphere = (function () {
  9208. function BoundingSphere(minimum, maximum) {
  9209. this.minimum = minimum;
  9210. this.maximum = maximum;
  9211. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9212. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9213. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9214. this.radius = distance * 0.5;
  9215. this.centerWorld = BABYLON.Vector3.Zero();
  9216. this._update(BABYLON.Matrix.Identity());
  9217. }
  9218. // Methods
  9219. BoundingSphere.prototype._update = function (world) {
  9220. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9221. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9222. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9223. };
  9224. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9225. for (var i = 0; i < 6; i++) {
  9226. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9227. return false;
  9228. }
  9229. return true;
  9230. };
  9231. BoundingSphere.prototype.intersectsPoint = function (point) {
  9232. var x = this.centerWorld.x - point.x;
  9233. var y = this.centerWorld.y - point.y;
  9234. var z = this.centerWorld.z - point.z;
  9235. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9236. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9237. return false;
  9238. return true;
  9239. };
  9240. // Statics
  9241. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9242. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9243. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9244. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9245. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9246. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9247. return false;
  9248. return true;
  9249. };
  9250. return BoundingSphere;
  9251. })();
  9252. BABYLON.BoundingSphere = BoundingSphere;
  9253. })(BABYLON || (BABYLON = {}));
  9254. var BABYLON;
  9255. (function (BABYLON) {
  9256. var BoundingBox = (function () {
  9257. function BoundingBox(minimum, maximum) {
  9258. this.minimum = minimum;
  9259. this.maximum = maximum;
  9260. this.vectors = new Array();
  9261. this.vectorsWorld = new Array();
  9262. // Bounding vectors
  9263. this.vectors.push(this.minimum.clone());
  9264. this.vectors.push(this.maximum.clone());
  9265. this.vectors.push(this.minimum.clone());
  9266. this.vectors[2].x = this.maximum.x;
  9267. this.vectors.push(this.minimum.clone());
  9268. this.vectors[3].y = this.maximum.y;
  9269. this.vectors.push(this.minimum.clone());
  9270. this.vectors[4].z = this.maximum.z;
  9271. this.vectors.push(this.maximum.clone());
  9272. this.vectors[5].z = this.minimum.z;
  9273. this.vectors.push(this.maximum.clone());
  9274. this.vectors[6].x = this.minimum.x;
  9275. this.vectors.push(this.maximum.clone());
  9276. this.vectors[7].y = this.minimum.y;
  9277. // OBB
  9278. this.center = this.maximum.add(this.minimum).scale(0.5);
  9279. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9280. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9281. // World
  9282. for (var index = 0; index < this.vectors.length; index++) {
  9283. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9284. }
  9285. this.minimumWorld = BABYLON.Vector3.Zero();
  9286. this.maximumWorld = BABYLON.Vector3.Zero();
  9287. this._update(BABYLON.Matrix.Identity());
  9288. }
  9289. // Methods
  9290. BoundingBox.prototype.getWorldMatrix = function () {
  9291. return this._worldMatrix;
  9292. };
  9293. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9294. this._worldMatrix.copyFrom(matrix);
  9295. return this;
  9296. };
  9297. BoundingBox.prototype._update = function (world) {
  9298. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9299. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9300. for (var index = 0; index < this.vectors.length; index++) {
  9301. var v = this.vectorsWorld[index];
  9302. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9303. if (v.x < this.minimumWorld.x)
  9304. this.minimumWorld.x = v.x;
  9305. if (v.y < this.minimumWorld.y)
  9306. this.minimumWorld.y = v.y;
  9307. if (v.z < this.minimumWorld.z)
  9308. this.minimumWorld.z = v.z;
  9309. if (v.x > this.maximumWorld.x)
  9310. this.maximumWorld.x = v.x;
  9311. if (v.y > this.maximumWorld.y)
  9312. this.maximumWorld.y = v.y;
  9313. if (v.z > this.maximumWorld.z)
  9314. this.maximumWorld.z = v.z;
  9315. }
  9316. // OBB
  9317. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9318. this.center.scaleInPlace(0.5);
  9319. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9320. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9321. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9322. this._worldMatrix = world;
  9323. };
  9324. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9325. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9326. };
  9327. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9328. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9329. };
  9330. BoundingBox.prototype.intersectsPoint = function (point) {
  9331. var delta = -BABYLON.Epsilon;
  9332. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9333. return false;
  9334. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9335. return false;
  9336. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9337. return false;
  9338. return true;
  9339. };
  9340. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9341. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9342. };
  9343. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9344. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9345. return false;
  9346. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9347. return false;
  9348. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9349. return false;
  9350. return true;
  9351. };
  9352. // Statics
  9353. BoundingBox.Intersects = function (box0, box1) {
  9354. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9355. return false;
  9356. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9357. return false;
  9358. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9359. return false;
  9360. return true;
  9361. };
  9362. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9363. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9364. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9365. return (num <= (sphereRadius * sphereRadius));
  9366. };
  9367. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9368. for (var p = 0; p < 6; p++) {
  9369. for (var i = 0; i < 8; i++) {
  9370. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9371. return false;
  9372. }
  9373. }
  9374. }
  9375. return true;
  9376. };
  9377. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9378. for (var p = 0; p < 6; p++) {
  9379. var inCount = 8;
  9380. for (var i = 0; i < 8; i++) {
  9381. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9382. --inCount;
  9383. }
  9384. else {
  9385. break;
  9386. }
  9387. }
  9388. if (inCount === 0)
  9389. return false;
  9390. }
  9391. return true;
  9392. };
  9393. return BoundingBox;
  9394. })();
  9395. BABYLON.BoundingBox = BoundingBox;
  9396. })(BABYLON || (BABYLON = {}));
  9397. var BABYLON;
  9398. (function (BABYLON) {
  9399. var computeBoxExtents = function (axis, box) {
  9400. var p = BABYLON.Vector3.Dot(box.center, axis);
  9401. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9402. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9403. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9404. var r = r0 + r1 + r2;
  9405. return {
  9406. min: p - r,
  9407. max: p + r
  9408. };
  9409. };
  9410. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9411. var axisOverlap = function (axis, box0, box1) {
  9412. var result0 = computeBoxExtents(axis, box0);
  9413. var result1 = computeBoxExtents(axis, box1);
  9414. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9415. };
  9416. var BoundingInfo = (function () {
  9417. function BoundingInfo(minimum, maximum) {
  9418. this.minimum = minimum;
  9419. this.maximum = maximum;
  9420. this._isLocked = false;
  9421. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9422. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9423. }
  9424. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9425. get: function () {
  9426. return this._isLocked;
  9427. },
  9428. set: function (value) {
  9429. this._isLocked = value;
  9430. },
  9431. enumerable: true,
  9432. configurable: true
  9433. });
  9434. // Methods
  9435. BoundingInfo.prototype.update = function (world) {
  9436. if (this._isLocked) {
  9437. return;
  9438. }
  9439. this.boundingBox._update(world);
  9440. this.boundingSphere._update(world);
  9441. };
  9442. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9443. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9444. return false;
  9445. return this.boundingBox.isInFrustum(frustumPlanes);
  9446. };
  9447. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9448. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9449. };
  9450. BoundingInfo.prototype._checkCollision = function (collider) {
  9451. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9452. };
  9453. BoundingInfo.prototype.intersectsPoint = function (point) {
  9454. if (!this.boundingSphere.centerWorld) {
  9455. return false;
  9456. }
  9457. if (!this.boundingSphere.intersectsPoint(point)) {
  9458. return false;
  9459. }
  9460. if (!this.boundingBox.intersectsPoint(point)) {
  9461. return false;
  9462. }
  9463. return true;
  9464. };
  9465. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9466. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9467. return false;
  9468. }
  9469. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9470. return false;
  9471. }
  9472. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9473. return false;
  9474. }
  9475. if (!precise) {
  9476. return true;
  9477. }
  9478. var box0 = this.boundingBox;
  9479. var box1 = boundingInfo.boundingBox;
  9480. if (!axisOverlap(box0.directions[0], box0, box1))
  9481. return false;
  9482. if (!axisOverlap(box0.directions[1], box0, box1))
  9483. return false;
  9484. if (!axisOverlap(box0.directions[2], box0, box1))
  9485. return false;
  9486. if (!axisOverlap(box1.directions[0], box0, box1))
  9487. return false;
  9488. if (!axisOverlap(box1.directions[1], box0, box1))
  9489. return false;
  9490. if (!axisOverlap(box1.directions[2], box0, box1))
  9491. return false;
  9492. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9493. return false;
  9494. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9495. return false;
  9496. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9497. return false;
  9498. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9499. return false;
  9500. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9501. return false;
  9502. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9503. return false;
  9504. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9505. return false;
  9506. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9507. return false;
  9508. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9509. return false;
  9510. return true;
  9511. };
  9512. return BoundingInfo;
  9513. })();
  9514. BABYLON.BoundingInfo = BoundingInfo;
  9515. })(BABYLON || (BABYLON = {}));
  9516. var BABYLON;
  9517. (function (BABYLON) {
  9518. var Ray = (function () {
  9519. function Ray(origin, direction, length) {
  9520. if (length === void 0) { length = Number.MAX_VALUE; }
  9521. this.origin = origin;
  9522. this.direction = direction;
  9523. this.length = length;
  9524. }
  9525. // Methods
  9526. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9527. var d = 0.0;
  9528. var maxValue = Number.MAX_VALUE;
  9529. var inv;
  9530. var min;
  9531. var max;
  9532. var temp;
  9533. if (Math.abs(this.direction.x) < 0.0000001) {
  9534. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9535. return false;
  9536. }
  9537. }
  9538. else {
  9539. inv = 1.0 / this.direction.x;
  9540. min = (minimum.x - this.origin.x) * inv;
  9541. max = (maximum.x - this.origin.x) * inv;
  9542. if (max === -Infinity) {
  9543. max = Infinity;
  9544. }
  9545. if (min > max) {
  9546. temp = min;
  9547. min = max;
  9548. max = temp;
  9549. }
  9550. d = Math.max(min, d);
  9551. maxValue = Math.min(max, maxValue);
  9552. if (d > maxValue) {
  9553. return false;
  9554. }
  9555. }
  9556. if (Math.abs(this.direction.y) < 0.0000001) {
  9557. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9558. return false;
  9559. }
  9560. }
  9561. else {
  9562. inv = 1.0 / this.direction.y;
  9563. min = (minimum.y - this.origin.y) * inv;
  9564. max = (maximum.y - this.origin.y) * inv;
  9565. if (max === -Infinity) {
  9566. max = Infinity;
  9567. }
  9568. if (min > max) {
  9569. temp = min;
  9570. min = max;
  9571. max = temp;
  9572. }
  9573. d = Math.max(min, d);
  9574. maxValue = Math.min(max, maxValue);
  9575. if (d > maxValue) {
  9576. return false;
  9577. }
  9578. }
  9579. if (Math.abs(this.direction.z) < 0.0000001) {
  9580. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9581. return false;
  9582. }
  9583. }
  9584. else {
  9585. inv = 1.0 / this.direction.z;
  9586. min = (minimum.z - this.origin.z) * inv;
  9587. max = (maximum.z - this.origin.z) * inv;
  9588. if (max === -Infinity) {
  9589. max = Infinity;
  9590. }
  9591. if (min > max) {
  9592. temp = min;
  9593. min = max;
  9594. max = temp;
  9595. }
  9596. d = Math.max(min, d);
  9597. maxValue = Math.min(max, maxValue);
  9598. if (d > maxValue) {
  9599. return false;
  9600. }
  9601. }
  9602. return true;
  9603. };
  9604. Ray.prototype.intersectsBox = function (box) {
  9605. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9606. };
  9607. Ray.prototype.intersectsSphere = function (sphere) {
  9608. var x = sphere.center.x - this.origin.x;
  9609. var y = sphere.center.y - this.origin.y;
  9610. var z = sphere.center.z - this.origin.z;
  9611. var pyth = (x * x) + (y * y) + (z * z);
  9612. var rr = sphere.radius * sphere.radius;
  9613. if (pyth <= rr) {
  9614. return true;
  9615. }
  9616. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9617. if (dot < 0.0) {
  9618. return false;
  9619. }
  9620. var temp = pyth - (dot * dot);
  9621. return temp <= rr;
  9622. };
  9623. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9624. if (!this._edge1) {
  9625. this._edge1 = BABYLON.Vector3.Zero();
  9626. this._edge2 = BABYLON.Vector3.Zero();
  9627. this._pvec = BABYLON.Vector3.Zero();
  9628. this._tvec = BABYLON.Vector3.Zero();
  9629. this._qvec = BABYLON.Vector3.Zero();
  9630. }
  9631. vertex1.subtractToRef(vertex0, this._edge1);
  9632. vertex2.subtractToRef(vertex0, this._edge2);
  9633. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9634. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9635. if (det === 0) {
  9636. return null;
  9637. }
  9638. var invdet = 1 / det;
  9639. this.origin.subtractToRef(vertex0, this._tvec);
  9640. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9641. if (bu < 0 || bu > 1.0) {
  9642. return null;
  9643. }
  9644. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9645. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9646. if (bv < 0 || bu + bv > 1.0) {
  9647. return null;
  9648. }
  9649. //check if the distance is longer than the predefined length.
  9650. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9651. if (distance > this.length) {
  9652. return null;
  9653. }
  9654. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9655. };
  9656. Ray.prototype.intersectsPlane = function (plane) {
  9657. var distance;
  9658. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9659. if (Math.abs(result1) < 9.99999997475243E-07) {
  9660. return null;
  9661. }
  9662. else {
  9663. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9664. distance = (-plane.d - result2) / result1;
  9665. if (distance < 0.0) {
  9666. if (distance < -9.99999997475243E-07) {
  9667. return null;
  9668. }
  9669. else {
  9670. return 0;
  9671. }
  9672. }
  9673. return distance;
  9674. }
  9675. };
  9676. /**
  9677. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9678. * @param sega the first point of the segment to test the intersection against
  9679. * @param segb the second point of the segment to test the intersection against
  9680. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9681. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9682. */
  9683. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9684. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9685. var u = segb.subtract(sega);
  9686. var v = rsegb.subtract(this.origin);
  9687. var w = sega.subtract(this.origin);
  9688. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9689. var b = BABYLON.Vector3.Dot(u, v);
  9690. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9691. var d = BABYLON.Vector3.Dot(u, w);
  9692. var e = BABYLON.Vector3.Dot(v, w);
  9693. var D = a * c - b * b; // always >= 0
  9694. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9695. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9696. // compute the line parameters of the two closest points
  9697. if (D < Ray.smallnum) {
  9698. sN = 0.0; // force using point P0 on segment S1
  9699. sD = 1.0; // to prevent possible division by 0.0 later
  9700. tN = e;
  9701. tD = c;
  9702. }
  9703. else {
  9704. sN = (b * e - c * d);
  9705. tN = (a * e - b * d);
  9706. if (sN < 0.0) {
  9707. sN = 0.0;
  9708. tN = e;
  9709. tD = c;
  9710. }
  9711. else if (sN > sD) {
  9712. sN = sD;
  9713. tN = e + b;
  9714. tD = c;
  9715. }
  9716. }
  9717. if (tN < 0.0) {
  9718. tN = 0.0;
  9719. // recompute sc for this edge
  9720. if (-d < 0.0) {
  9721. sN = 0.0;
  9722. }
  9723. else if (-d > a)
  9724. sN = sD;
  9725. else {
  9726. sN = -d;
  9727. sD = a;
  9728. }
  9729. }
  9730. else if (tN > tD) {
  9731. tN = tD;
  9732. // recompute sc for this edge
  9733. if ((-d + b) < 0.0) {
  9734. sN = 0;
  9735. }
  9736. else if ((-d + b) > a) {
  9737. sN = sD;
  9738. }
  9739. else {
  9740. sN = (-d + b);
  9741. sD = a;
  9742. }
  9743. }
  9744. // finally do the division to get sc and tc
  9745. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9746. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9747. // get the difference of the two closest points
  9748. var qtc = v.multiplyByFloats(tc, tc, tc);
  9749. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9750. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9751. if (isIntersected) {
  9752. return qtc.length();
  9753. }
  9754. return -1;
  9755. };
  9756. // Statics
  9757. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9758. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9759. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9760. var direction = end.subtract(start);
  9761. direction.normalize();
  9762. return new Ray(start, direction);
  9763. };
  9764. /**
  9765. * 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
  9766. * transformed to the given world matrix.
  9767. * @param origin The origin point
  9768. * @param end The end point
  9769. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9770. */
  9771. Ray.CreateNewFromTo = function (origin, end, world) {
  9772. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9773. var direction = end.subtract(origin);
  9774. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9775. direction.normalize();
  9776. return Ray.Transform(new Ray(origin, direction, length), world);
  9777. };
  9778. Ray.Transform = function (ray, matrix) {
  9779. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9780. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9781. newDirection.normalize();
  9782. return new Ray(newOrigin, newDirection, ray.length);
  9783. };
  9784. Ray.smallnum = 0.00000001;
  9785. Ray.rayl = 10e8;
  9786. return Ray;
  9787. })();
  9788. BABYLON.Ray = Ray;
  9789. })(BABYLON || (BABYLON = {}));
  9790. var BABYLON;
  9791. (function (BABYLON) {
  9792. var AbstractMesh = (function (_super) {
  9793. __extends(AbstractMesh, _super);
  9794. // Constructor
  9795. function AbstractMesh(name, scene) {
  9796. var _this = this;
  9797. _super.call(this, name, scene);
  9798. // Events
  9799. /**
  9800. * An event triggered when the mesh is disposed.
  9801. * @type {BABYLON.Observable}
  9802. */
  9803. this.onDisposeObservable = new BABYLON.Observable();
  9804. /**
  9805. * An event triggered when this mesh collides with another one
  9806. * @type {BABYLON.Observable}
  9807. */
  9808. this.onCollideObservable = new BABYLON.Observable();
  9809. /**
  9810. * An event triggered when the collision's position changes
  9811. * @type {BABYLON.Observable}
  9812. */
  9813. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9814. /**
  9815. * An event triggered after the world matrix is updated
  9816. * @type {BABYLON.Observable}
  9817. */
  9818. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9819. // Properties
  9820. this.definedFacingForward = true; // orientation for POV movement & rotation
  9821. this.position = new BABYLON.Vector3(0, 0, 0);
  9822. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9823. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9824. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9825. this.visibility = 1.0;
  9826. this.alphaIndex = Number.MAX_VALUE;
  9827. this.infiniteDistance = false;
  9828. this.isVisible = true;
  9829. this.isPickable = true;
  9830. this.showBoundingBox = false;
  9831. this.showSubMeshesBoundingBox = false;
  9832. this.isBlocker = false;
  9833. this.renderingGroupId = 0;
  9834. this.receiveShadows = false;
  9835. this.renderOutline = false;
  9836. this.outlineColor = BABYLON.Color3.Red();
  9837. this.outlineWidth = 0.02;
  9838. this.renderOverlay = false;
  9839. this.overlayColor = BABYLON.Color3.Red();
  9840. this.overlayAlpha = 0.5;
  9841. this.hasVertexAlpha = false;
  9842. this.useVertexColors = true;
  9843. this.applyFog = true;
  9844. this.computeBonesUsingShaders = true;
  9845. this.scalingDeterminant = 1;
  9846. this.numBoneInfluencers = 4;
  9847. this.useOctreeForRenderingSelection = true;
  9848. this.useOctreeForPicking = true;
  9849. this.useOctreeForCollisions = true;
  9850. this.layerMask = 0x0FFFFFFF;
  9851. this.alwaysSelectAsActiveMesh = false;
  9852. // Collisions
  9853. this._checkCollisions = false;
  9854. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9855. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9856. this._collider = new BABYLON.Collider();
  9857. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9858. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9859. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9860. // Edges
  9861. this.edgesWidth = 1;
  9862. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  9863. // Cache
  9864. this._localWorld = BABYLON.Matrix.Zero();
  9865. this._worldMatrix = BABYLON.Matrix.Zero();
  9866. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9867. this._absolutePosition = BABYLON.Vector3.Zero();
  9868. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9869. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9870. this._isDirty = false;
  9871. this._pivotMatrix = BABYLON.Matrix.Identity();
  9872. this._isDisposed = false;
  9873. this._renderId = 0;
  9874. this._intersectionsInProgress = new Array();
  9875. this._isWorldMatrixFrozen = false;
  9876. this._unIndexed = false;
  9877. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9878. if (collidedMesh === void 0) { collidedMesh = null; }
  9879. //TODO move this to the collision coordinator!
  9880. if (_this.getScene().workerCollisions)
  9881. newPosition.multiplyInPlace(_this._collider.radius);
  9882. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9883. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9884. _this.position.addInPlace(_this._diffPositionForCollisions);
  9885. }
  9886. if (collidedMesh) {
  9887. _this.onCollideObservable.notifyObservers(collidedMesh);
  9888. }
  9889. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9890. };
  9891. scene.addMesh(this);
  9892. }
  9893. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9894. get: function () {
  9895. return AbstractMesh._BILLBOARDMODE_NONE;
  9896. },
  9897. enumerable: true,
  9898. configurable: true
  9899. });
  9900. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9901. get: function () {
  9902. return AbstractMesh._BILLBOARDMODE_X;
  9903. },
  9904. enumerable: true,
  9905. configurable: true
  9906. });
  9907. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9908. get: function () {
  9909. return AbstractMesh._BILLBOARDMODE_Y;
  9910. },
  9911. enumerable: true,
  9912. configurable: true
  9913. });
  9914. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9915. get: function () {
  9916. return AbstractMesh._BILLBOARDMODE_Z;
  9917. },
  9918. enumerable: true,
  9919. configurable: true
  9920. });
  9921. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9922. get: function () {
  9923. return AbstractMesh._BILLBOARDMODE_ALL;
  9924. },
  9925. enumerable: true,
  9926. configurable: true
  9927. });
  9928. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9929. set: function (callback) {
  9930. if (this._onDisposeObserver) {
  9931. this.onDisposeObservable.remove(this._onDisposeObserver);
  9932. }
  9933. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9934. },
  9935. enumerable: true,
  9936. configurable: true
  9937. });
  9938. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9939. set: function (callback) {
  9940. if (this._onCollideObserver) {
  9941. this.onCollideObservable.remove(this._onCollideObserver);
  9942. }
  9943. this._onCollideObserver = this.onCollideObservable.add(callback);
  9944. },
  9945. enumerable: true,
  9946. configurable: true
  9947. });
  9948. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9949. set: function (callback) {
  9950. if (this._onCollisionPositionChangeObserver) {
  9951. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9952. }
  9953. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9954. },
  9955. enumerable: true,
  9956. configurable: true
  9957. });
  9958. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9959. get: function () {
  9960. return this._skeleton;
  9961. },
  9962. set: function (value) {
  9963. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9964. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9965. }
  9966. if (value && value.needInitialSkinMatrix) {
  9967. value._registerMeshWithPoseMatrix(this);
  9968. }
  9969. this._skeleton = value;
  9970. if (!this._skeleton) {
  9971. this._bonesTransformMatrices = null;
  9972. }
  9973. },
  9974. enumerable: true,
  9975. configurable: true
  9976. });
  9977. /**
  9978. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9979. */
  9980. AbstractMesh.prototype.toString = function (fullDetails) {
  9981. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9982. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9983. if (this._skeleton) {
  9984. ret += ", skeleton: " + this._skeleton.name;
  9985. }
  9986. if (fullDetails) {
  9987. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9988. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9989. }
  9990. return ret;
  9991. };
  9992. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9993. /**
  9994. * Getting the rotation object.
  9995. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9996. */
  9997. get: function () {
  9998. return this._rotation;
  9999. },
  10000. set: function (newRotation) {
  10001. this._rotation = newRotation;
  10002. },
  10003. enumerable: true,
  10004. configurable: true
  10005. });
  10006. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10007. get: function () {
  10008. return this._scaling;
  10009. },
  10010. set: function (newScaling) {
  10011. this._scaling = newScaling;
  10012. if (this.physicsImpostor) {
  10013. this.physicsImpostor.forceUpdate();
  10014. }
  10015. },
  10016. enumerable: true,
  10017. configurable: true
  10018. });
  10019. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10020. get: function () {
  10021. return this._rotationQuaternion;
  10022. },
  10023. set: function (quaternion) {
  10024. this._rotationQuaternion = quaternion;
  10025. //reset the rotation vector.
  10026. if (quaternion && this.rotation.length()) {
  10027. this.rotation.copyFromFloats(0, 0, 0);
  10028. }
  10029. },
  10030. enumerable: true,
  10031. configurable: true
  10032. });
  10033. // Methods
  10034. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10035. this._poseMatrix.copyFrom(matrix);
  10036. };
  10037. AbstractMesh.prototype.getPoseMatrix = function () {
  10038. return this._poseMatrix;
  10039. };
  10040. AbstractMesh.prototype.disableEdgesRendering = function () {
  10041. if (this._edgesRenderer !== undefined) {
  10042. this._edgesRenderer.dispose();
  10043. this._edgesRenderer = undefined;
  10044. }
  10045. };
  10046. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10047. if (epsilon === void 0) { epsilon = 0.95; }
  10048. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10049. this.disableEdgesRendering();
  10050. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10051. };
  10052. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10053. get: function () {
  10054. return false;
  10055. },
  10056. enumerable: true,
  10057. configurable: true
  10058. });
  10059. AbstractMesh.prototype.getLOD = function (camera) {
  10060. return this;
  10061. };
  10062. AbstractMesh.prototype.getTotalVertices = function () {
  10063. return 0;
  10064. };
  10065. AbstractMesh.prototype.getIndices = function () {
  10066. return null;
  10067. };
  10068. AbstractMesh.prototype.getVerticesData = function (kind) {
  10069. return null;
  10070. };
  10071. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10072. return false;
  10073. };
  10074. AbstractMesh.prototype.getBoundingInfo = function () {
  10075. if (this._masterMesh) {
  10076. return this._masterMesh.getBoundingInfo();
  10077. }
  10078. if (!this._boundingInfo) {
  10079. this._updateBoundingInfo();
  10080. }
  10081. return this._boundingInfo;
  10082. };
  10083. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10084. this._boundingInfo = boundingInfo;
  10085. };
  10086. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10087. get: function () {
  10088. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10089. },
  10090. enumerable: true,
  10091. configurable: true
  10092. });
  10093. AbstractMesh.prototype._preActivate = function () {
  10094. };
  10095. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10096. };
  10097. AbstractMesh.prototype._activate = function (renderId) {
  10098. this._renderId = renderId;
  10099. };
  10100. AbstractMesh.prototype.getWorldMatrix = function () {
  10101. if (this._masterMesh) {
  10102. return this._masterMesh.getWorldMatrix();
  10103. }
  10104. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10105. this.computeWorldMatrix();
  10106. }
  10107. return this._worldMatrix;
  10108. };
  10109. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10110. get: function () {
  10111. return this._worldMatrix;
  10112. },
  10113. enumerable: true,
  10114. configurable: true
  10115. });
  10116. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10117. get: function () {
  10118. return this._absolutePosition;
  10119. },
  10120. enumerable: true,
  10121. configurable: true
  10122. });
  10123. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10124. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10125. this.computeWorldMatrix(true);
  10126. this._isWorldMatrixFrozen = true;
  10127. };
  10128. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10129. this._isWorldMatrixFrozen = false;
  10130. this.computeWorldMatrix(true);
  10131. };
  10132. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10133. get: function () {
  10134. return this._isWorldMatrixFrozen;
  10135. },
  10136. enumerable: true,
  10137. configurable: true
  10138. });
  10139. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10140. axis.normalize();
  10141. if (!this.rotationQuaternion) {
  10142. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10143. this.rotation = BABYLON.Vector3.Zero();
  10144. }
  10145. var rotationQuaternion;
  10146. if (!space || space === BABYLON.Space.LOCAL) {
  10147. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10148. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10149. }
  10150. else {
  10151. if (this.parent) {
  10152. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10153. invertParentWorldMatrix.invert();
  10154. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10155. }
  10156. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10157. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10158. }
  10159. };
  10160. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10161. var displacementVector = axis.scale(distance);
  10162. if (!space || space === BABYLON.Space.LOCAL) {
  10163. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10164. this.setPositionWithLocalVector(tempV3);
  10165. }
  10166. else {
  10167. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10168. }
  10169. };
  10170. AbstractMesh.prototype.getAbsolutePosition = function () {
  10171. this.computeWorldMatrix();
  10172. return this._absolutePosition;
  10173. };
  10174. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10175. if (!absolutePosition) {
  10176. return;
  10177. }
  10178. var absolutePositionX;
  10179. var absolutePositionY;
  10180. var absolutePositionZ;
  10181. if (absolutePosition.x === undefined) {
  10182. if (arguments.length < 3) {
  10183. return;
  10184. }
  10185. absolutePositionX = arguments[0];
  10186. absolutePositionY = arguments[1];
  10187. absolutePositionZ = arguments[2];
  10188. }
  10189. else {
  10190. absolutePositionX = absolutePosition.x;
  10191. absolutePositionY = absolutePosition.y;
  10192. absolutePositionZ = absolutePosition.z;
  10193. }
  10194. if (this.parent) {
  10195. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10196. invertParentWorldMatrix.invert();
  10197. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10198. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10199. }
  10200. else {
  10201. this.position.x = absolutePositionX;
  10202. this.position.y = absolutePositionY;
  10203. this.position.z = absolutePositionZ;
  10204. }
  10205. };
  10206. // ================================== Point of View Movement =================================
  10207. /**
  10208. * Perform relative position change from the point of view of behind the front of the mesh.
  10209. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10210. * Supports definition of mesh facing forward or backward.
  10211. * @param {number} amountRight
  10212. * @param {number} amountUp
  10213. * @param {number} amountForward
  10214. */
  10215. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10216. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10217. };
  10218. /**
  10219. * Calculate relative position change from the point of view of behind the front of the mesh.
  10220. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10221. * Supports definition of mesh facing forward or backward.
  10222. * @param {number} amountRight
  10223. * @param {number} amountUp
  10224. * @param {number} amountForward
  10225. */
  10226. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10227. var rotMatrix = new BABYLON.Matrix();
  10228. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10229. rotQuaternion.toRotationMatrix(rotMatrix);
  10230. var translationDelta = BABYLON.Vector3.Zero();
  10231. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10232. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10233. return translationDelta;
  10234. };
  10235. // ================================== Point of View Rotation =================================
  10236. /**
  10237. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10238. * Supports definition of mesh facing forward or backward.
  10239. * @param {number} flipBack
  10240. * @param {number} twirlClockwise
  10241. * @param {number} tiltRight
  10242. */
  10243. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10244. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10245. };
  10246. /**
  10247. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10248. * Supports definition of mesh facing forward or backward.
  10249. * @param {number} flipBack
  10250. * @param {number} twirlClockwise
  10251. * @param {number} tiltRight
  10252. */
  10253. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10254. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10255. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10256. };
  10257. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10258. this._pivotMatrix = matrix;
  10259. this._cache.pivotMatrixUpdated = true;
  10260. };
  10261. AbstractMesh.prototype.getPivotMatrix = function () {
  10262. return this._pivotMatrix;
  10263. };
  10264. AbstractMesh.prototype._isSynchronized = function () {
  10265. if (this._isDirty) {
  10266. return false;
  10267. }
  10268. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10269. return false;
  10270. if (this._cache.pivotMatrixUpdated) {
  10271. return false;
  10272. }
  10273. if (this.infiniteDistance) {
  10274. return false;
  10275. }
  10276. if (!this._cache.position.equals(this.position))
  10277. return false;
  10278. if (this.rotationQuaternion) {
  10279. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10280. return false;
  10281. }
  10282. if (!this._cache.rotation.equals(this.rotation))
  10283. return false;
  10284. if (!this._cache.scaling.equals(this.scaling))
  10285. return false;
  10286. return true;
  10287. };
  10288. AbstractMesh.prototype._initCache = function () {
  10289. _super.prototype._initCache.call(this);
  10290. this._cache.localMatrixUpdated = false;
  10291. this._cache.position = BABYLON.Vector3.Zero();
  10292. this._cache.scaling = BABYLON.Vector3.Zero();
  10293. this._cache.rotation = BABYLON.Vector3.Zero();
  10294. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10295. this._cache.billboardMode = -1;
  10296. };
  10297. AbstractMesh.prototype.markAsDirty = function (property) {
  10298. if (property === "rotation") {
  10299. this.rotationQuaternion = null;
  10300. }
  10301. this._currentRenderId = Number.MAX_VALUE;
  10302. this._isDirty = true;
  10303. };
  10304. AbstractMesh.prototype._updateBoundingInfo = function () {
  10305. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10306. this._boundingInfo.update(this.worldMatrixFromCache);
  10307. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10308. };
  10309. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10310. if (!this.subMeshes) {
  10311. return;
  10312. }
  10313. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10314. var subMesh = this.subMeshes[subIndex];
  10315. if (!subMesh.IsGlobal) {
  10316. subMesh.updateBoundingInfo(matrix);
  10317. }
  10318. }
  10319. };
  10320. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10321. if (this._isWorldMatrixFrozen) {
  10322. return this._worldMatrix;
  10323. }
  10324. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10325. this._currentRenderId = this.getScene().getRenderId();
  10326. return this._worldMatrix;
  10327. }
  10328. this._cache.position.copyFrom(this.position);
  10329. this._cache.scaling.copyFrom(this.scaling);
  10330. this._cache.pivotMatrixUpdated = false;
  10331. this._cache.billboardMode = this.billboardMode;
  10332. this._currentRenderId = this.getScene().getRenderId();
  10333. this._isDirty = false;
  10334. // Scaling
  10335. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10336. // Rotation
  10337. //rotate, if quaternion is set and rotation was used
  10338. if (this.rotationQuaternion) {
  10339. var len = this.rotation.length();
  10340. if (len) {
  10341. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10342. this.rotation.copyFromFloats(0, 0, 0);
  10343. }
  10344. }
  10345. if (this.rotationQuaternion) {
  10346. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10347. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10348. }
  10349. else {
  10350. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10351. this._cache.rotation.copyFrom(this.rotation);
  10352. }
  10353. // Translation
  10354. if (this.infiniteDistance && !this.parent) {
  10355. var camera = this.getScene().activeCamera;
  10356. if (camera) {
  10357. var cameraWorldMatrix = camera.getWorldMatrix();
  10358. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10359. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10360. }
  10361. }
  10362. else {
  10363. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10364. }
  10365. // Composing transformations
  10366. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10367. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10368. // Billboarding
  10369. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10370. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10371. var localPosition = BABYLON.Tmp.Vector3[0];
  10372. if (this.parent && this.parent.getWorldMatrix) {
  10373. this._markSyncedWithParent();
  10374. var parentMatrix;
  10375. if (this._meshToBoneReferal) {
  10376. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10377. parentMatrix = BABYLON.Tmp.Matrix[6];
  10378. }
  10379. else {
  10380. parentMatrix = this.parent.getWorldMatrix();
  10381. }
  10382. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10383. localPosition = BABYLON.Tmp.Vector3[1];
  10384. }
  10385. var zero = this.getScene().activeCamera.globalPosition.clone();
  10386. if (this.parent && this.parent.position) {
  10387. localPosition.addInPlace(this.parent.position);
  10388. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10389. }
  10390. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10391. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10392. zero.x = localPosition.x + BABYLON.Epsilon;
  10393. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10394. zero.y = localPosition.y + BABYLON.Epsilon;
  10395. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10396. zero.z = localPosition.z + BABYLON.Epsilon;
  10397. }
  10398. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10399. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10400. BABYLON.Tmp.Matrix[3].invert();
  10401. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10402. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10403. }
  10404. // Local world
  10405. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10406. // Parent
  10407. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10408. this._markSyncedWithParent();
  10409. if (this._meshToBoneReferal) {
  10410. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10411. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10412. }
  10413. else {
  10414. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10415. }
  10416. }
  10417. else {
  10418. this._worldMatrix.copyFrom(this._localWorld);
  10419. }
  10420. // Bounding info
  10421. this._updateBoundingInfo();
  10422. // Absolute position
  10423. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10424. // Callbacks
  10425. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10426. if (!this._poseMatrix) {
  10427. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10428. }
  10429. return this._worldMatrix;
  10430. };
  10431. /**
  10432. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10433. * @param func: callback function to add
  10434. */
  10435. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10436. this.onAfterWorldMatrixUpdateObservable.add(func);
  10437. };
  10438. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10439. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10440. };
  10441. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10442. this.computeWorldMatrix();
  10443. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10444. };
  10445. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10446. this.computeWorldMatrix();
  10447. var invLocalWorldMatrix = this._localWorld.clone();
  10448. invLocalWorldMatrix.invert();
  10449. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10450. };
  10451. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10452. this.computeWorldMatrix(true);
  10453. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10454. };
  10455. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10456. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10457. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10458. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10459. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10460. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10461. /// <returns>Mesh oriented towards targetMesh</returns>
  10462. if (yawCor === void 0) { yawCor = 0; }
  10463. if (pitchCor === void 0) { pitchCor = 0; }
  10464. if (rollCor === void 0) { rollCor = 0; }
  10465. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10466. var dv = AbstractMesh._lookAtVectorCache;
  10467. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10468. targetPoint.subtractToRef(pos, dv);
  10469. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10470. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10471. var pitch = Math.atan2(dv.y, len);
  10472. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10473. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10474. };
  10475. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10476. this._meshToBoneReferal = affectedMesh;
  10477. this.parent = bone;
  10478. if (bone.getWorldMatrix().determinant() < 0) {
  10479. this.scalingDeterminant *= -1;
  10480. }
  10481. };
  10482. AbstractMesh.prototype.detachFromBone = function () {
  10483. if (this.parent.getWorldMatrix().determinant() < 0) {
  10484. this.scalingDeterminant *= -1;
  10485. }
  10486. this._meshToBoneReferal = null;
  10487. this.parent = null;
  10488. };
  10489. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10490. return this._boundingInfo.isInFrustum(frustumPlanes);
  10491. };
  10492. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10493. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10494. ;
  10495. };
  10496. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10497. if (!this._boundingInfo || !mesh._boundingInfo) {
  10498. return false;
  10499. }
  10500. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10501. };
  10502. AbstractMesh.prototype.intersectsPoint = function (point) {
  10503. if (!this._boundingInfo) {
  10504. return false;
  10505. }
  10506. return this._boundingInfo.intersectsPoint(point);
  10507. };
  10508. // Physics
  10509. /**
  10510. * @Deprecated. Use new PhysicsImpostor instead.
  10511. * */
  10512. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10513. //legacy support
  10514. if (impostor.impostor) {
  10515. options = impostor;
  10516. impostor = impostor.impostor;
  10517. }
  10518. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10519. return this.physicsImpostor.physicsBody;
  10520. };
  10521. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10522. return this.physicsImpostor;
  10523. };
  10524. /**
  10525. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10526. */
  10527. AbstractMesh.prototype.getPhysicsMass = function () {
  10528. return this.physicsImpostor.getParam("mass");
  10529. };
  10530. /**
  10531. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10532. */
  10533. AbstractMesh.prototype.getPhysicsFriction = function () {
  10534. return this.physicsImpostor.getParam("friction");
  10535. };
  10536. /**
  10537. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10538. */
  10539. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10540. return this.physicsImpostor.getParam("restitution");
  10541. };
  10542. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10543. if (!camera) {
  10544. camera = this.getScene().activeCamera;
  10545. }
  10546. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10547. };
  10548. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10549. if (!camera) {
  10550. camera = this.getScene().activeCamera;
  10551. }
  10552. return this.absolutePosition.subtract(camera.position).length();
  10553. };
  10554. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10555. if (!this.physicsImpostor) {
  10556. return;
  10557. }
  10558. this.physicsImpostor.applyImpulse(force, contactPoint);
  10559. };
  10560. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10561. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10562. return;
  10563. }
  10564. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10565. mainPivot: pivot1,
  10566. connectedPivot: pivot2,
  10567. nativeParams: options
  10568. });
  10569. };
  10570. /**
  10571. * @Deprecated
  10572. */
  10573. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10574. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10575. this.updatePhysicsBody();
  10576. };
  10577. /**
  10578. * @Deprecated
  10579. * Calling this function is not needed anymore.
  10580. * The physics engine takes care of transofmration automatically.
  10581. */
  10582. AbstractMesh.prototype.updatePhysicsBody = function () {
  10583. //Unneeded
  10584. };
  10585. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10586. // Collisions
  10587. get: function () {
  10588. return this._checkCollisions;
  10589. },
  10590. set: function (collisionEnabled) {
  10591. this._checkCollisions = collisionEnabled;
  10592. if (this.getScene().workerCollisions) {
  10593. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10594. }
  10595. },
  10596. enumerable: true,
  10597. configurable: true
  10598. });
  10599. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10600. var globalPosition = this.getAbsolutePosition();
  10601. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10602. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10603. this._collider.radius = this.ellipsoid;
  10604. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10605. };
  10606. // Submeshes octree
  10607. /**
  10608. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10609. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10610. */
  10611. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10612. if (maxCapacity === void 0) { maxCapacity = 64; }
  10613. if (maxDepth === void 0) { maxDepth = 2; }
  10614. if (!this._submeshesOctree) {
  10615. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10616. }
  10617. this.computeWorldMatrix(true);
  10618. // Update octree
  10619. var bbox = this.getBoundingInfo().boundingBox;
  10620. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10621. return this._submeshesOctree;
  10622. };
  10623. // Collisions
  10624. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10625. this._generatePointsArray();
  10626. // Transformation
  10627. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10628. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10629. subMesh._lastColliderWorldVertices = [];
  10630. subMesh._trianglePlanes = [];
  10631. var start = subMesh.verticesStart;
  10632. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10633. for (var i = start; i < end; i++) {
  10634. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10635. }
  10636. }
  10637. // Collide
  10638. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10639. if (collider.collisionFound) {
  10640. collider.collidedMesh = this;
  10641. }
  10642. };
  10643. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10644. var subMeshes;
  10645. var len;
  10646. // Octrees
  10647. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10648. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10649. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10650. len = intersections.length;
  10651. subMeshes = intersections.data;
  10652. }
  10653. else {
  10654. subMeshes = this.subMeshes;
  10655. len = subMeshes.length;
  10656. }
  10657. for (var index = 0; index < len; index++) {
  10658. var subMesh = subMeshes[index];
  10659. // Bounding test
  10660. if (len > 1 && !subMesh._checkCollision(collider))
  10661. continue;
  10662. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10663. }
  10664. };
  10665. AbstractMesh.prototype._checkCollision = function (collider) {
  10666. // Bounding box test
  10667. if (!this._boundingInfo._checkCollision(collider))
  10668. return;
  10669. // Transformation matrix
  10670. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10671. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10672. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10673. };
  10674. // Picking
  10675. AbstractMesh.prototype._generatePointsArray = function () {
  10676. return false;
  10677. };
  10678. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10679. var pickingInfo = new BABYLON.PickingInfo();
  10680. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10681. return pickingInfo;
  10682. }
  10683. if (!this._generatePointsArray()) {
  10684. return pickingInfo;
  10685. }
  10686. var intersectInfo = null;
  10687. // Octrees
  10688. var subMeshes;
  10689. var len;
  10690. if (this._submeshesOctree && this.useOctreeForPicking) {
  10691. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10692. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10693. len = intersections.length;
  10694. subMeshes = intersections.data;
  10695. }
  10696. else {
  10697. subMeshes = this.subMeshes;
  10698. len = subMeshes.length;
  10699. }
  10700. for (var index = 0; index < len; index++) {
  10701. var subMesh = subMeshes[index];
  10702. // Bounding test
  10703. if (len > 1 && !subMesh.canIntersects(ray))
  10704. continue;
  10705. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10706. if (currentIntersectInfo) {
  10707. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10708. intersectInfo = currentIntersectInfo;
  10709. intersectInfo.subMeshId = index;
  10710. if (fastCheck) {
  10711. break;
  10712. }
  10713. }
  10714. }
  10715. }
  10716. if (intersectInfo) {
  10717. // Get picked point
  10718. var world = this.getWorldMatrix();
  10719. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10720. var direction = ray.direction.clone();
  10721. direction = direction.scale(intersectInfo.distance);
  10722. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10723. var pickedPoint = worldOrigin.add(worldDirection);
  10724. // Return result
  10725. pickingInfo.hit = true;
  10726. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10727. pickingInfo.pickedPoint = pickedPoint;
  10728. pickingInfo.pickedMesh = this;
  10729. pickingInfo.bu = intersectInfo.bu;
  10730. pickingInfo.bv = intersectInfo.bv;
  10731. pickingInfo.faceId = intersectInfo.faceId;
  10732. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10733. return pickingInfo;
  10734. }
  10735. return pickingInfo;
  10736. };
  10737. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10738. return null;
  10739. };
  10740. AbstractMesh.prototype.releaseSubMeshes = function () {
  10741. if (this.subMeshes) {
  10742. while (this.subMeshes.length) {
  10743. this.subMeshes[0].dispose();
  10744. }
  10745. }
  10746. else {
  10747. this.subMeshes = new Array();
  10748. }
  10749. };
  10750. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10751. var _this = this;
  10752. var index;
  10753. // Action manager
  10754. if (this.actionManager) {
  10755. this.actionManager.dispose();
  10756. this.actionManager = null;
  10757. }
  10758. // Skeleton
  10759. this.skeleton = null;
  10760. // Animations
  10761. this.getScene().stopAnimation(this);
  10762. // Physics
  10763. if (this.physicsImpostor) {
  10764. this.physicsImpostor.dispose();
  10765. }
  10766. // Intersections in progress
  10767. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10768. var other = this._intersectionsInProgress[index];
  10769. var pos = other._intersectionsInProgress.indexOf(this);
  10770. other._intersectionsInProgress.splice(pos, 1);
  10771. }
  10772. this._intersectionsInProgress = [];
  10773. // Lights
  10774. var lights = this.getScene().lights;
  10775. lights.forEach(function (light) {
  10776. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10777. if (meshIndex !== -1) {
  10778. light.includedOnlyMeshes.splice(meshIndex, 1);
  10779. }
  10780. meshIndex = light.excludedMeshes.indexOf(_this);
  10781. if (meshIndex !== -1) {
  10782. light.excludedMeshes.splice(meshIndex, 1);
  10783. }
  10784. // Shadow generators
  10785. var generator = light.getShadowGenerator();
  10786. if (generator) {
  10787. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  10788. if (meshIndex !== -1) {
  10789. generator.getShadowMap().renderList.splice(meshIndex, 1);
  10790. }
  10791. }
  10792. });
  10793. // Edges
  10794. if (this._edgesRenderer) {
  10795. this._edgesRenderer.dispose();
  10796. this._edgesRenderer = null;
  10797. }
  10798. // SubMeshes
  10799. this.releaseSubMeshes();
  10800. // Remove from scene
  10801. this.getScene().removeMesh(this);
  10802. if (!doNotRecurse) {
  10803. // Particles
  10804. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10805. if (this.getScene().particleSystems[index].emitter === this) {
  10806. this.getScene().particleSystems[index].dispose();
  10807. index--;
  10808. }
  10809. }
  10810. // Children
  10811. var objects = this.getDescendants(true);
  10812. for (index = 0; index < objects.length; index++) {
  10813. objects[index].dispose();
  10814. }
  10815. }
  10816. else {
  10817. var childMeshes = this.getChildMeshes(true);
  10818. for (index = 0; index < childMeshes.length; index++) {
  10819. var child = childMeshes[index];
  10820. child.parent = null;
  10821. child.computeWorldMatrix(true);
  10822. }
  10823. }
  10824. _super.prototype.dispose.call(this);
  10825. this.onAfterWorldMatrixUpdateObservable.clear();
  10826. this.onCollideObservable.clear();
  10827. this.onCollisionPositionChangeObservable.clear();
  10828. this._isDisposed = true;
  10829. // Callback
  10830. this.onDisposeObservable.notifyObservers(this);
  10831. this.onDisposeObservable.clear();
  10832. };
  10833. // Statics
  10834. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10835. AbstractMesh._BILLBOARDMODE_X = 1;
  10836. AbstractMesh._BILLBOARDMODE_Y = 2;
  10837. AbstractMesh._BILLBOARDMODE_Z = 4;
  10838. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10839. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  10840. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  10841. return AbstractMesh;
  10842. })(BABYLON.Node);
  10843. BABYLON.AbstractMesh = AbstractMesh;
  10844. })(BABYLON || (BABYLON = {}));
  10845. var BABYLON;
  10846. (function (BABYLON) {
  10847. var Light = (function (_super) {
  10848. __extends(Light, _super);
  10849. function Light(name, scene) {
  10850. _super.call(this, name, scene);
  10851. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  10852. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  10853. this.intensity = 1.0;
  10854. this.range = Number.MAX_VALUE;
  10855. this.includeOnlyWithLayerMask = 0;
  10856. this.includedOnlyMeshes = new Array();
  10857. this.excludedMeshes = new Array();
  10858. this.excludeWithLayerMask = 0;
  10859. this.lightmapMode = 0;
  10860. // PBR Properties.
  10861. this.radius = 0.00001;
  10862. this._excludedMeshesIds = new Array();
  10863. this._includedOnlyMeshesIds = new Array();
  10864. scene.addLight(this);
  10865. }
  10866. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  10867. /**
  10868. * If every light affecting the material is in this lightmapMode,
  10869. * material.lightmapTexture adds or multiplies
  10870. * (depends on material.useLightmapAsShadowmap)
  10871. * after every other light calculations.
  10872. */
  10873. get: function () {
  10874. return Light._LIGHTMAP_DEFAULT;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  10880. /**
  10881. * material.lightmapTexture as only diffuse lighting from this light
  10882. * adds pnly specular lighting from this light
  10883. * adds dynamic shadows
  10884. */
  10885. get: function () {
  10886. return Light._LIGHTMAP_SPECULAR;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  10892. /**
  10893. * material.lightmapTexture as only lighting
  10894. * no light calculation from this light
  10895. * only adds dynamic shadows from this light
  10896. */
  10897. get: function () {
  10898. return Light._LIGHTMAP_SHADOWSONLY;
  10899. },
  10900. enumerable: true,
  10901. configurable: true
  10902. });
  10903. /**
  10904. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10905. */
  10906. Light.prototype.toString = function (fullDetails) {
  10907. var ret = "Name: " + this.name;
  10908. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  10909. if (this.animations) {
  10910. for (var i = 0; i < this.animations.length; i++) {
  10911. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10912. }
  10913. }
  10914. if (fullDetails) {
  10915. }
  10916. return ret;
  10917. };
  10918. Light.prototype.getShadowGenerator = function () {
  10919. return this._shadowGenerator;
  10920. };
  10921. Light.prototype.getAbsolutePosition = function () {
  10922. return BABYLON.Vector3.Zero();
  10923. };
  10924. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10925. };
  10926. Light.prototype._getWorldMatrix = function () {
  10927. return BABYLON.Matrix.Identity();
  10928. };
  10929. Light.prototype.canAffectMesh = function (mesh) {
  10930. if (!mesh) {
  10931. return true;
  10932. }
  10933. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10934. return false;
  10935. }
  10936. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10937. return false;
  10938. }
  10939. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10940. return false;
  10941. }
  10942. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10943. return false;
  10944. }
  10945. return true;
  10946. };
  10947. Light.prototype.getWorldMatrix = function () {
  10948. this._currentRenderId = this.getScene().getRenderId();
  10949. var worldMatrix = this._getWorldMatrix();
  10950. if (this.parent && this.parent.getWorldMatrix) {
  10951. if (!this._parentedWorldMatrix) {
  10952. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10953. }
  10954. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10955. this._markSyncedWithParent();
  10956. return this._parentedWorldMatrix;
  10957. }
  10958. return worldMatrix;
  10959. };
  10960. Light.prototype.dispose = function () {
  10961. if (this._shadowGenerator) {
  10962. this._shadowGenerator.dispose();
  10963. this._shadowGenerator = null;
  10964. }
  10965. // Animations
  10966. this.getScene().stopAnimation(this);
  10967. // Remove from scene
  10968. this.getScene().removeLight(this);
  10969. _super.prototype.dispose.call(this);
  10970. };
  10971. Light.prototype.getTypeID = function () {
  10972. return 0;
  10973. };
  10974. Light.prototype.clone = function (name) {
  10975. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10976. };
  10977. Light.prototype.serialize = function () {
  10978. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10979. // Type
  10980. serializationObject.type = this.getTypeID();
  10981. // Parent
  10982. if (this.parent) {
  10983. serializationObject.parentId = this.parent.id;
  10984. }
  10985. // Inclusion / exclusions
  10986. if (this.excludedMeshes.length > 0) {
  10987. serializationObject.excludedMeshesIds = [];
  10988. this.excludedMeshes.forEach(function (mesh) {
  10989. serializationObject.excludedMeshesIds.push(mesh.id);
  10990. });
  10991. }
  10992. if (this.includedOnlyMeshes.length > 0) {
  10993. serializationObject.includedOnlyMeshesIds = [];
  10994. this.includedOnlyMeshes.forEach(function (mesh) {
  10995. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10996. });
  10997. }
  10998. // Animations
  10999. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11000. serializationObject.ranges = this.serializeAnimationRanges();
  11001. return serializationObject;
  11002. };
  11003. Light.GetConstructorFromName = function (type, name, scene) {
  11004. switch (type) {
  11005. case 0:
  11006. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11007. case 1:
  11008. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11009. case 2:
  11010. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11011. case 3:
  11012. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11013. }
  11014. };
  11015. Light.Parse = function (parsedLight, scene) {
  11016. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11017. // Inclusion / exclusions
  11018. if (parsedLight.excludedMeshesIds) {
  11019. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11020. }
  11021. if (parsedLight.includedOnlyMeshesIds) {
  11022. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11023. }
  11024. // Parent
  11025. if (parsedLight.parentId) {
  11026. light._waitingParentId = parsedLight.parentId;
  11027. }
  11028. // Animations
  11029. if (parsedLight.animations) {
  11030. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11031. var parsedAnimation = parsedLight.animations[animationIndex];
  11032. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11033. }
  11034. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11035. }
  11036. if (parsedLight.autoAnimate) {
  11037. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11038. }
  11039. return light;
  11040. };
  11041. //lightmapMode Consts
  11042. Light._LIGHTMAP_DEFAULT = 0;
  11043. Light._LIGHTMAP_SPECULAR = 1;
  11044. Light._LIGHTMAP_SHADOWSONLY = 2;
  11045. __decorate([
  11046. BABYLON.serializeAsColor3()
  11047. ], Light.prototype, "diffuse", void 0);
  11048. __decorate([
  11049. BABYLON.serializeAsColor3()
  11050. ], Light.prototype, "specular", void 0);
  11051. __decorate([
  11052. BABYLON.serialize()
  11053. ], Light.prototype, "intensity", void 0);
  11054. __decorate([
  11055. BABYLON.serialize()
  11056. ], Light.prototype, "range", void 0);
  11057. __decorate([
  11058. BABYLON.serialize()
  11059. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11060. __decorate([
  11061. BABYLON.serialize()
  11062. ], Light.prototype, "excludeWithLayerMask", void 0);
  11063. __decorate([
  11064. BABYLON.serialize()
  11065. ], Light.prototype, "lightmapMode", void 0);
  11066. __decorate([
  11067. BABYLON.serialize()
  11068. ], Light.prototype, "radius", void 0);
  11069. return Light;
  11070. })(BABYLON.Node);
  11071. BABYLON.Light = Light;
  11072. })(BABYLON || (BABYLON = {}));
  11073. var BABYLON;
  11074. (function (BABYLON) {
  11075. var PointLight = (function (_super) {
  11076. __extends(PointLight, _super);
  11077. function PointLight(name, position, scene) {
  11078. _super.call(this, name, scene);
  11079. this.position = position;
  11080. }
  11081. PointLight.prototype.getAbsolutePosition = function () {
  11082. return this.transformedPosition ? this.transformedPosition : this.position;
  11083. };
  11084. PointLight.prototype.computeTransformedPosition = function () {
  11085. if (this.parent && this.parent.getWorldMatrix) {
  11086. if (!this.transformedPosition) {
  11087. this.transformedPosition = BABYLON.Vector3.Zero();
  11088. }
  11089. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11090. return true;
  11091. }
  11092. return false;
  11093. };
  11094. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11095. if (this.parent && this.parent.getWorldMatrix) {
  11096. this.computeTransformedPosition();
  11097. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11098. return;
  11099. }
  11100. if (this.getScene().useRightHandedSystem) {
  11101. effect.setFloat4(positionUniformName, -this.position.x, -this.position.y, -this.position.z, 0);
  11102. }
  11103. else {
  11104. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11105. }
  11106. };
  11107. PointLight.prototype.needCube = function () {
  11108. return true;
  11109. };
  11110. PointLight.prototype.supportsVSM = function () {
  11111. return false;
  11112. };
  11113. PointLight.prototype.needRefreshPerFrame = function () {
  11114. return false;
  11115. };
  11116. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11117. switch (faceIndex) {
  11118. case 0:
  11119. return new BABYLON.Vector3(1, 0, 0);
  11120. case 1:
  11121. return new BABYLON.Vector3(-1, 0, 0);
  11122. case 2:
  11123. return new BABYLON.Vector3(0, -1, 0);
  11124. case 3:
  11125. return new BABYLON.Vector3(0, 1, 0);
  11126. case 4:
  11127. return new BABYLON.Vector3(0, 0, 1);
  11128. case 5:
  11129. return new BABYLON.Vector3(0, 0, -1);
  11130. }
  11131. return BABYLON.Vector3.Zero();
  11132. };
  11133. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11134. var activeCamera = this.getScene().activeCamera;
  11135. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11136. };
  11137. PointLight.prototype._getWorldMatrix = function () {
  11138. if (!this._worldMatrix) {
  11139. this._worldMatrix = BABYLON.Matrix.Identity();
  11140. }
  11141. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11142. return this._worldMatrix;
  11143. };
  11144. PointLight.prototype.getTypeID = function () {
  11145. return 0;
  11146. };
  11147. __decorate([
  11148. BABYLON.serializeAsVector3()
  11149. ], PointLight.prototype, "position", void 0);
  11150. return PointLight;
  11151. })(BABYLON.Light);
  11152. BABYLON.PointLight = PointLight;
  11153. })(BABYLON || (BABYLON = {}));
  11154. var BABYLON;
  11155. (function (BABYLON) {
  11156. var SpotLight = (function (_super) {
  11157. __extends(SpotLight, _super);
  11158. function SpotLight(name, position, direction, angle, exponent, scene) {
  11159. _super.call(this, name, scene);
  11160. this.position = position;
  11161. this.direction = direction;
  11162. this.angle = angle;
  11163. this.exponent = exponent;
  11164. }
  11165. SpotLight.prototype.getAbsolutePosition = function () {
  11166. return this.transformedPosition ? this.transformedPosition : this.position;
  11167. };
  11168. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11169. var activeCamera = this.getScene().activeCamera;
  11170. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11171. };
  11172. SpotLight.prototype.needCube = function () {
  11173. return false;
  11174. };
  11175. SpotLight.prototype.supportsVSM = function () {
  11176. return true;
  11177. };
  11178. SpotLight.prototype.needRefreshPerFrame = function () {
  11179. return false;
  11180. };
  11181. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11182. return this.direction;
  11183. };
  11184. SpotLight.prototype.setDirectionToTarget = function (target) {
  11185. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11186. return this.direction;
  11187. };
  11188. SpotLight.prototype.computeTransformedPosition = function () {
  11189. if (this.parent && this.parent.getWorldMatrix) {
  11190. if (!this.transformedPosition) {
  11191. this.transformedPosition = BABYLON.Vector3.Zero();
  11192. }
  11193. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11194. return true;
  11195. }
  11196. return false;
  11197. };
  11198. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11199. var normalizeDirection;
  11200. if (this.parent && this.parent.getWorldMatrix) {
  11201. if (!this._transformedDirection) {
  11202. this._transformedDirection = BABYLON.Vector3.Zero();
  11203. }
  11204. this.computeTransformedPosition();
  11205. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11206. if (this.getScene().useRightHandedSystem) {
  11207. effect.setFloat4(positionUniformName, -this.transformedPosition.x, -this.transformedPosition.y, -this.transformedPosition.z, this.exponent);
  11208. }
  11209. else {
  11210. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11211. }
  11212. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11213. }
  11214. else {
  11215. if (this.getScene().useRightHandedSystem) {
  11216. effect.setFloat4(positionUniformName, -this.position.x, -this.position.y, -this.position.z, this.exponent);
  11217. }
  11218. else {
  11219. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11220. }
  11221. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11222. }
  11223. if (this.getScene().useRightHandedSystem) {
  11224. effect.setFloat4(directionUniformName, -normalizeDirection.x, -normalizeDirection.y, -normalizeDirection.z, Math.cos(this.angle * 0.5));
  11225. }
  11226. else {
  11227. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11228. }
  11229. };
  11230. SpotLight.prototype._getWorldMatrix = function () {
  11231. if (!this._worldMatrix) {
  11232. this._worldMatrix = BABYLON.Matrix.Identity();
  11233. }
  11234. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11235. return this._worldMatrix;
  11236. };
  11237. SpotLight.prototype.getTypeID = function () {
  11238. return 2;
  11239. };
  11240. __decorate([
  11241. BABYLON.serializeAsVector3()
  11242. ], SpotLight.prototype, "position", void 0);
  11243. __decorate([
  11244. BABYLON.serializeAsVector3()
  11245. ], SpotLight.prototype, "direction", void 0);
  11246. __decorate([
  11247. BABYLON.serialize()
  11248. ], SpotLight.prototype, "angle", void 0);
  11249. __decorate([
  11250. BABYLON.serialize()
  11251. ], SpotLight.prototype, "exponent", void 0);
  11252. return SpotLight;
  11253. })(BABYLON.Light);
  11254. BABYLON.SpotLight = SpotLight;
  11255. })(BABYLON || (BABYLON = {}));
  11256. var BABYLON;
  11257. (function (BABYLON) {
  11258. var HemisphericLight = (function (_super) {
  11259. __extends(HemisphericLight, _super);
  11260. function HemisphericLight(name, direction, scene) {
  11261. _super.call(this, name, scene);
  11262. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11263. this.direction = direction;
  11264. }
  11265. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11266. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11267. return this.direction;
  11268. };
  11269. HemisphericLight.prototype.getShadowGenerator = function () {
  11270. return null;
  11271. };
  11272. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11273. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11274. if (this.getScene().useRightHandedSystem) {
  11275. effect.setFloat4(directionUniformName, -normalizeDirection.x, -normalizeDirection.y, -normalizeDirection.z, 0);
  11276. }
  11277. else {
  11278. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11279. }
  11280. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11281. };
  11282. HemisphericLight.prototype._getWorldMatrix = function () {
  11283. if (!this._worldMatrix) {
  11284. this._worldMatrix = BABYLON.Matrix.Identity();
  11285. }
  11286. return this._worldMatrix;
  11287. };
  11288. HemisphericLight.prototype.getTypeID = function () {
  11289. return 3;
  11290. };
  11291. __decorate([
  11292. BABYLON.serializeAsColor3()
  11293. ], HemisphericLight.prototype, "groundColor", void 0);
  11294. __decorate([
  11295. BABYLON.serializeAsVector3()
  11296. ], HemisphericLight.prototype, "direction", void 0);
  11297. return HemisphericLight;
  11298. })(BABYLON.Light);
  11299. BABYLON.HemisphericLight = HemisphericLight;
  11300. })(BABYLON || (BABYLON = {}));
  11301. var BABYLON;
  11302. (function (BABYLON) {
  11303. var DirectionalLight = (function (_super) {
  11304. __extends(DirectionalLight, _super);
  11305. function DirectionalLight(name, direction, scene) {
  11306. _super.call(this, name, scene);
  11307. this.shadowOrthoScale = 0.5;
  11308. this.autoUpdateExtends = true;
  11309. // Cache
  11310. this._orthoLeft = Number.MAX_VALUE;
  11311. this._orthoRight = Number.MIN_VALUE;
  11312. this._orthoTop = Number.MIN_VALUE;
  11313. this._orthoBottom = Number.MAX_VALUE;
  11314. this.position = direction.scale(-1);
  11315. this.direction = direction;
  11316. }
  11317. DirectionalLight.prototype.getAbsolutePosition = function () {
  11318. return this.transformedPosition ? this.transformedPosition : this.position;
  11319. };
  11320. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11321. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11322. return this.direction;
  11323. };
  11324. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11325. var activeCamera = this.getScene().activeCamera;
  11326. // Check extends
  11327. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11328. var tempVector3 = BABYLON.Vector3.Zero();
  11329. this._orthoLeft = Number.MAX_VALUE;
  11330. this._orthoRight = Number.MIN_VALUE;
  11331. this._orthoTop = Number.MIN_VALUE;
  11332. this._orthoBottom = Number.MAX_VALUE;
  11333. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11334. var mesh = renderList[meshIndex];
  11335. if (!mesh) {
  11336. continue;
  11337. }
  11338. var boundingInfo = mesh.getBoundingInfo();
  11339. if (!boundingInfo) {
  11340. continue;
  11341. }
  11342. var boundingBox = boundingInfo.boundingBox;
  11343. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11344. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11345. if (tempVector3.x < this._orthoLeft)
  11346. this._orthoLeft = tempVector3.x;
  11347. if (tempVector3.y < this._orthoBottom)
  11348. this._orthoBottom = tempVector3.y;
  11349. if (tempVector3.x > this._orthoRight)
  11350. this._orthoRight = tempVector3.x;
  11351. if (tempVector3.y > this._orthoTop)
  11352. this._orthoTop = tempVector3.y;
  11353. }
  11354. }
  11355. }
  11356. var xOffset = this._orthoRight - this._orthoLeft;
  11357. var yOffset = this._orthoTop - this._orthoBottom;
  11358. 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);
  11359. };
  11360. DirectionalLight.prototype.supportsVSM = function () {
  11361. return true;
  11362. };
  11363. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11364. return true;
  11365. };
  11366. DirectionalLight.prototype.needCube = function () {
  11367. return false;
  11368. };
  11369. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11370. return this.direction;
  11371. };
  11372. DirectionalLight.prototype.computeTransformedPosition = function () {
  11373. if (this.parent && this.parent.getWorldMatrix) {
  11374. if (!this.transformedPosition) {
  11375. this.transformedPosition = BABYLON.Vector3.Zero();
  11376. }
  11377. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11378. return true;
  11379. }
  11380. return false;
  11381. };
  11382. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11383. if (this.parent && this.parent.getWorldMatrix) {
  11384. if (!this._transformedDirection) {
  11385. this._transformedDirection = BABYLON.Vector3.Zero();
  11386. }
  11387. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11388. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11389. return;
  11390. }
  11391. if (this.getScene().useRightHandedSystem) {
  11392. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, -1);
  11393. }
  11394. else {
  11395. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11396. }
  11397. };
  11398. DirectionalLight.prototype._getWorldMatrix = function () {
  11399. if (!this._worldMatrix) {
  11400. this._worldMatrix = BABYLON.Matrix.Identity();
  11401. }
  11402. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11403. return this._worldMatrix;
  11404. };
  11405. DirectionalLight.prototype.getTypeID = function () {
  11406. return 1;
  11407. };
  11408. __decorate([
  11409. BABYLON.serializeAsVector3()
  11410. ], DirectionalLight.prototype, "position", void 0);
  11411. __decorate([
  11412. BABYLON.serializeAsVector3()
  11413. ], DirectionalLight.prototype, "direction", void 0);
  11414. __decorate([
  11415. BABYLON.serialize()
  11416. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11417. __decorate([
  11418. BABYLON.serialize()
  11419. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11420. return DirectionalLight;
  11421. })(BABYLON.Light);
  11422. BABYLON.DirectionalLight = DirectionalLight;
  11423. })(BABYLON || (BABYLON = {}));
  11424. var BABYLON;
  11425. (function (BABYLON) {
  11426. var ShadowGenerator = (function () {
  11427. function ShadowGenerator(mapSize, light) {
  11428. var _this = this;
  11429. // Members
  11430. this._filter = ShadowGenerator.FILTER_NONE;
  11431. this.blurScale = 2;
  11432. this._blurBoxOffset = 0;
  11433. this._bias = 0.00005;
  11434. this._lightDirection = BABYLON.Vector3.Zero();
  11435. this.forceBackFacesOnly = false;
  11436. this._darkness = 0;
  11437. this._transparencyShadow = false;
  11438. this._viewMatrix = BABYLON.Matrix.Zero();
  11439. this._projectionMatrix = BABYLON.Matrix.Zero();
  11440. this._transformMatrix = BABYLON.Matrix.Zero();
  11441. this._worldViewProjection = BABYLON.Matrix.Zero();
  11442. this._currentFaceIndex = 0;
  11443. this._currentFaceIndexCache = 0;
  11444. this._useFullFloat = true;
  11445. this._light = light;
  11446. this._scene = light.getScene();
  11447. this._mapSize = mapSize;
  11448. light._shadowGenerator = this;
  11449. // Texture type fallback from float to int if not supported.
  11450. var textureType;
  11451. var caps = this._scene.getEngine().getCaps();
  11452. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11453. this._useFullFloat = true;
  11454. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11455. }
  11456. else {
  11457. this._useFullFloat = false;
  11458. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11459. }
  11460. // Render target
  11461. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11462. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11463. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11464. this._shadowMap.anisotropicFilteringLevel = 1;
  11465. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11466. this._shadowMap.renderParticles = false;
  11467. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11468. _this._currentFaceIndex = faceIndex;
  11469. });
  11470. this._shadowMap.onAfterUnbindObservable.add(function () {
  11471. if (!_this.useBlurVarianceShadowMap) {
  11472. return;
  11473. }
  11474. if (!_this._shadowMap2) {
  11475. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11476. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11477. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11478. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11479. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11480. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11481. effect.setTexture("textureSampler", _this._shadowMap);
  11482. });
  11483. _this.blurBoxOffset = 1;
  11484. }
  11485. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11486. });
  11487. // Custom render function
  11488. var renderSubMesh = function (subMesh) {
  11489. var mesh = subMesh.getRenderingMesh();
  11490. var scene = _this._scene;
  11491. var engine = scene.getEngine();
  11492. // Culling
  11493. engine.setState(subMesh.getMaterial().backFaceCulling);
  11494. // Managing instances
  11495. var batch = mesh._getInstancesRenderList(subMesh._id);
  11496. if (batch.mustReturn) {
  11497. return;
  11498. }
  11499. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11500. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11501. engine.enableEffect(_this._effect);
  11502. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11503. var material = subMesh.getMaterial();
  11504. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11505. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11506. if (_this.getLight().needCube()) {
  11507. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11508. }
  11509. // Alpha test
  11510. if (material && material.needAlphaTesting()) {
  11511. var alphaTexture = material.getAlphaTestTexture();
  11512. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11513. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11514. }
  11515. // Bones
  11516. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11517. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11518. }
  11519. if (_this.forceBackFacesOnly) {
  11520. engine.setState(true, 0, false, true);
  11521. }
  11522. // Draw
  11523. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11524. if (_this.forceBackFacesOnly) {
  11525. engine.setState(true, 0, false, false);
  11526. }
  11527. }
  11528. else {
  11529. // Need to reset refresh rate of the shadowMap
  11530. _this._shadowMap.resetRefreshCounter();
  11531. }
  11532. };
  11533. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11534. var index;
  11535. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11536. renderSubMesh(opaqueSubMeshes.data[index]);
  11537. }
  11538. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11539. renderSubMesh(alphaTestSubMeshes.data[index]);
  11540. }
  11541. if (_this._transparencyShadow) {
  11542. for (index = 0; index < transparentSubMeshes.length; index++) {
  11543. renderSubMesh(transparentSubMeshes.data[index]);
  11544. }
  11545. }
  11546. };
  11547. this._shadowMap.onClearObservable.add(function (engine) {
  11548. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11549. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11550. }
  11551. else {
  11552. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11553. }
  11554. });
  11555. }
  11556. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11557. // Static
  11558. get: function () {
  11559. return ShadowGenerator._FILTER_NONE;
  11560. },
  11561. enumerable: true,
  11562. configurable: true
  11563. });
  11564. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11565. get: function () {
  11566. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11567. },
  11568. enumerable: true,
  11569. configurable: true
  11570. });
  11571. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11572. get: function () {
  11573. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11574. },
  11575. enumerable: true,
  11576. configurable: true
  11577. });
  11578. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11579. get: function () {
  11580. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11581. },
  11582. enumerable: true,
  11583. configurable: true
  11584. });
  11585. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11586. get: function () {
  11587. return this._bias;
  11588. },
  11589. set: function (bias) {
  11590. this._bias = bias;
  11591. },
  11592. enumerable: true,
  11593. configurable: true
  11594. });
  11595. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11596. get: function () {
  11597. return this._blurBoxOffset;
  11598. },
  11599. set: function (value) {
  11600. var _this = this;
  11601. if (this._blurBoxOffset === value) {
  11602. return;
  11603. }
  11604. this._blurBoxOffset = value;
  11605. if (this._boxBlurPostprocess) {
  11606. this._boxBlurPostprocess.dispose();
  11607. }
  11608. 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);
  11609. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11610. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11611. });
  11612. },
  11613. enumerable: true,
  11614. configurable: true
  11615. });
  11616. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11617. get: function () {
  11618. return this._filter;
  11619. },
  11620. set: function (value) {
  11621. if (this._filter === value) {
  11622. return;
  11623. }
  11624. this._filter = value;
  11625. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11626. this._shadowMap.anisotropicFilteringLevel = 16;
  11627. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11628. }
  11629. else {
  11630. this._shadowMap.anisotropicFilteringLevel = 1;
  11631. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11632. }
  11633. },
  11634. enumerable: true,
  11635. configurable: true
  11636. });
  11637. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11638. get: function () {
  11639. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11640. },
  11641. set: function (value) {
  11642. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11643. },
  11644. enumerable: true,
  11645. configurable: true
  11646. });
  11647. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11648. get: function () {
  11649. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11650. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11651. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11652. },
  11653. set: function (value) {
  11654. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11655. },
  11656. enumerable: true,
  11657. configurable: true
  11658. });
  11659. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11660. get: function () {
  11661. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11662. },
  11663. set: function (value) {
  11664. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11665. },
  11666. enumerable: true,
  11667. configurable: true
  11668. });
  11669. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11670. var defines = [];
  11671. if (this._useFullFloat) {
  11672. defines.push("#define FULLFLOAT");
  11673. }
  11674. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11675. defines.push("#define VSM");
  11676. }
  11677. if (this.getLight().needCube()) {
  11678. defines.push("#define CUBEMAP");
  11679. }
  11680. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11681. var mesh = subMesh.getMesh();
  11682. var material = subMesh.getMaterial();
  11683. // Alpha test
  11684. if (material && material.needAlphaTesting()) {
  11685. defines.push("#define ALPHATEST");
  11686. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11687. attribs.push(BABYLON.VertexBuffer.UVKind);
  11688. defines.push("#define UV1");
  11689. }
  11690. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11691. var alphaTexture = material.getAlphaTestTexture();
  11692. if (alphaTexture.coordinatesIndex === 1) {
  11693. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11694. defines.push("#define UV2");
  11695. }
  11696. }
  11697. }
  11698. // Bones
  11699. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11700. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11701. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11702. if (mesh.numBoneInfluencers > 4) {
  11703. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11704. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11705. }
  11706. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11707. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11708. }
  11709. else {
  11710. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11711. }
  11712. // Instances
  11713. if (useInstances) {
  11714. defines.push("#define INSTANCES");
  11715. attribs.push("world0");
  11716. attribs.push("world1");
  11717. attribs.push("world2");
  11718. attribs.push("world3");
  11719. }
  11720. // Get correct effect
  11721. var join = defines.join("\n");
  11722. if (this._cachedDefines !== join) {
  11723. this._cachedDefines = join;
  11724. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11725. }
  11726. return this._effect.isReady();
  11727. };
  11728. ShadowGenerator.prototype.getShadowMap = function () {
  11729. return this._shadowMap;
  11730. };
  11731. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11732. if (this._shadowMap2) {
  11733. return this._shadowMap2;
  11734. }
  11735. return this._shadowMap;
  11736. };
  11737. ShadowGenerator.prototype.getLight = function () {
  11738. return this._light;
  11739. };
  11740. // Methods
  11741. ShadowGenerator.prototype.getTransformMatrix = function () {
  11742. var scene = this._scene;
  11743. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11744. return this._transformMatrix;
  11745. }
  11746. this._currentRenderID = scene.getRenderId();
  11747. this._currentFaceIndexCache = this._currentFaceIndex;
  11748. var lightPosition = this._light.position;
  11749. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11750. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11751. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11752. }
  11753. if (this._light.computeTransformedPosition()) {
  11754. lightPosition = this._light.transformedPosition;
  11755. }
  11756. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11757. this._cachedPosition = lightPosition.clone();
  11758. this._cachedDirection = this._lightDirection.clone();
  11759. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11760. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11761. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11762. }
  11763. return this._transformMatrix;
  11764. };
  11765. ShadowGenerator.prototype.getDarkness = function () {
  11766. return this._darkness;
  11767. };
  11768. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11769. if (darkness >= 1.0)
  11770. this._darkness = 1.0;
  11771. else if (darkness <= 0.0)
  11772. this._darkness = 0.0;
  11773. else
  11774. this._darkness = darkness;
  11775. };
  11776. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11777. this._transparencyShadow = hasShadow;
  11778. };
  11779. ShadowGenerator.prototype._packHalf = function (depth) {
  11780. var scale = depth * 255.0;
  11781. var fract = scale - Math.floor(scale);
  11782. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11783. };
  11784. ShadowGenerator.prototype.dispose = function () {
  11785. this._shadowMap.dispose();
  11786. if (this._shadowMap2) {
  11787. this._shadowMap2.dispose();
  11788. }
  11789. if (this._downSamplePostprocess) {
  11790. this._downSamplePostprocess.dispose();
  11791. }
  11792. if (this._boxBlurPostprocess) {
  11793. this._boxBlurPostprocess.dispose();
  11794. }
  11795. };
  11796. ShadowGenerator.prototype.serialize = function () {
  11797. var serializationObject = {};
  11798. serializationObject.lightId = this._light.id;
  11799. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11800. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11801. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11802. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11803. serializationObject.renderList = [];
  11804. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11805. var mesh = this.getShadowMap().renderList[meshIndex];
  11806. serializationObject.renderList.push(mesh.id);
  11807. }
  11808. return serializationObject;
  11809. };
  11810. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11811. //casting to point light, as light is missing the position attr and typescript complains.
  11812. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11813. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11814. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11815. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11816. meshes.forEach(function (mesh) {
  11817. shadowGenerator.getShadowMap().renderList.push(mesh);
  11818. });
  11819. }
  11820. if (parsedShadowGenerator.usePoissonSampling) {
  11821. shadowGenerator.usePoissonSampling = true;
  11822. }
  11823. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11824. shadowGenerator.useVarianceShadowMap = true;
  11825. }
  11826. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11827. shadowGenerator.useBlurVarianceShadowMap = true;
  11828. if (parsedShadowGenerator.blurScale) {
  11829. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11830. }
  11831. if (parsedShadowGenerator.blurBoxOffset) {
  11832. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11833. }
  11834. }
  11835. if (parsedShadowGenerator.bias !== undefined) {
  11836. shadowGenerator.bias = parsedShadowGenerator.bias;
  11837. }
  11838. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11839. return shadowGenerator;
  11840. };
  11841. ShadowGenerator._FILTER_NONE = 0;
  11842. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11843. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11844. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11845. return ShadowGenerator;
  11846. })();
  11847. BABYLON.ShadowGenerator = ShadowGenerator;
  11848. })(BABYLON || (BABYLON = {}));
  11849. var BABYLON;
  11850. (function (BABYLON) {
  11851. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  11852. if (boxMin.x > sphereCenter.x + sphereRadius)
  11853. return false;
  11854. if (sphereCenter.x - sphereRadius > boxMax.x)
  11855. return false;
  11856. if (boxMin.y > sphereCenter.y + sphereRadius)
  11857. return false;
  11858. if (sphereCenter.y - sphereRadius > boxMax.y)
  11859. return false;
  11860. if (boxMin.z > sphereCenter.z + sphereRadius)
  11861. return false;
  11862. if (sphereCenter.z - sphereRadius > boxMax.z)
  11863. return false;
  11864. return true;
  11865. };
  11866. var getLowestRoot = (function () {
  11867. var result = { root: 0, found: false };
  11868. return function (a, b, c, maxR) {
  11869. result.root = 0;
  11870. result.found = false;
  11871. var determinant = b * b - 4.0 * a * c;
  11872. if (determinant < 0)
  11873. return result;
  11874. var sqrtD = Math.sqrt(determinant);
  11875. var r1 = (-b - sqrtD) / (2.0 * a);
  11876. var r2 = (-b + sqrtD) / (2.0 * a);
  11877. if (r1 > r2) {
  11878. var temp = r2;
  11879. r2 = r1;
  11880. r1 = temp;
  11881. }
  11882. if (r1 > 0 && r1 < maxR) {
  11883. result.root = r1;
  11884. result.found = true;
  11885. return result;
  11886. }
  11887. if (r2 > 0 && r2 < maxR) {
  11888. result.root = r2;
  11889. result.found = true;
  11890. return result;
  11891. }
  11892. return result;
  11893. };
  11894. })();
  11895. var Collider = (function () {
  11896. function Collider() {
  11897. this.radius = new BABYLON.Vector3(1, 1, 1);
  11898. this.retry = 0;
  11899. this.basePointWorld = BABYLON.Vector3.Zero();
  11900. this.velocityWorld = BABYLON.Vector3.Zero();
  11901. this.normalizedVelocity = BABYLON.Vector3.Zero();
  11902. this._collisionPoint = BABYLON.Vector3.Zero();
  11903. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  11904. this._tempVector = BABYLON.Vector3.Zero();
  11905. this._tempVector2 = BABYLON.Vector3.Zero();
  11906. this._tempVector3 = BABYLON.Vector3.Zero();
  11907. this._tempVector4 = BABYLON.Vector3.Zero();
  11908. this._edge = BABYLON.Vector3.Zero();
  11909. this._baseToVertex = BABYLON.Vector3.Zero();
  11910. this._destinationPoint = BABYLON.Vector3.Zero();
  11911. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  11912. this._displacementVector = BABYLON.Vector3.Zero();
  11913. }
  11914. // Methods
  11915. Collider.prototype._initialize = function (source, dir, e) {
  11916. this.velocity = dir;
  11917. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  11918. this.basePoint = source;
  11919. source.multiplyToRef(this.radius, this.basePointWorld);
  11920. dir.multiplyToRef(this.radius, this.velocityWorld);
  11921. this.velocityWorldLength = this.velocityWorld.length();
  11922. this.epsilon = e;
  11923. this.collisionFound = false;
  11924. };
  11925. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  11926. pa.subtractToRef(point, this._tempVector);
  11927. pb.subtractToRef(point, this._tempVector2);
  11928. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  11929. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11930. if (d < 0)
  11931. return false;
  11932. pc.subtractToRef(point, this._tempVector3);
  11933. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  11934. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11935. if (d < 0)
  11936. return false;
  11937. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  11938. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11939. return d >= 0;
  11940. };
  11941. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  11942. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  11943. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  11944. if (distance > this.velocityWorldLength + max + sphereRadius) {
  11945. return false;
  11946. }
  11947. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  11948. return false;
  11949. return true;
  11950. };
  11951. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  11952. var t0;
  11953. var embeddedInPlane = false;
  11954. //defensive programming, actually not needed.
  11955. if (!trianglePlaneArray) {
  11956. trianglePlaneArray = [];
  11957. }
  11958. if (!trianglePlaneArray[faceIndex]) {
  11959. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  11960. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  11961. }
  11962. var trianglePlane = trianglePlaneArray[faceIndex];
  11963. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  11964. return;
  11965. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  11966. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  11967. if (normalDotVelocity == 0) {
  11968. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  11969. return;
  11970. embeddedInPlane = true;
  11971. t0 = 0;
  11972. }
  11973. else {
  11974. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11975. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11976. if (t0 > t1) {
  11977. var temp = t1;
  11978. t1 = t0;
  11979. t0 = temp;
  11980. }
  11981. if (t0 > 1.0 || t1 < 0.0)
  11982. return;
  11983. if (t0 < 0)
  11984. t0 = 0;
  11985. if (t0 > 1.0)
  11986. t0 = 1.0;
  11987. }
  11988. this._collisionPoint.copyFromFloats(0, 0, 0);
  11989. var found = false;
  11990. var t = 1.0;
  11991. if (!embeddedInPlane) {
  11992. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  11993. this.velocity.scaleToRef(t0, this._tempVector);
  11994. this._planeIntersectionPoint.addInPlace(this._tempVector);
  11995. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  11996. found = true;
  11997. t = t0;
  11998. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  11999. }
  12000. }
  12001. if (!found) {
  12002. var velocitySquaredLength = this.velocity.lengthSquared();
  12003. var a = velocitySquaredLength;
  12004. this.basePoint.subtractToRef(p1, this._tempVector);
  12005. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12006. var c = this._tempVector.lengthSquared() - 1.0;
  12007. var lowestRoot = getLowestRoot(a, b, c, t);
  12008. if (lowestRoot.found) {
  12009. t = lowestRoot.root;
  12010. found = true;
  12011. this._collisionPoint.copyFrom(p1);
  12012. }
  12013. this.basePoint.subtractToRef(p2, this._tempVector);
  12014. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12015. c = this._tempVector.lengthSquared() - 1.0;
  12016. lowestRoot = getLowestRoot(a, b, c, t);
  12017. if (lowestRoot.found) {
  12018. t = lowestRoot.root;
  12019. found = true;
  12020. this._collisionPoint.copyFrom(p2);
  12021. }
  12022. this.basePoint.subtractToRef(p3, this._tempVector);
  12023. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12024. c = this._tempVector.lengthSquared() - 1.0;
  12025. lowestRoot = getLowestRoot(a, b, c, t);
  12026. if (lowestRoot.found) {
  12027. t = lowestRoot.root;
  12028. found = true;
  12029. this._collisionPoint.copyFrom(p3);
  12030. }
  12031. p2.subtractToRef(p1, this._edge);
  12032. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12033. var edgeSquaredLength = this._edge.lengthSquared();
  12034. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12035. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12036. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12037. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12038. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12039. lowestRoot = getLowestRoot(a, b, c, t);
  12040. if (lowestRoot.found) {
  12041. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12042. if (f >= 0.0 && f <= 1.0) {
  12043. t = lowestRoot.root;
  12044. found = true;
  12045. this._edge.scaleInPlace(f);
  12046. p1.addToRef(this._edge, this._collisionPoint);
  12047. }
  12048. }
  12049. p3.subtractToRef(p2, this._edge);
  12050. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12051. edgeSquaredLength = this._edge.lengthSquared();
  12052. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12053. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12054. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12055. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12056. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12057. lowestRoot = getLowestRoot(a, b, c, t);
  12058. if (lowestRoot.found) {
  12059. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12060. if (f >= 0.0 && f <= 1.0) {
  12061. t = lowestRoot.root;
  12062. found = true;
  12063. this._edge.scaleInPlace(f);
  12064. p2.addToRef(this._edge, this._collisionPoint);
  12065. }
  12066. }
  12067. p1.subtractToRef(p3, this._edge);
  12068. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12069. edgeSquaredLength = this._edge.lengthSquared();
  12070. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12071. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12072. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12073. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12074. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12075. lowestRoot = getLowestRoot(a, b, c, t);
  12076. if (lowestRoot.found) {
  12077. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12078. if (f >= 0.0 && f <= 1.0) {
  12079. t = lowestRoot.root;
  12080. found = true;
  12081. this._edge.scaleInPlace(f);
  12082. p3.addToRef(this._edge, this._collisionPoint);
  12083. }
  12084. }
  12085. }
  12086. if (found) {
  12087. var distToCollision = t * this.velocity.length();
  12088. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12089. if (!this.intersectionPoint) {
  12090. this.intersectionPoint = this._collisionPoint.clone();
  12091. }
  12092. else {
  12093. this.intersectionPoint.copyFrom(this._collisionPoint);
  12094. }
  12095. this.nearestDistance = distToCollision;
  12096. this.collisionFound = true;
  12097. }
  12098. }
  12099. };
  12100. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12101. for (var i = indexStart; i < indexEnd; i += 3) {
  12102. var p1 = pts[indices[i] - decal];
  12103. var p2 = pts[indices[i + 1] - decal];
  12104. var p3 = pts[indices[i + 2] - decal];
  12105. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12106. }
  12107. };
  12108. Collider.prototype._getResponse = function (pos, vel) {
  12109. pos.addToRef(vel, this._destinationPoint);
  12110. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12111. this.basePoint.addToRef(vel, pos);
  12112. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12113. this._slidePlaneNormal.normalize();
  12114. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12115. pos.addInPlace(this._displacementVector);
  12116. this.intersectionPoint.addInPlace(this._displacementVector);
  12117. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12118. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12119. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12120. };
  12121. return Collider;
  12122. })();
  12123. BABYLON.Collider = Collider;
  12124. })(BABYLON || (BABYLON = {}));
  12125. var BABYLON;
  12126. (function (BABYLON) {
  12127. //WebWorker code will be inserted to this variable.
  12128. BABYLON.CollisionWorker = "";
  12129. (function (WorkerTaskType) {
  12130. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12131. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12132. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12133. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12134. var WorkerTaskType = BABYLON.WorkerTaskType;
  12135. (function (WorkerReplyType) {
  12136. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12137. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12138. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12139. var WorkerReplyType = BABYLON.WorkerReplyType;
  12140. var CollisionCoordinatorWorker = (function () {
  12141. function CollisionCoordinatorWorker() {
  12142. var _this = this;
  12143. this._scaledPosition = BABYLON.Vector3.Zero();
  12144. this._scaledVelocity = BABYLON.Vector3.Zero();
  12145. this.onMeshUpdated = function (mesh) {
  12146. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12147. };
  12148. this.onGeometryUpdated = function (geometry) {
  12149. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12150. };
  12151. this._afterRender = function () {
  12152. if (!_this._init)
  12153. return;
  12154. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12155. return;
  12156. }
  12157. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12158. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12159. if (_this._runningUpdated > 4) {
  12160. return;
  12161. }
  12162. ++_this._runningUpdated;
  12163. var payload = {
  12164. updatedMeshes: _this._addUpdateMeshesList,
  12165. updatedGeometries: _this._addUpdateGeometriesList,
  12166. removedGeometries: _this._toRemoveGeometryArray,
  12167. removedMeshes: _this._toRemoveMeshesArray
  12168. };
  12169. var message = {
  12170. payload: payload,
  12171. taskType: WorkerTaskType.UPDATE
  12172. };
  12173. var serializable = [];
  12174. for (var id in payload.updatedGeometries) {
  12175. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12176. //prepare transferables
  12177. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12178. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12179. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12180. }
  12181. }
  12182. _this._worker.postMessage(message, serializable);
  12183. _this._addUpdateMeshesList = {};
  12184. _this._addUpdateGeometriesList = {};
  12185. _this._toRemoveGeometryArray = [];
  12186. _this._toRemoveMeshesArray = [];
  12187. };
  12188. this._onMessageFromWorker = function (e) {
  12189. var returnData = e.data;
  12190. if (returnData.error != WorkerReplyType.SUCCESS) {
  12191. //TODO what errors can be returned from the worker?
  12192. BABYLON.Tools.Warn("error returned from worker!");
  12193. return;
  12194. }
  12195. switch (returnData.taskType) {
  12196. case WorkerTaskType.INIT:
  12197. _this._init = true;
  12198. //Update the worked with ALL of the scene's current state
  12199. _this._scene.meshes.forEach(function (mesh) {
  12200. _this.onMeshAdded(mesh);
  12201. });
  12202. _this._scene.getGeometries().forEach(function (geometry) {
  12203. _this.onGeometryAdded(geometry);
  12204. });
  12205. break;
  12206. case WorkerTaskType.UPDATE:
  12207. _this._runningUpdated--;
  12208. break;
  12209. case WorkerTaskType.COLLIDE:
  12210. _this._runningCollisionTask = false;
  12211. var returnPayload = returnData.payload;
  12212. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12213. return;
  12214. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12215. //cleanup
  12216. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12217. break;
  12218. }
  12219. };
  12220. this._collisionsCallbackArray = [];
  12221. this._init = false;
  12222. this._runningUpdated = 0;
  12223. this._runningCollisionTask = false;
  12224. this._addUpdateMeshesList = {};
  12225. this._addUpdateGeometriesList = {};
  12226. this._toRemoveGeometryArray = [];
  12227. this._toRemoveMeshesArray = [];
  12228. }
  12229. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12230. if (!this._init)
  12231. return;
  12232. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12233. return;
  12234. position.divideToRef(collider.radius, this._scaledPosition);
  12235. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12236. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12237. var payload = {
  12238. collider: {
  12239. position: this._scaledPosition.asArray(),
  12240. velocity: this._scaledVelocity.asArray(),
  12241. radius: collider.radius.asArray()
  12242. },
  12243. collisionId: collisionIndex,
  12244. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12245. maximumRetry: maximumRetry
  12246. };
  12247. var message = {
  12248. payload: payload,
  12249. taskType: WorkerTaskType.COLLIDE
  12250. };
  12251. this._worker.postMessage(message);
  12252. };
  12253. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12254. this._scene = scene;
  12255. this._scene.registerAfterRender(this._afterRender);
  12256. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12257. this._worker = new Worker(workerUrl);
  12258. this._worker.onmessage = this._onMessageFromWorker;
  12259. var message = {
  12260. payload: {},
  12261. taskType: WorkerTaskType.INIT
  12262. };
  12263. this._worker.postMessage(message);
  12264. };
  12265. CollisionCoordinatorWorker.prototype.destroy = function () {
  12266. this._scene.unregisterAfterRender(this._afterRender);
  12267. this._worker.terminate();
  12268. };
  12269. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12270. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12271. this.onMeshUpdated(mesh);
  12272. };
  12273. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12274. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12275. };
  12276. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12277. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12278. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12279. this.onGeometryUpdated(geometry);
  12280. };
  12281. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12282. this._toRemoveGeometryArray.push(geometry.id);
  12283. };
  12284. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12285. var submeshes = [];
  12286. if (mesh.subMeshes) {
  12287. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12288. return {
  12289. position: idx,
  12290. verticesStart: sm.verticesStart,
  12291. verticesCount: sm.verticesCount,
  12292. indexStart: sm.indexStart,
  12293. indexCount: sm.indexCount,
  12294. hasMaterial: !!sm.getMaterial(),
  12295. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12296. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12297. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12298. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12299. };
  12300. });
  12301. }
  12302. var geometryId = null;
  12303. if (mesh instanceof BABYLON.Mesh) {
  12304. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12305. }
  12306. else if (mesh instanceof BABYLON.InstancedMesh) {
  12307. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12308. }
  12309. return {
  12310. uniqueId: mesh.uniqueId,
  12311. id: mesh.id,
  12312. name: mesh.name,
  12313. geometryId: geometryId,
  12314. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12315. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12316. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12317. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12318. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12319. subMeshes: submeshes,
  12320. checkCollisions: mesh.checkCollisions
  12321. };
  12322. };
  12323. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12324. return {
  12325. id: geometry.id,
  12326. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12327. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12328. indices: new Int32Array(geometry.getIndices() || []),
  12329. };
  12330. };
  12331. return CollisionCoordinatorWorker;
  12332. })();
  12333. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12334. var CollisionCoordinatorLegacy = (function () {
  12335. function CollisionCoordinatorLegacy() {
  12336. this._scaledPosition = BABYLON.Vector3.Zero();
  12337. this._scaledVelocity = BABYLON.Vector3.Zero();
  12338. this._finalPosition = BABYLON.Vector3.Zero();
  12339. }
  12340. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12341. position.divideToRef(collider.radius, this._scaledPosition);
  12342. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12343. collider.collidedMesh = null;
  12344. collider.retry = 0;
  12345. collider.initialVelocity = this._scaledVelocity;
  12346. collider.initialPosition = this._scaledPosition;
  12347. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12348. this._finalPosition.multiplyInPlace(collider.radius);
  12349. //run the callback
  12350. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12351. };
  12352. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12353. this._scene = scene;
  12354. };
  12355. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12356. //Legacy need no destruction method.
  12357. };
  12358. //No update in legacy mode
  12359. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12360. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12361. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12362. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12363. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12364. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12365. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12366. if (excludedMesh === void 0) { excludedMesh = null; }
  12367. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12368. if (collider.retry >= maximumRetry) {
  12369. finalPosition.copyFrom(position);
  12370. return;
  12371. }
  12372. collider._initialize(position, velocity, closeDistance);
  12373. // Check all meshes
  12374. for (var index = 0; index < this._scene.meshes.length; index++) {
  12375. var mesh = this._scene.meshes[index];
  12376. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12377. mesh._checkCollision(collider);
  12378. }
  12379. }
  12380. if (!collider.collisionFound) {
  12381. position.addToRef(velocity, finalPosition);
  12382. return;
  12383. }
  12384. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12385. collider._getResponse(position, velocity);
  12386. }
  12387. if (velocity.length() <= closeDistance) {
  12388. finalPosition.copyFrom(position);
  12389. return;
  12390. }
  12391. collider.retry++;
  12392. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12393. };
  12394. return CollisionCoordinatorLegacy;
  12395. })();
  12396. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12397. })(BABYLON || (BABYLON = {}));
  12398. var BABYLON;
  12399. (function (BABYLON) {
  12400. var Camera = (function (_super) {
  12401. __extends(Camera, _super);
  12402. function Camera(name, position, scene) {
  12403. _super.call(this, name, scene);
  12404. this.upVector = BABYLON.Vector3.Up();
  12405. this.orthoLeft = null;
  12406. this.orthoRight = null;
  12407. this.orthoBottom = null;
  12408. this.orthoTop = null;
  12409. this.fov = 0.8;
  12410. this.minZ = 1.0;
  12411. this.maxZ = 10000.0;
  12412. this.inertia = 0.9;
  12413. this.mode = Camera.PERSPECTIVE_CAMERA;
  12414. this.isIntermediate = false;
  12415. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12416. this.layerMask = 0x0FFFFFFF;
  12417. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12418. // Camera rig members
  12419. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12420. this._rigCameras = new Array();
  12421. // Cache
  12422. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12423. this._projectionMatrix = new BABYLON.Matrix();
  12424. this._postProcesses = new Array();
  12425. this._transformMatrix = BABYLON.Matrix.Zero();
  12426. this._activeMeshes = new BABYLON.SmartArray(256);
  12427. this._globalPosition = BABYLON.Vector3.Zero();
  12428. this._refreshFrustumPlanes = true;
  12429. scene.addCamera(this);
  12430. if (!scene.activeCamera) {
  12431. scene.activeCamera = this;
  12432. }
  12433. this.position = position;
  12434. }
  12435. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12436. get: function () {
  12437. return Camera._PERSPECTIVE_CAMERA;
  12438. },
  12439. enumerable: true,
  12440. configurable: true
  12441. });
  12442. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12443. get: function () {
  12444. return Camera._ORTHOGRAPHIC_CAMERA;
  12445. },
  12446. enumerable: true,
  12447. configurable: true
  12448. });
  12449. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12450. get: function () {
  12451. return Camera._FOVMODE_VERTICAL_FIXED;
  12452. },
  12453. enumerable: true,
  12454. configurable: true
  12455. });
  12456. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12457. get: function () {
  12458. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12459. },
  12460. enumerable: true,
  12461. configurable: true
  12462. });
  12463. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12464. get: function () {
  12465. return Camera._RIG_MODE_NONE;
  12466. },
  12467. enumerable: true,
  12468. configurable: true
  12469. });
  12470. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12471. get: function () {
  12472. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12473. },
  12474. enumerable: true,
  12475. configurable: true
  12476. });
  12477. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12478. get: function () {
  12479. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12480. },
  12481. enumerable: true,
  12482. configurable: true
  12483. });
  12484. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12485. get: function () {
  12486. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12487. },
  12488. enumerable: true,
  12489. configurable: true
  12490. });
  12491. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12492. get: function () {
  12493. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12494. },
  12495. enumerable: true,
  12496. configurable: true
  12497. });
  12498. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12499. get: function () {
  12500. return Camera._RIG_MODE_VR;
  12501. },
  12502. enumerable: true,
  12503. configurable: true
  12504. });
  12505. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  12506. get: function () {
  12507. return Camera._RIG_MODE_WEBVR;
  12508. },
  12509. enumerable: true,
  12510. configurable: true
  12511. });
  12512. /**
  12513. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12514. */
  12515. Camera.prototype.toString = function (fullDetails) {
  12516. var ret = "Name: " + this.name;
  12517. ret += ", type: " + this.getTypeName();
  12518. if (this.animations) {
  12519. for (var i = 0; i < this.animations.length; i++) {
  12520. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12521. }
  12522. }
  12523. if (fullDetails) {
  12524. }
  12525. return ret;
  12526. };
  12527. Object.defineProperty(Camera.prototype, "globalPosition", {
  12528. get: function () {
  12529. return this._globalPosition;
  12530. },
  12531. enumerable: true,
  12532. configurable: true
  12533. });
  12534. Camera.prototype.getActiveMeshes = function () {
  12535. return this._activeMeshes;
  12536. };
  12537. Camera.prototype.isActiveMesh = function (mesh) {
  12538. return (this._activeMeshes.indexOf(mesh) !== -1);
  12539. };
  12540. //Cache
  12541. Camera.prototype._initCache = function () {
  12542. _super.prototype._initCache.call(this);
  12543. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12544. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12545. this._cache.mode = undefined;
  12546. this._cache.minZ = undefined;
  12547. this._cache.maxZ = undefined;
  12548. this._cache.fov = undefined;
  12549. this._cache.aspectRatio = undefined;
  12550. this._cache.orthoLeft = undefined;
  12551. this._cache.orthoRight = undefined;
  12552. this._cache.orthoBottom = undefined;
  12553. this._cache.orthoTop = undefined;
  12554. this._cache.renderWidth = undefined;
  12555. this._cache.renderHeight = undefined;
  12556. };
  12557. Camera.prototype._updateCache = function (ignoreParentClass) {
  12558. if (!ignoreParentClass) {
  12559. _super.prototype._updateCache.call(this);
  12560. }
  12561. var engine = this.getEngine();
  12562. this._cache.position.copyFrom(this.position);
  12563. this._cache.upVector.copyFrom(this.upVector);
  12564. this._cache.mode = this.mode;
  12565. this._cache.minZ = this.minZ;
  12566. this._cache.maxZ = this.maxZ;
  12567. this._cache.fov = this.fov;
  12568. this._cache.aspectRatio = engine.getAspectRatio(this);
  12569. this._cache.orthoLeft = this.orthoLeft;
  12570. this._cache.orthoRight = this.orthoRight;
  12571. this._cache.orthoBottom = this.orthoBottom;
  12572. this._cache.orthoTop = this.orthoTop;
  12573. this._cache.renderWidth = engine.getRenderWidth();
  12574. this._cache.renderHeight = engine.getRenderHeight();
  12575. };
  12576. Camera.prototype._updateFromScene = function () {
  12577. this.updateCache();
  12578. this.update();
  12579. };
  12580. // Synchronized
  12581. Camera.prototype._isSynchronized = function () {
  12582. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12583. };
  12584. Camera.prototype._isSynchronizedViewMatrix = function () {
  12585. if (!_super.prototype._isSynchronized.call(this))
  12586. return false;
  12587. return this._cache.position.equals(this.position)
  12588. && this._cache.upVector.equals(this.upVector)
  12589. && this.isSynchronizedWithParent();
  12590. };
  12591. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12592. var check = this._cache.mode === this.mode
  12593. && this._cache.minZ === this.minZ
  12594. && this._cache.maxZ === this.maxZ;
  12595. if (!check) {
  12596. return false;
  12597. }
  12598. var engine = this.getEngine();
  12599. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12600. check = this._cache.fov === this.fov
  12601. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12602. }
  12603. else {
  12604. check = this._cache.orthoLeft === this.orthoLeft
  12605. && this._cache.orthoRight === this.orthoRight
  12606. && this._cache.orthoBottom === this.orthoBottom
  12607. && this._cache.orthoTop === this.orthoTop
  12608. && this._cache.renderWidth === engine.getRenderWidth()
  12609. && this._cache.renderHeight === engine.getRenderHeight();
  12610. }
  12611. return check;
  12612. };
  12613. // Controls
  12614. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12615. };
  12616. Camera.prototype.detachControl = function (element) {
  12617. };
  12618. Camera.prototype.update = function () {
  12619. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12620. this._updateRigCameras();
  12621. }
  12622. this._checkInputs();
  12623. };
  12624. Camera.prototype._checkInputs = function () {
  12625. };
  12626. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12627. // invalidate framebuffer
  12628. if (this._postProcesses.length > 0) {
  12629. this._postProcesses[0].markTextureDirty();
  12630. }
  12631. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12632. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12633. var cam = this._rigCameras[i];
  12634. var rigPostProcess = cam._rigPostProcess;
  12635. // for VR rig, there does not have to be a post process
  12636. if (rigPostProcess) {
  12637. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12638. if (isPass) {
  12639. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12640. cam.isIntermediate = this._postProcesses.length === 0;
  12641. }
  12642. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12643. rigPostProcess.markTextureDirty();
  12644. }
  12645. else {
  12646. cam._postProcesses = this._postProcesses.slice(0);
  12647. }
  12648. }
  12649. };
  12650. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12651. if (insertAt === void 0) { insertAt = null; }
  12652. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12653. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12654. return 0;
  12655. }
  12656. if (insertAt == null || insertAt < 0) {
  12657. this._postProcesses.push(postProcess);
  12658. }
  12659. else {
  12660. this._postProcesses.splice(insertAt, 0, postProcess);
  12661. }
  12662. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12663. return this._postProcesses.indexOf(postProcess);
  12664. };
  12665. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12666. if (atIndices === void 0) { atIndices = null; }
  12667. var result = [];
  12668. var i;
  12669. var index;
  12670. if (!atIndices) {
  12671. var idx = this._postProcesses.indexOf(postProcess);
  12672. if (idx !== -1) {
  12673. this._postProcesses.splice(idx, 1);
  12674. }
  12675. }
  12676. else {
  12677. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12678. // iterate descending, so can just splice as we go
  12679. for (i = atIndices.length - 1; i >= 0; i--) {
  12680. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12681. result.push(i);
  12682. continue;
  12683. }
  12684. this._postProcesses.splice(index, 1);
  12685. }
  12686. }
  12687. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12688. return result;
  12689. };
  12690. Camera.prototype.getWorldMatrix = function () {
  12691. if (!this._worldMatrix) {
  12692. this._worldMatrix = BABYLON.Matrix.Identity();
  12693. }
  12694. var viewMatrix = this.getViewMatrix();
  12695. viewMatrix.invertToRef(this._worldMatrix);
  12696. return this._worldMatrix;
  12697. };
  12698. Camera.prototype._getViewMatrix = function () {
  12699. return BABYLON.Matrix.Identity();
  12700. };
  12701. Camera.prototype.getViewMatrix = function (force) {
  12702. this._computedViewMatrix = this._computeViewMatrix(force);
  12703. if (!force && this._isSynchronizedViewMatrix()) {
  12704. return this._computedViewMatrix;
  12705. }
  12706. this._refreshFrustumPlanes = true;
  12707. if (!this.parent || !this.parent.getWorldMatrix) {
  12708. this._globalPosition.copyFrom(this.position);
  12709. }
  12710. else {
  12711. if (!this._worldMatrix) {
  12712. this._worldMatrix = BABYLON.Matrix.Identity();
  12713. }
  12714. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12715. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12716. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12717. this._computedViewMatrix.invert();
  12718. this._markSyncedWithParent();
  12719. }
  12720. this._currentRenderId = this.getScene().getRenderId();
  12721. return this._computedViewMatrix;
  12722. };
  12723. Camera.prototype._computeViewMatrix = function (force) {
  12724. if (!force && this._isSynchronizedViewMatrix()) {
  12725. return this._computedViewMatrix;
  12726. }
  12727. this._computedViewMatrix = this._getViewMatrix();
  12728. this._currentRenderId = this.getScene().getRenderId();
  12729. return this._computedViewMatrix;
  12730. };
  12731. Camera.prototype.getProjectionMatrix = function (force) {
  12732. if (!force && this._isSynchronizedProjectionMatrix()) {
  12733. return this._projectionMatrix;
  12734. }
  12735. this._refreshFrustumPlanes = true;
  12736. var engine = this.getEngine();
  12737. var scene = this.getScene();
  12738. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12739. if (this.minZ <= 0) {
  12740. this.minZ = 0.1;
  12741. }
  12742. if (scene.useRightHandedSystem) {
  12743. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12744. }
  12745. else {
  12746. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12747. }
  12748. return this._projectionMatrix;
  12749. }
  12750. var halfWidth = engine.getRenderWidth() / 2.0;
  12751. var halfHeight = engine.getRenderHeight() / 2.0;
  12752. if (scene.useRightHandedSystem) {
  12753. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12754. }
  12755. else {
  12756. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12757. }
  12758. return this._projectionMatrix;
  12759. };
  12760. Camera.prototype.getTranformationMatrix = function () {
  12761. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12762. return this._transformMatrix;
  12763. };
  12764. Camera.prototype.updateFrustumPlanes = function () {
  12765. if (!this._refreshFrustumPlanes) {
  12766. return;
  12767. }
  12768. this.getTranformationMatrix();
  12769. if (!this._frustumPlanes) {
  12770. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12771. }
  12772. else {
  12773. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12774. }
  12775. this._refreshFrustumPlanes = false;
  12776. };
  12777. Camera.prototype.isInFrustum = function (target) {
  12778. this.updateFrustumPlanes();
  12779. return target.isInFrustum(this._frustumPlanes);
  12780. };
  12781. Camera.prototype.isCompletelyInFrustum = function (target) {
  12782. this.updateFrustumPlanes();
  12783. return target.isCompletelyInFrustum(this._frustumPlanes);
  12784. };
  12785. Camera.prototype.dispose = function () {
  12786. // Animations
  12787. this.getScene().stopAnimation(this);
  12788. // Remove from scene
  12789. this.getScene().removeCamera(this);
  12790. while (this._rigCameras.length > 0) {
  12791. this._rigCameras.pop().dispose();
  12792. }
  12793. // Postprocesses
  12794. for (var i = 0; i < this._postProcesses.length; ++i) {
  12795. this._postProcesses[i].dispose(this);
  12796. }
  12797. _super.prototype.dispose.call(this);
  12798. };
  12799. // ---- Camera rigs section ----
  12800. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12801. while (this._rigCameras.length > 0) {
  12802. this._rigCameras.pop().dispose();
  12803. }
  12804. this.cameraRigMode = mode;
  12805. this._cameraRigParams = {};
  12806. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12807. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12808. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12809. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12810. // create the rig cameras, unless none
  12811. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12812. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12813. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12814. }
  12815. switch (this.cameraRigMode) {
  12816. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12817. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12818. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12819. break;
  12820. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12821. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12822. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12823. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12824. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12825. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12826. break;
  12827. case Camera.RIG_MODE_VR:
  12828. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12829. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12830. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12831. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12832. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12833. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12834. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12835. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12836. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12837. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12838. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12839. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12840. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12841. if (metrics.compensateDistortion) {
  12842. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  12843. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  12844. }
  12845. break;
  12846. case Camera.RIG_MODE_WEBVR:
  12847. if (rigParams.vrDisplay) {
  12848. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  12849. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  12850. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12851. this._rigCameras[0].setCameraRigParameter("vrFieldOfView", leftEye.fieldOfView);
  12852. this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  12853. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12854. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  12855. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12856. this._rigCameras[1].setCameraRigParameter("vrFieldOfView", rightEye.fieldOfView);
  12857. this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  12858. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12859. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  12860. }
  12861. break;
  12862. }
  12863. this._cascadePostProcessesToRigCams();
  12864. this.
  12865. update();
  12866. };
  12867. Camera.prototype._getVRProjectionMatrix = function () {
  12868. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12869. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  12870. return this._projectionMatrix;
  12871. };
  12872. Camera.prototype._getWebVRProjectionMatrix = function () {
  12873. BABYLON.Matrix.PerspectiveFovWebVRToRef(this._cameraRigParams['vrFieldOfView'], this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12874. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams['vrOffsetMatrix'], this._projectionMatrix);
  12875. return this._projectionMatrix;
  12876. };
  12877. Camera.prototype.setCameraRigParameter = function (name, value) {
  12878. if (!this._cameraRigParams) {
  12879. this._cameraRigParams = {};
  12880. }
  12881. this._cameraRigParams[name] = value;
  12882. //provisionnally:
  12883. if (name === "interaxialDistance") {
  12884. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  12885. }
  12886. };
  12887. /**
  12888. * needs to be overridden by children so sub has required properties to be copied
  12889. */
  12890. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  12891. return null;
  12892. };
  12893. /**
  12894. * May need to be overridden by children
  12895. */
  12896. Camera.prototype._updateRigCameras = function () {
  12897. for (var i = 0; i < this._rigCameras.length; i++) {
  12898. this._rigCameras[i].minZ = this.minZ;
  12899. this._rigCameras[i].maxZ = this.maxZ;
  12900. this._rigCameras[i].fov = this.fov;
  12901. }
  12902. // only update viewport when ANAGLYPH
  12903. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  12904. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  12905. }
  12906. };
  12907. Camera.prototype._setupInputs = function () {
  12908. };
  12909. Camera.prototype.serialize = function () {
  12910. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12911. // Type
  12912. serializationObject.type = this.getTypeName();
  12913. // Parent
  12914. if (this.parent) {
  12915. serializationObject.parentId = this.parent.id;
  12916. }
  12917. if (this.inputs) {
  12918. this.inputs.serialize(serializationObject);
  12919. }
  12920. // Animations
  12921. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12922. serializationObject.ranges = this.serializeAnimationRanges();
  12923. return serializationObject;
  12924. };
  12925. Camera.prototype.getTypeName = function () {
  12926. return "Camera";
  12927. };
  12928. Camera.prototype.clone = function (name) {
  12929. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  12930. };
  12931. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  12932. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  12933. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  12934. switch (type) {
  12935. case "ArcRotateCamera":
  12936. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  12937. case "DeviceOrientationCamera":
  12938. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  12939. case "FollowCamera":
  12940. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  12941. case "ArcFollowCamera":
  12942. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  12943. case "GamepadCamera":
  12944. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  12945. case "TouchCamera":
  12946. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  12947. case "VirtualJoysticksCamera":
  12948. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  12949. case "WebVRFreeCamera":
  12950. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12951. case "VRDeviceOrientationFreeCamera":
  12952. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12953. case "AnaglyphArcRotateCamera":
  12954. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12955. case "AnaglyphFreeCamera":
  12956. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12957. case "AnaglyphGamepadCamera":
  12958. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12959. case "AnaglyphUniversalCamera":
  12960. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12961. case "StereoscopicArcRotateCamera":
  12962. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12963. case "StereoscopicFreeCamera":
  12964. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12965. case "StereoscopicGamepadCamera":
  12966. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12967. case "StereoscopicUniversalCamera":
  12968. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12969. case "FreeCamera":
  12970. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12971. default:
  12972. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12973. }
  12974. };
  12975. Camera.Parse = function (parsedCamera, scene) {
  12976. var type = parsedCamera.type;
  12977. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  12978. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  12979. // Parent
  12980. if (parsedCamera.parentId) {
  12981. camera._waitingParentId = parsedCamera.parentId;
  12982. }
  12983. //If camera has an input manager, let it parse inputs settings
  12984. if (camera.inputs) {
  12985. camera.inputs.parse(parsedCamera);
  12986. camera._setupInputs();
  12987. }
  12988. // Target
  12989. if (parsedCamera.target) {
  12990. if (camera.setTarget) {
  12991. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  12992. }
  12993. }
  12994. // Apply 3d rig, when found
  12995. if (parsedCamera.cameraRigMode) {
  12996. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  12997. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  12998. }
  12999. // Animations
  13000. if (parsedCamera.animations) {
  13001. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13002. var parsedAnimation = parsedCamera.animations[animationIndex];
  13003. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13004. }
  13005. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13006. }
  13007. if (parsedCamera.autoAnimate) {
  13008. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13009. }
  13010. return camera;
  13011. };
  13012. // Statics
  13013. Camera._PERSPECTIVE_CAMERA = 0;
  13014. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13015. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13016. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13017. Camera._RIG_MODE_NONE = 0;
  13018. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13019. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13020. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13021. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13022. Camera._RIG_MODE_VR = 20;
  13023. Camera._RIG_MODE_WEBVR = 21;
  13024. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13025. __decorate([
  13026. BABYLON.serializeAsVector3()
  13027. ], Camera.prototype, "position", void 0);
  13028. __decorate([
  13029. BABYLON.serializeAsVector3()
  13030. ], Camera.prototype, "upVector", void 0);
  13031. __decorate([
  13032. BABYLON.serialize()
  13033. ], Camera.prototype, "orthoLeft", void 0);
  13034. __decorate([
  13035. BABYLON.serialize()
  13036. ], Camera.prototype, "orthoRight", void 0);
  13037. __decorate([
  13038. BABYLON.serialize()
  13039. ], Camera.prototype, "orthoBottom", void 0);
  13040. __decorate([
  13041. BABYLON.serialize()
  13042. ], Camera.prototype, "orthoTop", void 0);
  13043. __decorate([
  13044. BABYLON.serialize()
  13045. ], Camera.prototype, "fov", void 0);
  13046. __decorate([
  13047. BABYLON.serialize()
  13048. ], Camera.prototype, "minZ", void 0);
  13049. __decorate([
  13050. BABYLON.serialize()
  13051. ], Camera.prototype, "maxZ", void 0);
  13052. __decorate([
  13053. BABYLON.serialize()
  13054. ], Camera.prototype, "inertia", void 0);
  13055. __decorate([
  13056. BABYLON.serialize()
  13057. ], Camera.prototype, "mode", void 0);
  13058. __decorate([
  13059. BABYLON.serialize()
  13060. ], Camera.prototype, "layerMask", void 0);
  13061. __decorate([
  13062. BABYLON.serialize()
  13063. ], Camera.prototype, "fovMode", void 0);
  13064. __decorate([
  13065. BABYLON.serialize()
  13066. ], Camera.prototype, "cameraRigMode", void 0);
  13067. __decorate([
  13068. BABYLON.serialize()
  13069. ], Camera.prototype, "interaxialDistance", void 0);
  13070. __decorate([
  13071. BABYLON.serialize()
  13072. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13073. return Camera;
  13074. })(BABYLON.Node);
  13075. BABYLON.Camera = Camera;
  13076. })(BABYLON || (BABYLON = {}));
  13077. var BABYLON;
  13078. (function (BABYLON) {
  13079. BABYLON.CameraInputTypes = {};
  13080. var CameraInputsManager = (function () {
  13081. function CameraInputsManager(camera) {
  13082. this.attached = {};
  13083. this.camera = camera;
  13084. this.checkInputs = function () { };
  13085. }
  13086. CameraInputsManager.prototype.add = function (input) {
  13087. var type = input.getSimpleName();
  13088. if (this.attached[type]) {
  13089. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13090. return;
  13091. }
  13092. this.attached[type] = input;
  13093. input.camera = this.camera;
  13094. //for checkInputs, we are dynamically creating a function
  13095. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13096. if (input.checkInputs) {
  13097. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13098. }
  13099. if (this.attachedElement) {
  13100. input.attachControl(this.attachedElement);
  13101. }
  13102. };
  13103. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13104. for (var cam in this.attached) {
  13105. var input = this.attached[cam];
  13106. if (input === inputToRemove) {
  13107. input.detachControl(this.attachedElement);
  13108. delete this.attached[cam];
  13109. this.rebuildInputCheck();
  13110. }
  13111. }
  13112. };
  13113. CameraInputsManager.prototype.removeByType = function (inputType) {
  13114. for (var cam in this.attached) {
  13115. var input = this.attached[cam];
  13116. if (input.getTypeName() === inputType) {
  13117. input.detachControl(this.attachedElement);
  13118. delete this.attached[cam];
  13119. this.rebuildInputCheck();
  13120. }
  13121. }
  13122. };
  13123. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13124. var current = this.checkInputs;
  13125. return function () {
  13126. current();
  13127. fn();
  13128. };
  13129. };
  13130. CameraInputsManager.prototype.attachInput = function (input) {
  13131. input.attachControl(this.attachedElement, this.noPreventDefault);
  13132. };
  13133. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13134. if (this.attachedElement) {
  13135. return;
  13136. }
  13137. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13138. this.attachedElement = element;
  13139. this.noPreventDefault = noPreventDefault;
  13140. for (var cam in this.attached) {
  13141. var input = this.attached[cam];
  13142. this.attached[cam].attachControl(element, noPreventDefault);
  13143. }
  13144. };
  13145. CameraInputsManager.prototype.detachElement = function (element) {
  13146. if (this.attachedElement !== element) {
  13147. return;
  13148. }
  13149. for (var cam in this.attached) {
  13150. var input = this.attached[cam];
  13151. this.attached[cam].detachControl(element);
  13152. }
  13153. this.attachedElement = null;
  13154. };
  13155. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13156. this.checkInputs = function () { };
  13157. for (var cam in this.attached) {
  13158. var input = this.attached[cam];
  13159. if (input.checkInputs) {
  13160. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13161. }
  13162. }
  13163. };
  13164. CameraInputsManager.prototype.clear = function () {
  13165. if (this.attachedElement) {
  13166. this.detachElement(this.attachedElement);
  13167. }
  13168. this.attached = {};
  13169. this.attachedElement = null;
  13170. this.checkInputs = function () { };
  13171. };
  13172. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13173. var inputs = {};
  13174. for (var cam in this.attached) {
  13175. var input = this.attached[cam];
  13176. var res = BABYLON.SerializationHelper.Serialize(input);
  13177. inputs[input.getTypeName()] = res;
  13178. }
  13179. serializedCamera.inputsmgr = inputs;
  13180. };
  13181. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13182. var parsedInputs = parsedCamera.inputsmgr;
  13183. if (parsedInputs) {
  13184. this.clear();
  13185. for (var n in parsedInputs) {
  13186. var construct = BABYLON.CameraInputTypes[n];
  13187. if (construct) {
  13188. var parsedinput = parsedInputs[n];
  13189. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13190. this.add(input);
  13191. }
  13192. }
  13193. }
  13194. else {
  13195. //2016-03-08 this part is for managing backward compatibility
  13196. for (var n in this.attached) {
  13197. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13198. if (construct) {
  13199. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13200. this.remove(this.attached[n]);
  13201. this.add(input);
  13202. }
  13203. }
  13204. }
  13205. };
  13206. return CameraInputsManager;
  13207. })();
  13208. BABYLON.CameraInputsManager = CameraInputsManager;
  13209. })(BABYLON || (BABYLON = {}));
  13210. var BABYLON;
  13211. (function (BABYLON) {
  13212. var FreeCameraMouseInput = (function () {
  13213. function FreeCameraMouseInput(touchEnabled) {
  13214. if (touchEnabled === void 0) { touchEnabled = true; }
  13215. this.touchEnabled = touchEnabled;
  13216. this.angularSensibility = 2000.0;
  13217. }
  13218. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13219. var _this = this;
  13220. if (!this._pointerInput) {
  13221. var camera = this.camera;
  13222. var engine = this.camera.getEngine();
  13223. this._pointerInput = function (p, s) {
  13224. var evt = p.event;
  13225. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13226. return;
  13227. }
  13228. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13229. try {
  13230. evt.srcElement.setPointerCapture(evt.pointerId);
  13231. }
  13232. catch (e) {
  13233. }
  13234. _this.previousPosition = {
  13235. x: evt.clientX,
  13236. y: evt.clientY
  13237. };
  13238. if (!noPreventDefault) {
  13239. evt.preventDefault();
  13240. element.focus();
  13241. }
  13242. }
  13243. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13244. try {
  13245. evt.srcElement.releasePointerCapture(evt.pointerId);
  13246. }
  13247. catch (e) {
  13248. }
  13249. _this.previousPosition = null;
  13250. if (!noPreventDefault) {
  13251. evt.preventDefault();
  13252. }
  13253. }
  13254. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13255. if (!_this.previousPosition && !engine.isPointerLock) {
  13256. return;
  13257. }
  13258. var offsetX;
  13259. var offsetY;
  13260. if (!engine.isPointerLock) {
  13261. offsetX = evt.clientX - _this.previousPosition.x;
  13262. offsetY = evt.clientY - _this.previousPosition.y;
  13263. }
  13264. else {
  13265. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13266. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13267. }
  13268. if (_this.camera.getScene().useRightHandedSystem) {
  13269. camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13270. }
  13271. else {
  13272. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13273. }
  13274. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13275. _this.previousPosition = {
  13276. x: evt.clientX,
  13277. y: evt.clientY
  13278. };
  13279. if (!noPreventDefault) {
  13280. evt.preventDefault();
  13281. }
  13282. }
  13283. };
  13284. }
  13285. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13286. };
  13287. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13288. if (this._observer && element) {
  13289. this.camera.getScene().onPointerObservable.remove(this._observer);
  13290. this._observer = null;
  13291. this.previousPosition = null;
  13292. }
  13293. };
  13294. FreeCameraMouseInput.prototype.getTypeName = function () {
  13295. return "FreeCameraMouseInput";
  13296. };
  13297. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13298. return "mouse";
  13299. };
  13300. __decorate([
  13301. BABYLON.serialize()
  13302. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13303. return FreeCameraMouseInput;
  13304. })();
  13305. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13306. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13307. })(BABYLON || (BABYLON = {}));
  13308. var BABYLON;
  13309. (function (BABYLON) {
  13310. var FreeCameraKeyboardMoveInput = (function () {
  13311. function FreeCameraKeyboardMoveInput() {
  13312. this._keys = [];
  13313. this.keysUp = [38];
  13314. this.keysDown = [40];
  13315. this.keysLeft = [37];
  13316. this.keysRight = [39];
  13317. }
  13318. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13319. var _this = this;
  13320. if (!this._onKeyDown) {
  13321. element.tabIndex = 1;
  13322. this._onKeyDown = function (evt) {
  13323. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13324. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13325. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13326. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13327. var index = _this._keys.indexOf(evt.keyCode);
  13328. if (index === -1) {
  13329. _this._keys.push(evt.keyCode);
  13330. }
  13331. if (!noPreventDefault) {
  13332. evt.preventDefault();
  13333. }
  13334. }
  13335. };
  13336. this._onKeyUp = function (evt) {
  13337. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13338. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13339. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13340. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13341. var index = _this._keys.indexOf(evt.keyCode);
  13342. if (index >= 0) {
  13343. _this._keys.splice(index, 1);
  13344. }
  13345. if (!noPreventDefault) {
  13346. evt.preventDefault();
  13347. }
  13348. }
  13349. };
  13350. element.addEventListener("keydown", this._onKeyDown, false);
  13351. element.addEventListener("keyup", this._onKeyUp, false);
  13352. BABYLON.Tools.RegisterTopRootEvents([
  13353. { name: "blur", handler: this._onLostFocus }
  13354. ]);
  13355. }
  13356. };
  13357. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13358. if (this._onKeyDown) {
  13359. element.removeEventListener("keydown", this._onKeyDown);
  13360. element.removeEventListener("keyup", this._onKeyUp);
  13361. BABYLON.Tools.UnregisterTopRootEvents([
  13362. { name: "blur", handler: this._onLostFocus }
  13363. ]);
  13364. this._keys = [];
  13365. this._onKeyDown = null;
  13366. this._onKeyUp = null;
  13367. }
  13368. };
  13369. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13370. if (this._onKeyDown) {
  13371. var camera = this.camera;
  13372. // Keyboard
  13373. for (var index = 0; index < this._keys.length; index++) {
  13374. var keyCode = this._keys[index];
  13375. var speed = camera._computeLocalCameraSpeed();
  13376. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13377. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13378. }
  13379. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13380. camera._localDirection.copyFromFloats(0, 0, speed);
  13381. }
  13382. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13383. camera._localDirection.copyFromFloats(speed, 0, 0);
  13384. }
  13385. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13386. camera._localDirection.copyFromFloats(0, 0, -speed);
  13387. }
  13388. if (camera.getScene().useRightHandedSystem) {
  13389. camera._localDirection.z *= -1;
  13390. }
  13391. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13392. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13393. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13394. }
  13395. }
  13396. };
  13397. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13398. return "FreeCameraKeyboardMoveInput";
  13399. };
  13400. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13401. this._keys = [];
  13402. };
  13403. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13404. return "keyboard";
  13405. };
  13406. __decorate([
  13407. BABYLON.serialize()
  13408. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13409. __decorate([
  13410. BABYLON.serialize()
  13411. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13412. __decorate([
  13413. BABYLON.serialize()
  13414. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13415. __decorate([
  13416. BABYLON.serialize()
  13417. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13418. return FreeCameraKeyboardMoveInput;
  13419. })();
  13420. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13421. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13422. })(BABYLON || (BABYLON = {}));
  13423. var BABYLON;
  13424. (function (BABYLON) {
  13425. var FreeCameraTouchInput = (function () {
  13426. function FreeCameraTouchInput() {
  13427. this._offsetX = null;
  13428. this._offsetY = null;
  13429. this._pointerCount = 0;
  13430. this._pointerPressed = [];
  13431. this.touchAngularSensibility = 200000.0;
  13432. this.touchMoveSensibility = 250.0;
  13433. }
  13434. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13435. var _this = this;
  13436. var previousPosition;
  13437. if (this._pointerInput === undefined) {
  13438. this._onLostFocus = function (evt) {
  13439. _this._offsetX = null;
  13440. _this._offsetY = null;
  13441. };
  13442. this._pointerInput = function (p, s) {
  13443. var evt = p.event;
  13444. if (evt.pointerType === "mouse") {
  13445. return;
  13446. }
  13447. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13448. if (!noPreventDefault) {
  13449. evt.preventDefault();
  13450. }
  13451. _this._pointerPressed.push(evt.pointerId);
  13452. if (_this._pointerPressed.length !== 1) {
  13453. return;
  13454. }
  13455. previousPosition = {
  13456. x: evt.clientX,
  13457. y: evt.clientY
  13458. };
  13459. }
  13460. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13461. if (!noPreventDefault) {
  13462. evt.preventDefault();
  13463. }
  13464. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13465. if (index === -1) {
  13466. return;
  13467. }
  13468. _this._pointerPressed.splice(index, 1);
  13469. if (index != 0) {
  13470. return;
  13471. }
  13472. previousPosition = null;
  13473. _this._offsetX = null;
  13474. _this._offsetY = null;
  13475. }
  13476. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13477. if (!noPreventDefault) {
  13478. evt.preventDefault();
  13479. }
  13480. if (!previousPosition) {
  13481. return;
  13482. }
  13483. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13484. if (index != 0) {
  13485. return;
  13486. }
  13487. _this._offsetX = evt.clientX - previousPosition.x;
  13488. _this._offsetY = -(evt.clientY - previousPosition.y);
  13489. }
  13490. };
  13491. }
  13492. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13493. element.addEventListener("blur", this._onLostFocus);
  13494. };
  13495. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13496. if (this._pointerInput && element) {
  13497. this.camera.getScene().onPointerObservable.remove(this._observer);
  13498. this._observer = null;
  13499. element.removeEventListener("blur", this._onLostFocus);
  13500. this._onLostFocus = null;
  13501. this._pointerPressed = [];
  13502. this._offsetX = null;
  13503. this._offsetY = null;
  13504. this._pointerCount = 0;
  13505. }
  13506. };
  13507. FreeCameraTouchInput.prototype.checkInputs = function () {
  13508. if (this._offsetX) {
  13509. var camera = this.camera;
  13510. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13511. if (this._pointerPressed.length > 1) {
  13512. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13513. }
  13514. else {
  13515. var speed = camera._computeLocalCameraSpeed();
  13516. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13517. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13518. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13519. }
  13520. }
  13521. };
  13522. FreeCameraTouchInput.prototype.getTypeName = function () {
  13523. return "FreeCameraTouchInput";
  13524. };
  13525. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13526. return "touch";
  13527. };
  13528. __decorate([
  13529. BABYLON.serialize()
  13530. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13531. __decorate([
  13532. BABYLON.serialize()
  13533. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13534. return FreeCameraTouchInput;
  13535. })();
  13536. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13537. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13538. })(BABYLON || (BABYLON = {}));
  13539. var BABYLON;
  13540. (function (BABYLON) {
  13541. var FreeCameraDeviceOrientationInput = (function () {
  13542. function FreeCameraDeviceOrientationInput() {
  13543. var _this = this;
  13544. this._screenOrientationAngle = 0;
  13545. this._screenQuaternion = new BABYLON.Quaternion();
  13546. this._alpha = 0;
  13547. this._beta = 0;
  13548. this._gamma = 0;
  13549. this._orientationChanged = function () {
  13550. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13551. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13552. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13553. };
  13554. this._deviceOrientation = function (evt) {
  13555. _this._alpha = evt.alpha;
  13556. _this._beta = evt.beta;
  13557. _this._gamma = evt.gamma;
  13558. };
  13559. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13560. this._orientationChanged();
  13561. }
  13562. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13563. get: function () {
  13564. return this._camera;
  13565. },
  13566. set: function (camera) {
  13567. this._camera = camera;
  13568. if (!this._camera.rotationQuaternion)
  13569. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13570. },
  13571. enumerable: true,
  13572. configurable: true
  13573. });
  13574. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13575. window.addEventListener("orientationchange", this._orientationChanged);
  13576. window.addEventListener("deviceorientation", this._deviceOrientation);
  13577. //In certain cases, the attach control is called AFTER orientation was changed,
  13578. //So this is needed.
  13579. this._orientationChanged();
  13580. };
  13581. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13582. window.removeEventListener("orientationchange", this._orientationChanged);
  13583. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13584. };
  13585. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13586. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13587. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13588. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13589. //Mirror on XY Plane
  13590. this._camera.rotationQuaternion.z *= -1;
  13591. this._camera.rotationQuaternion.w *= -1;
  13592. };
  13593. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13594. return "FreeCameraDeviceOrientationInput";
  13595. };
  13596. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13597. return "deviceOrientation";
  13598. };
  13599. return FreeCameraDeviceOrientationInput;
  13600. })();
  13601. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13602. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13603. })(BABYLON || (BABYLON = {}));
  13604. var BABYLON;
  13605. (function (BABYLON) {
  13606. var FreeCameraGamepadInput = (function () {
  13607. function FreeCameraGamepadInput() {
  13608. this.gamepadAngularSensibility = 200;
  13609. this.gamepadMoveSensibility = 40;
  13610. }
  13611. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13612. var _this = this;
  13613. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13614. };
  13615. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13616. if (this._gamepads) {
  13617. this._gamepads.dispose();
  13618. }
  13619. this.gamepad = null;
  13620. };
  13621. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13622. if (this.gamepad) {
  13623. var camera = this.camera;
  13624. var LSValues = this.gamepad.leftStick;
  13625. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13626. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13627. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13628. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13629. var RSValues = this.gamepad.rightStick;
  13630. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13631. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13632. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13633. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13634. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13635. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13636. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13637. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13638. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13639. }
  13640. };
  13641. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13642. // Only the first gamepad can control the camera
  13643. if (gamepad.index === 0) {
  13644. this.gamepad = gamepad;
  13645. }
  13646. };
  13647. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13648. return "FreeCameraGamepadInput";
  13649. };
  13650. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13651. return "gamepad";
  13652. };
  13653. __decorate([
  13654. BABYLON.serialize()
  13655. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13656. __decorate([
  13657. BABYLON.serialize()
  13658. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13659. return FreeCameraGamepadInput;
  13660. })();
  13661. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13662. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13663. })(BABYLON || (BABYLON = {}));
  13664. var BABYLON;
  13665. (function (BABYLON) {
  13666. var ArcRotateCameraKeyboardMoveInput = (function () {
  13667. function ArcRotateCameraKeyboardMoveInput() {
  13668. this._keys = [];
  13669. this.keysUp = [38];
  13670. this.keysDown = [40];
  13671. this.keysLeft = [37];
  13672. this.keysRight = [39];
  13673. }
  13674. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13675. var _this = this;
  13676. element.tabIndex = 1;
  13677. this._onKeyDown = function (evt) {
  13678. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13679. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13680. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13681. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13682. var index = _this._keys.indexOf(evt.keyCode);
  13683. if (index === -1) {
  13684. _this._keys.push(evt.keyCode);
  13685. }
  13686. if (evt.preventDefault) {
  13687. if (!noPreventDefault) {
  13688. evt.preventDefault();
  13689. }
  13690. }
  13691. }
  13692. };
  13693. this._onKeyUp = function (evt) {
  13694. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13695. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13696. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13697. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13698. var index = _this._keys.indexOf(evt.keyCode);
  13699. if (index >= 0) {
  13700. _this._keys.splice(index, 1);
  13701. }
  13702. if (evt.preventDefault) {
  13703. if (!noPreventDefault) {
  13704. evt.preventDefault();
  13705. }
  13706. }
  13707. }
  13708. };
  13709. this._onLostFocus = function () {
  13710. _this._keys = [];
  13711. };
  13712. element.addEventListener("keydown", this._onKeyDown, false);
  13713. element.addEventListener("keyup", this._onKeyUp, false);
  13714. BABYLON.Tools.RegisterTopRootEvents([
  13715. { name: "blur", handler: this._onLostFocus }
  13716. ]);
  13717. };
  13718. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13719. if (element) {
  13720. element.removeEventListener("keydown", this._onKeyDown);
  13721. element.removeEventListener("keyup", this._onKeyUp);
  13722. }
  13723. BABYLON.Tools.UnregisterTopRootEvents([
  13724. { name: "blur", handler: this._onLostFocus }
  13725. ]);
  13726. this._keys = [];
  13727. this._onKeyDown = null;
  13728. this._onKeyUp = null;
  13729. this._onLostFocus = null;
  13730. };
  13731. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13732. if (this._onKeyDown) {
  13733. var camera = this.camera;
  13734. for (var index = 0; index < this._keys.length; index++) {
  13735. var keyCode = this._keys[index];
  13736. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13737. camera.inertialAlphaOffset -= 0.01;
  13738. }
  13739. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13740. camera.inertialBetaOffset -= 0.01;
  13741. }
  13742. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13743. camera.inertialAlphaOffset += 0.01;
  13744. }
  13745. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13746. camera.inertialBetaOffset += 0.01;
  13747. }
  13748. }
  13749. }
  13750. };
  13751. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13752. return "ArcRotateCameraKeyboardMoveInput";
  13753. };
  13754. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13755. return "keyboard";
  13756. };
  13757. __decorate([
  13758. BABYLON.serialize()
  13759. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13760. __decorate([
  13761. BABYLON.serialize()
  13762. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13763. __decorate([
  13764. BABYLON.serialize()
  13765. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13766. __decorate([
  13767. BABYLON.serialize()
  13768. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13769. return ArcRotateCameraKeyboardMoveInput;
  13770. })();
  13771. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13772. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13773. })(BABYLON || (BABYLON = {}));
  13774. var BABYLON;
  13775. (function (BABYLON) {
  13776. var ArcRotateCameraMouseWheelInput = (function () {
  13777. function ArcRotateCameraMouseWheelInput() {
  13778. this.wheelPrecision = 3.0;
  13779. }
  13780. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13781. var _this = this;
  13782. this._wheel = function (p, s) {
  13783. //sanity check - this should be a PointerWheel event.
  13784. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13785. return;
  13786. var event = p.event;
  13787. var delta = 0;
  13788. if (event.wheelDelta) {
  13789. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13790. }
  13791. else if (event.detail) {
  13792. delta = -event.detail / _this.wheelPrecision;
  13793. }
  13794. if (delta)
  13795. _this.camera.inertialRadiusOffset += delta;
  13796. if (event.preventDefault) {
  13797. if (!noPreventDefault) {
  13798. event.preventDefault();
  13799. }
  13800. }
  13801. };
  13802. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13803. };
  13804. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13805. if (this._observer && element) {
  13806. this.camera.getScene().onPointerObservable.remove(this._observer);
  13807. this._observer = null;
  13808. this._wheel = null;
  13809. }
  13810. };
  13811. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13812. return "ArcRotateCameraMouseWheelInput";
  13813. };
  13814. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13815. return "mousewheel";
  13816. };
  13817. __decorate([
  13818. BABYLON.serialize()
  13819. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13820. return ArcRotateCameraMouseWheelInput;
  13821. })();
  13822. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13823. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13824. })(BABYLON || (BABYLON = {}));
  13825. var BABYLON;
  13826. (function (BABYLON) {
  13827. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13828. var ArcRotateCameraPointersInput = (function () {
  13829. function ArcRotateCameraPointersInput() {
  13830. this.angularSensibilityX = 1000.0;
  13831. this.angularSensibilityY = 1000.0;
  13832. this.pinchPrecision = 6.0;
  13833. this.panningSensibility = 50.0;
  13834. this._isPanClick = false;
  13835. this.pinchInwards = true;
  13836. }
  13837. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  13838. var _this = this;
  13839. var engine = this.camera.getEngine();
  13840. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  13841. var pointA, pointB;
  13842. var previousPinchDistance = 0;
  13843. this._pointerInput = function (p, s) {
  13844. var evt = p.event;
  13845. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13846. try {
  13847. evt.srcElement.setPointerCapture(evt.pointerId);
  13848. }
  13849. catch (e) {
  13850. }
  13851. // Manage panning with pan button click
  13852. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  13853. // manage pointers
  13854. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  13855. if (pointA === undefined) {
  13856. pointA = cacheSoloPointer;
  13857. }
  13858. else if (pointB === undefined) {
  13859. pointB = cacheSoloPointer;
  13860. }
  13861. if (!noPreventDefault) {
  13862. evt.preventDefault();
  13863. element.focus();
  13864. }
  13865. }
  13866. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13867. try {
  13868. evt.srcElement.releasePointerCapture(evt.pointerId);
  13869. }
  13870. catch (e) {
  13871. }
  13872. cacheSoloPointer = null;
  13873. previousPinchDistance = 0;
  13874. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  13875. //but emptying completly pointers collection is required to fix a bug on iPhone :
  13876. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  13877. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  13878. pointA = pointB = undefined;
  13879. if (!noPreventDefault) {
  13880. evt.preventDefault();
  13881. }
  13882. }
  13883. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13884. if (!noPreventDefault) {
  13885. evt.preventDefault();
  13886. }
  13887. // One button down
  13888. if (pointA && pointB === undefined) {
  13889. if (_this.panningSensibility !== 0 &&
  13890. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  13891. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  13892. _this.camera
  13893. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  13894. _this.camera
  13895. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  13896. }
  13897. else {
  13898. var offsetX = evt.clientX - cacheSoloPointer.x;
  13899. var offsetY = evt.clientY - cacheSoloPointer.y;
  13900. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13901. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13902. }
  13903. cacheSoloPointer.x = evt.clientX;
  13904. cacheSoloPointer.y = evt.clientY;
  13905. }
  13906. else if (pointA && pointB) {
  13907. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  13908. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  13909. ed.x = evt.clientX;
  13910. ed.y = evt.clientY;
  13911. var direction = _this.pinchInwards ? 1 : -1;
  13912. var distX = pointA.x - pointB.x;
  13913. var distY = pointA.y - pointB.y;
  13914. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  13915. if (previousPinchDistance === 0) {
  13916. previousPinchDistance = pinchSquaredDistance;
  13917. return;
  13918. }
  13919. if (pinchSquaredDistance !== previousPinchDistance) {
  13920. _this.camera
  13921. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  13922. (_this.pinchPrecision *
  13923. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  13924. direction);
  13925. previousPinchDistance = pinchSquaredDistance;
  13926. }
  13927. }
  13928. }
  13929. };
  13930. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13931. this._onContextMenu = function (evt) {
  13932. evt.preventDefault();
  13933. };
  13934. if (!this.camera._useCtrlForPanning) {
  13935. element.addEventListener("contextmenu", this._onContextMenu, false);
  13936. }
  13937. this._onLostFocus = function () {
  13938. //this._keys = [];
  13939. pointA = pointB = undefined;
  13940. previousPinchDistance = 0;
  13941. cacheSoloPointer = null;
  13942. };
  13943. this._onMouseMove = function (evt) {
  13944. if (!engine.isPointerLock) {
  13945. return;
  13946. }
  13947. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13948. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13949. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13950. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13951. if (!noPreventDefault) {
  13952. evt.preventDefault();
  13953. }
  13954. };
  13955. this._onGestureStart = function (e) {
  13956. if (window.MSGesture === undefined) {
  13957. return;
  13958. }
  13959. if (!_this._MSGestureHandler) {
  13960. _this._MSGestureHandler = new MSGesture();
  13961. _this._MSGestureHandler.target = element;
  13962. }
  13963. _this._MSGestureHandler.addPointer(e.pointerId);
  13964. };
  13965. this._onGesture = function (e) {
  13966. _this.camera.radius *= e.scale;
  13967. if (e.preventDefault) {
  13968. if (!noPreventDefault) {
  13969. e.stopPropagation();
  13970. e.preventDefault();
  13971. }
  13972. }
  13973. };
  13974. element.addEventListener("mousemove", this._onMouseMove, false);
  13975. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  13976. element.addEventListener("MSGestureChange", this._onGesture, false);
  13977. element.addEventListener("keydown", this._onKeyDown, false);
  13978. element.addEventListener("keyup", this._onKeyUp, false);
  13979. BABYLON.Tools.RegisterTopRootEvents([
  13980. { name: "blur", handler: this._onLostFocus }
  13981. ]);
  13982. };
  13983. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  13984. if (element && this._observer) {
  13985. this.camera.getScene().onPointerObservable.remove(this._observer);
  13986. this._observer = null;
  13987. element.removeEventListener("contextmenu", this._onContextMenu);
  13988. element.removeEventListener("mousemove", this._onMouseMove);
  13989. element.removeEventListener("MSPointerDown", this._onGestureStart);
  13990. element.removeEventListener("MSGestureChange", this._onGesture);
  13991. element.removeEventListener("keydown", this._onKeyDown);
  13992. element.removeEventListener("keyup", this._onKeyUp);
  13993. this._isPanClick = false;
  13994. this.pinchInwards = true;
  13995. this._onKeyDown = null;
  13996. this._onKeyUp = null;
  13997. this._onMouseMove = null;
  13998. this._onGestureStart = null;
  13999. this._onGesture = null;
  14000. this._MSGestureHandler = null;
  14001. this._onLostFocus = null;
  14002. this._onContextMenu = null;
  14003. }
  14004. BABYLON.Tools.UnregisterTopRootEvents([
  14005. { name: "blur", handler: this._onLostFocus }
  14006. ]);
  14007. };
  14008. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14009. return "ArcRotateCameraPointersInput";
  14010. };
  14011. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14012. return "pointers";
  14013. };
  14014. __decorate([
  14015. BABYLON.serialize()
  14016. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14017. __decorate([
  14018. BABYLON.serialize()
  14019. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14020. __decorate([
  14021. BABYLON.serialize()
  14022. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14023. __decorate([
  14024. BABYLON.serialize()
  14025. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14026. return ArcRotateCameraPointersInput;
  14027. })();
  14028. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14029. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14030. })(BABYLON || (BABYLON = {}));
  14031. var BABYLON;
  14032. (function (BABYLON) {
  14033. var ArcRotateCameraGamepadInput = (function () {
  14034. function ArcRotateCameraGamepadInput() {
  14035. this.gamepadRotationSensibility = 80;
  14036. this.gamepadMoveSensibility = 40;
  14037. }
  14038. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14039. var _this = this;
  14040. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14041. };
  14042. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14043. if (this._gamepads) {
  14044. this._gamepads.dispose();
  14045. }
  14046. this.gamepad = null;
  14047. };
  14048. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14049. if (this.gamepad) {
  14050. var camera = this.camera;
  14051. var RSValues = this.gamepad.rightStick;
  14052. if (RSValues.x != 0) {
  14053. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14054. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14055. camera.inertialAlphaOffset += normalizedRX;
  14056. }
  14057. }
  14058. if (RSValues.y != 0) {
  14059. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14060. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14061. camera.inertialBetaOffset += normalizedRY;
  14062. }
  14063. }
  14064. var LSValues = this.gamepad.leftStick;
  14065. if (LSValues.y != 0) {
  14066. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14067. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14068. this.camera.inertialRadiusOffset -= normalizedLY;
  14069. }
  14070. }
  14071. }
  14072. };
  14073. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14074. // Only the first gamepad can control the camera
  14075. if (gamepad.index === 0) {
  14076. this.gamepad = gamepad;
  14077. }
  14078. };
  14079. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14080. return "ArcRotateCameraGamepadInput";
  14081. };
  14082. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14083. return "gamepad";
  14084. };
  14085. __decorate([
  14086. BABYLON.serialize()
  14087. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14088. __decorate([
  14089. BABYLON.serialize()
  14090. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14091. return ArcRotateCameraGamepadInput;
  14092. })();
  14093. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14094. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14095. })(BABYLON || (BABYLON = {}));
  14096. var BABYLON;
  14097. (function (BABYLON) {
  14098. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14099. function ArcRotateCameraVRDeviceOrientationInput() {
  14100. this.alphaCorrection = 1;
  14101. this.betaCorrection = 1;
  14102. this.gammaCorrection = 1;
  14103. this._alpha = 0;
  14104. this._beta = 0;
  14105. this._gamma = 0;
  14106. this._dirty = false;
  14107. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14108. }
  14109. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14110. this.camera.attachControl(element, noPreventDefault);
  14111. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14112. };
  14113. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14114. var camera = this.camera;
  14115. this._alpha = +evt.alpha | 0;
  14116. this._beta = +evt.beta | 0;
  14117. this._gamma = +evt.gamma | 0;
  14118. this._dirty = true;
  14119. };
  14120. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14121. if (this._dirty) {
  14122. this._dirty = false;
  14123. if (this._gamma < 0) {
  14124. this._gamma = 180 + this._gamma;
  14125. }
  14126. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14127. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14128. }
  14129. };
  14130. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14131. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14132. };
  14133. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14134. return "ArcRotateCameraVRDeviceOrientationInput";
  14135. };
  14136. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14137. return "VRDeviceOrientation";
  14138. };
  14139. return ArcRotateCameraVRDeviceOrientationInput;
  14140. })();
  14141. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14142. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14143. })(BABYLON || (BABYLON = {}));
  14144. var BABYLON;
  14145. (function (BABYLON) {
  14146. var TargetCamera = (function (_super) {
  14147. __extends(TargetCamera, _super);
  14148. function TargetCamera(name, position, scene) {
  14149. _super.call(this, name, position, scene);
  14150. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14151. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14152. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14153. this.speed = 2.0;
  14154. this.noRotationConstraint = false;
  14155. this.lockedTarget = null;
  14156. this._currentTarget = BABYLON.Vector3.Zero();
  14157. this._viewMatrix = BABYLON.Matrix.Zero();
  14158. this._camMatrix = BABYLON.Matrix.Zero();
  14159. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14160. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14161. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14162. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14163. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14164. this._lookAtTemp = BABYLON.Matrix.Zero();
  14165. this._tempMatrix = BABYLON.Matrix.Zero();
  14166. }
  14167. TargetCamera.prototype.getFrontPosition = function (distance) {
  14168. var direction = this.getTarget().subtract(this.position);
  14169. direction.normalize();
  14170. direction.scaleInPlace(distance);
  14171. return this.globalPosition.add(direction);
  14172. };
  14173. TargetCamera.prototype._getLockedTargetPosition = function () {
  14174. if (!this.lockedTarget) {
  14175. return null;
  14176. }
  14177. return this.lockedTarget.position || this.lockedTarget;
  14178. };
  14179. // Cache
  14180. TargetCamera.prototype._initCache = function () {
  14181. _super.prototype._initCache.call(this);
  14182. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14183. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14184. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14185. };
  14186. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14187. if (!ignoreParentClass) {
  14188. _super.prototype._updateCache.call(this);
  14189. }
  14190. var lockedTargetPosition = this._getLockedTargetPosition();
  14191. if (!lockedTargetPosition) {
  14192. this._cache.lockedTarget = null;
  14193. }
  14194. else {
  14195. if (!this._cache.lockedTarget) {
  14196. this._cache.lockedTarget = lockedTargetPosition.clone();
  14197. }
  14198. else {
  14199. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14200. }
  14201. }
  14202. this._cache.rotation.copyFrom(this.rotation);
  14203. if (this.rotationQuaternion)
  14204. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14205. };
  14206. // Synchronized
  14207. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14208. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14209. return false;
  14210. }
  14211. var lockedTargetPosition = this._getLockedTargetPosition();
  14212. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14213. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14214. };
  14215. // Methods
  14216. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14217. var engine = this.getEngine();
  14218. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14219. };
  14220. // Target
  14221. TargetCamera.prototype.setTarget = function (target) {
  14222. this.upVector.normalize();
  14223. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14224. this._camMatrix.invert();
  14225. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14226. var vDir = target.subtract(this.position);
  14227. if (vDir.x >= 0.0) {
  14228. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14229. }
  14230. else {
  14231. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14232. }
  14233. this.rotation.z = 0;
  14234. if (isNaN(this.rotation.x)) {
  14235. this.rotation.x = 0;
  14236. }
  14237. if (isNaN(this.rotation.y)) {
  14238. this.rotation.y = 0;
  14239. }
  14240. if (isNaN(this.rotation.z)) {
  14241. this.rotation.z = 0;
  14242. }
  14243. if (this.rotationQuaternion) {
  14244. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14245. }
  14246. };
  14247. TargetCamera.prototype.getTarget = function () {
  14248. return this._currentTarget;
  14249. };
  14250. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14251. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14252. };
  14253. TargetCamera.prototype._updatePosition = function () {
  14254. this.position.addInPlace(this.cameraDirection);
  14255. };
  14256. TargetCamera.prototype._checkInputs = function () {
  14257. var needToMove = this._decideIfNeedsToMove();
  14258. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14259. // Move
  14260. if (needToMove) {
  14261. this._updatePosition();
  14262. }
  14263. // Rotate
  14264. if (needToRotate) {
  14265. this.rotation.x += this.cameraRotation.x;
  14266. this.rotation.y += this.cameraRotation.y;
  14267. if (!this.noRotationConstraint) {
  14268. var limit = (Math.PI / 2) * 0.95;
  14269. if (this.rotation.x > limit)
  14270. this.rotation.x = limit;
  14271. if (this.rotation.x < -limit)
  14272. this.rotation.x = -limit;
  14273. }
  14274. }
  14275. // Inertia
  14276. if (needToMove) {
  14277. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14278. this.cameraDirection.x = 0;
  14279. }
  14280. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14281. this.cameraDirection.y = 0;
  14282. }
  14283. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14284. this.cameraDirection.z = 0;
  14285. }
  14286. this.cameraDirection.scaleInPlace(this.inertia);
  14287. }
  14288. if (needToRotate) {
  14289. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14290. this.cameraRotation.x = 0;
  14291. }
  14292. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14293. this.cameraRotation.y = 0;
  14294. }
  14295. this.cameraRotation.scaleInPlace(this.inertia);
  14296. }
  14297. _super.prototype._checkInputs.call(this);
  14298. };
  14299. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14300. if (this.rotationQuaternion) {
  14301. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14302. //update the up vector!
  14303. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14304. }
  14305. else {
  14306. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14307. }
  14308. };
  14309. TargetCamera.prototype._getViewMatrix = function () {
  14310. if (!this.lockedTarget) {
  14311. // Compute
  14312. this._updateCameraRotationMatrix();
  14313. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14314. // Computing target and final matrix
  14315. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14316. }
  14317. else {
  14318. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14319. }
  14320. if (this.getScene().useRightHandedSystem) {
  14321. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14322. }
  14323. else {
  14324. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14325. }
  14326. return this._viewMatrix;
  14327. };
  14328. /**
  14329. * @override
  14330. * Override Camera.createRigCamera
  14331. */
  14332. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14333. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14334. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14335. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14336. if (!this.rotationQuaternion) {
  14337. this.rotationQuaternion = new BABYLON.Quaternion();
  14338. }
  14339. rigCamera._cameraRigParams = {};
  14340. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14341. }
  14342. return rigCamera;
  14343. }
  14344. return null;
  14345. };
  14346. /**
  14347. * @override
  14348. * Override Camera._updateRigCameras
  14349. */
  14350. TargetCamera.prototype._updateRigCameras = function () {
  14351. var camLeft = this._rigCameras[0];
  14352. var camRight = this._rigCameras[1];
  14353. switch (this.cameraRigMode) {
  14354. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14355. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14356. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14357. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14358. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14359. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14360. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14361. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14362. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14363. camLeft.setTarget(this.getTarget());
  14364. camRight.setTarget(this.getTarget());
  14365. break;
  14366. case BABYLON.Camera.RIG_MODE_VR:
  14367. case BABYLON.Camera.RIG_MODE_WEBVR:
  14368. if (camLeft.rotationQuaternion) {
  14369. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14370. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14371. }
  14372. else {
  14373. camLeft.rotation.copyFrom(this.rotation);
  14374. camRight.rotation.copyFrom(this.rotation);
  14375. }
  14376. camLeft.position.copyFrom(this.position);
  14377. camRight.position.copyFrom(this.position);
  14378. break;
  14379. }
  14380. _super.prototype._updateRigCameras.call(this);
  14381. };
  14382. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14383. if (!this._rigCamTransformMatrix) {
  14384. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14385. }
  14386. var target = this.getTarget();
  14387. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14388. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14389. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14390. };
  14391. TargetCamera.prototype.getTypeName = function () {
  14392. return "TargetCamera";
  14393. };
  14394. __decorate([
  14395. BABYLON.serializeAsVector3()
  14396. ], TargetCamera.prototype, "rotation", void 0);
  14397. __decorate([
  14398. BABYLON.serialize()
  14399. ], TargetCamera.prototype, "speed", void 0);
  14400. __decorate([
  14401. BABYLON.serializeAsMeshReference("lockedTargetId")
  14402. ], TargetCamera.prototype, "lockedTarget", void 0);
  14403. return TargetCamera;
  14404. })(BABYLON.Camera);
  14405. BABYLON.TargetCamera = TargetCamera;
  14406. })(BABYLON || (BABYLON = {}));
  14407. var BABYLON;
  14408. (function (BABYLON) {
  14409. var FreeCamera = (function (_super) {
  14410. __extends(FreeCamera, _super);
  14411. function FreeCamera(name, position, scene) {
  14412. var _this = this;
  14413. _super.call(this, name, position, scene);
  14414. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14415. this.checkCollisions = false;
  14416. this.applyGravity = false;
  14417. this._collider = new BABYLON.Collider();
  14418. this._needMoveForGravity = false;
  14419. this._oldPosition = BABYLON.Vector3.Zero();
  14420. this._diffPosition = BABYLON.Vector3.Zero();
  14421. this._newPosition = BABYLON.Vector3.Zero();
  14422. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14423. if (collidedMesh === void 0) { collidedMesh = null; }
  14424. //TODO move this to the collision coordinator!
  14425. if (_this.getScene().workerCollisions)
  14426. newPosition.multiplyInPlace(_this._collider.radius);
  14427. var updatePosition = function (newPos) {
  14428. _this._newPosition.copyFrom(newPos);
  14429. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14430. var oldPosition = _this.position.clone();
  14431. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14432. _this.position.addInPlace(_this._diffPosition);
  14433. if (_this.onCollide && collidedMesh) {
  14434. _this.onCollide(collidedMesh);
  14435. }
  14436. }
  14437. };
  14438. updatePosition(newPosition);
  14439. };
  14440. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14441. this.inputs.addKeyboard().addMouse();
  14442. }
  14443. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14444. //-- begin properties for backward compatibility for inputs
  14445. get: function () {
  14446. var mouse = this.inputs.attached["mouse"];
  14447. if (mouse)
  14448. return mouse.angularSensibility;
  14449. },
  14450. set: function (value) {
  14451. var mouse = this.inputs.attached["mouse"];
  14452. if (mouse)
  14453. mouse.angularSensibility = value;
  14454. },
  14455. enumerable: true,
  14456. configurable: true
  14457. });
  14458. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14459. get: function () {
  14460. var keyboard = this.inputs.attached["keyboard"];
  14461. if (keyboard)
  14462. return keyboard.keysUp;
  14463. },
  14464. set: function (value) {
  14465. var keyboard = this.inputs.attached["keyboard"];
  14466. if (keyboard)
  14467. keyboard.keysUp = value;
  14468. },
  14469. enumerable: true,
  14470. configurable: true
  14471. });
  14472. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14473. get: function () {
  14474. var keyboard = this.inputs.attached["keyboard"];
  14475. if (keyboard)
  14476. return keyboard.keysDown;
  14477. },
  14478. set: function (value) {
  14479. var keyboard = this.inputs.attached["keyboard"];
  14480. if (keyboard)
  14481. keyboard.keysDown = value;
  14482. },
  14483. enumerable: true,
  14484. configurable: true
  14485. });
  14486. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14487. get: function () {
  14488. var keyboard = this.inputs.attached["keyboard"];
  14489. if (keyboard)
  14490. return keyboard.keysLeft;
  14491. },
  14492. set: function (value) {
  14493. var keyboard = this.inputs.attached["keyboard"];
  14494. if (keyboard)
  14495. keyboard.keysLeft = value;
  14496. },
  14497. enumerable: true,
  14498. configurable: true
  14499. });
  14500. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14501. get: function () {
  14502. var keyboard = this.inputs.attached["keyboard"];
  14503. if (keyboard)
  14504. return keyboard.keysRight;
  14505. },
  14506. set: function (value) {
  14507. var keyboard = this.inputs.attached["keyboard"];
  14508. if (keyboard)
  14509. keyboard.keysRight = value;
  14510. },
  14511. enumerable: true,
  14512. configurable: true
  14513. });
  14514. // Controls
  14515. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14516. this.inputs.attachElement(element, noPreventDefault);
  14517. };
  14518. FreeCamera.prototype.detachControl = function (element) {
  14519. this.inputs.detachElement(element);
  14520. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14521. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14522. };
  14523. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14524. var globalPosition;
  14525. if (this.parent) {
  14526. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14527. }
  14528. else {
  14529. globalPosition = this.position;
  14530. }
  14531. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14532. this._collider.radius = this.ellipsoid;
  14533. //no need for clone, as long as gravity is not on.
  14534. var actualVelocity = velocity;
  14535. //add gravity to the velocity to prevent the dual-collision checking
  14536. if (this.applyGravity) {
  14537. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14538. actualVelocity = velocity.add(this.getScene().gravity);
  14539. }
  14540. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14541. };
  14542. FreeCamera.prototype._checkInputs = function () {
  14543. if (!this._localDirection) {
  14544. this._localDirection = BABYLON.Vector3.Zero();
  14545. this._transformedDirection = BABYLON.Vector3.Zero();
  14546. }
  14547. this.inputs.checkInputs();
  14548. _super.prototype._checkInputs.call(this);
  14549. };
  14550. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14551. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14552. };
  14553. FreeCamera.prototype._updatePosition = function () {
  14554. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14555. this._collideWithWorld(this.cameraDirection);
  14556. }
  14557. else {
  14558. this.position.addInPlace(this.cameraDirection);
  14559. }
  14560. };
  14561. FreeCamera.prototype.dispose = function () {
  14562. this.inputs.clear();
  14563. _super.prototype.dispose.call(this);
  14564. };
  14565. FreeCamera.prototype.getTypeName = function () {
  14566. return "FreeCamera";
  14567. };
  14568. __decorate([
  14569. BABYLON.serializeAsVector3()
  14570. ], FreeCamera.prototype, "ellipsoid", void 0);
  14571. __decorate([
  14572. BABYLON.serialize()
  14573. ], FreeCamera.prototype, "checkCollisions", void 0);
  14574. __decorate([
  14575. BABYLON.serialize()
  14576. ], FreeCamera.prototype, "applyGravity", void 0);
  14577. return FreeCamera;
  14578. })(BABYLON.TargetCamera);
  14579. BABYLON.FreeCamera = FreeCamera;
  14580. })(BABYLON || (BABYLON = {}));
  14581. var BABYLON;
  14582. (function (BABYLON) {
  14583. var FreeCameraInputsManager = (function (_super) {
  14584. __extends(FreeCameraInputsManager, _super);
  14585. function FreeCameraInputsManager(camera) {
  14586. _super.call(this, camera);
  14587. }
  14588. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14589. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14590. return this;
  14591. };
  14592. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14593. if (touchEnabled === void 0) { touchEnabled = true; }
  14594. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14595. return this;
  14596. };
  14597. FreeCameraInputsManager.prototype.addGamepad = function () {
  14598. this.add(new BABYLON.FreeCameraGamepadInput());
  14599. return this;
  14600. };
  14601. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14602. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14603. return this;
  14604. };
  14605. FreeCameraInputsManager.prototype.addTouch = function () {
  14606. this.add(new BABYLON.FreeCameraTouchInput());
  14607. return this;
  14608. };
  14609. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14610. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14611. return this;
  14612. };
  14613. return FreeCameraInputsManager;
  14614. })(BABYLON.CameraInputsManager);
  14615. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14616. })(BABYLON || (BABYLON = {}));
  14617. var BABYLON;
  14618. (function (BABYLON) {
  14619. var FollowCamera = (function (_super) {
  14620. __extends(FollowCamera, _super);
  14621. function FollowCamera(name, position, scene, target) {
  14622. _super.call(this, name, position, scene);
  14623. this.radius = 12;
  14624. this.rotationOffset = 0;
  14625. this.heightOffset = 4;
  14626. this.cameraAcceleration = 0.05;
  14627. this.maxCameraSpeed = 20;
  14628. this.target = target;
  14629. }
  14630. FollowCamera.prototype.getRadians = function (degrees) {
  14631. return degrees * Math.PI / 180;
  14632. };
  14633. FollowCamera.prototype.follow = function (cameraTarget) {
  14634. if (!cameraTarget)
  14635. return;
  14636. var yRotation;
  14637. if (cameraTarget.rotationQuaternion) {
  14638. var rotMatrix = new BABYLON.Matrix();
  14639. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14640. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14641. }
  14642. else {
  14643. yRotation = cameraTarget.rotation.y;
  14644. }
  14645. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14646. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14647. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14648. var dx = targetX - this.position.x;
  14649. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14650. var dz = (targetZ) - this.position.z;
  14651. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14652. var vy = dy * this.cameraAcceleration;
  14653. var vz = dz * this.cameraAcceleration * 2;
  14654. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14655. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14656. }
  14657. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14658. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14659. }
  14660. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14661. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14662. }
  14663. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14664. this.setTarget(cameraTarget.position);
  14665. };
  14666. FollowCamera.prototype._checkInputs = function () {
  14667. _super.prototype._checkInputs.call(this);
  14668. this.follow(this.target);
  14669. };
  14670. FollowCamera.prototype.getTypeName = function () {
  14671. return "FollowCamera";
  14672. };
  14673. __decorate([
  14674. BABYLON.serialize()
  14675. ], FollowCamera.prototype, "radius", void 0);
  14676. __decorate([
  14677. BABYLON.serialize()
  14678. ], FollowCamera.prototype, "rotationOffset", void 0);
  14679. __decorate([
  14680. BABYLON.serialize()
  14681. ], FollowCamera.prototype, "heightOffset", void 0);
  14682. __decorate([
  14683. BABYLON.serialize()
  14684. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14685. __decorate([
  14686. BABYLON.serialize()
  14687. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14688. __decorate([
  14689. BABYLON.serializeAsMeshReference("lockedTargetId")
  14690. ], FollowCamera.prototype, "target", void 0);
  14691. return FollowCamera;
  14692. })(BABYLON.TargetCamera);
  14693. BABYLON.FollowCamera = FollowCamera;
  14694. var ArcFollowCamera = (function (_super) {
  14695. __extends(ArcFollowCamera, _super);
  14696. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14697. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14698. this.alpha = alpha;
  14699. this.beta = beta;
  14700. this.radius = radius;
  14701. this.target = target;
  14702. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14703. this.follow();
  14704. }
  14705. ArcFollowCamera.prototype.follow = function () {
  14706. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14707. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14708. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14709. this.position = this.target.position.add(this._cartesianCoordinates);
  14710. this.setTarget(this.target.position);
  14711. };
  14712. ArcFollowCamera.prototype._checkInputs = function () {
  14713. _super.prototype._checkInputs.call(this);
  14714. this.follow();
  14715. };
  14716. ArcFollowCamera.prototype.getTypeName = function () {
  14717. return "ArcFollowCamera";
  14718. };
  14719. return ArcFollowCamera;
  14720. })(BABYLON.TargetCamera);
  14721. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14722. })(BABYLON || (BABYLON = {}));
  14723. var BABYLON;
  14724. (function (BABYLON) {
  14725. // We're mainly based on the logic defined into the FreeCamera code
  14726. var TouchCamera = (function (_super) {
  14727. __extends(TouchCamera, _super);
  14728. //-- end properties for backward compatibility for inputs
  14729. function TouchCamera(name, position, scene) {
  14730. _super.call(this, name, position, scene);
  14731. this.inputs.addTouch();
  14732. this._setupInputs();
  14733. }
  14734. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14735. //-- Begin properties for backward compatibility for inputs
  14736. get: function () {
  14737. var touch = this.inputs.attached["touch"];
  14738. if (touch)
  14739. return touch.touchAngularSensibility;
  14740. },
  14741. set: function (value) {
  14742. var touch = this.inputs.attached["touch"];
  14743. if (touch)
  14744. touch.touchAngularSensibility = value;
  14745. },
  14746. enumerable: true,
  14747. configurable: true
  14748. });
  14749. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14750. get: function () {
  14751. var touch = this.inputs.attached["touch"];
  14752. if (touch)
  14753. return touch.touchMoveSensibility;
  14754. },
  14755. set: function (value) {
  14756. var touch = this.inputs.attached["touch"];
  14757. if (touch)
  14758. touch.touchMoveSensibility = value;
  14759. },
  14760. enumerable: true,
  14761. configurable: true
  14762. });
  14763. TouchCamera.prototype.getTypeName = function () {
  14764. return "TouchCamera";
  14765. };
  14766. TouchCamera.prototype._setupInputs = function () {
  14767. var mouse = this.inputs.attached["mouse"];
  14768. if (mouse) {
  14769. mouse.touchEnabled = false;
  14770. }
  14771. };
  14772. return TouchCamera;
  14773. })(BABYLON.FreeCamera);
  14774. BABYLON.TouchCamera = TouchCamera;
  14775. })(BABYLON || (BABYLON = {}));
  14776. var BABYLON;
  14777. (function (BABYLON) {
  14778. var ArcRotateCamera = (function (_super) {
  14779. __extends(ArcRotateCamera, _super);
  14780. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14781. var _this = this;
  14782. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14783. this.inertialAlphaOffset = 0;
  14784. this.inertialBetaOffset = 0;
  14785. this.inertialRadiusOffset = 0;
  14786. this.lowerAlphaLimit = null;
  14787. this.upperAlphaLimit = null;
  14788. this.lowerBetaLimit = 0.01;
  14789. this.upperBetaLimit = Math.PI;
  14790. this.lowerRadiusLimit = null;
  14791. this.upperRadiusLimit = null;
  14792. this.inertialPanningX = 0;
  14793. this.inertialPanningY = 0;
  14794. //-- end properties for backward compatibility for inputs
  14795. this.zoomOnFactor = 1;
  14796. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14797. this.allowUpsideDown = true;
  14798. this._viewMatrix = new BABYLON.Matrix();
  14799. // Panning
  14800. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14801. this.checkCollisions = false;
  14802. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14803. this._collider = new BABYLON.Collider();
  14804. this._previousPosition = BABYLON.Vector3.Zero();
  14805. this._collisionVelocity = BABYLON.Vector3.Zero();
  14806. this._newPosition = BABYLON.Vector3.Zero();
  14807. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14808. if (collidedMesh === void 0) { collidedMesh = null; }
  14809. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14810. newPosition.multiplyInPlace(_this._collider.radius);
  14811. }
  14812. if (!collidedMesh) {
  14813. _this._previousPosition.copyFrom(_this.position);
  14814. }
  14815. else {
  14816. _this.setPosition(newPosition);
  14817. if (_this.onCollide) {
  14818. _this.onCollide(collidedMesh);
  14819. }
  14820. }
  14821. // Recompute because of constraints
  14822. var cosa = Math.cos(_this.alpha);
  14823. var sina = Math.sin(_this.alpha);
  14824. var cosb = Math.cos(_this.beta);
  14825. var sinb = Math.sin(_this.beta);
  14826. if (sinb === 0) {
  14827. sinb = 0.0001;
  14828. }
  14829. var target = _this._getTargetPosition();
  14830. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  14831. _this.position.copyFrom(_this._newPosition);
  14832. var up = _this.upVector;
  14833. if (_this.allowUpsideDown && _this.beta < 0) {
  14834. up = up.clone();
  14835. up = up.negate();
  14836. }
  14837. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  14838. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  14839. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  14840. _this._collisionTriggered = false;
  14841. };
  14842. if (!target) {
  14843. this.target = BABYLON.Vector3.Zero();
  14844. }
  14845. else {
  14846. this.target = target;
  14847. }
  14848. this.alpha = alpha;
  14849. this.beta = beta;
  14850. this.radius = radius;
  14851. this.getViewMatrix();
  14852. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  14853. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  14854. }
  14855. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  14856. //-- begin properties for backward compatibility for inputs
  14857. get: function () {
  14858. var pointers = this.inputs.attached["pointers"];
  14859. if (pointers)
  14860. return pointers.angularSensibilityX;
  14861. },
  14862. set: function (value) {
  14863. var pointers = this.inputs.attached["pointers"];
  14864. if (pointers) {
  14865. pointers.angularSensibilityX = value;
  14866. }
  14867. },
  14868. enumerable: true,
  14869. configurable: true
  14870. });
  14871. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  14872. get: function () {
  14873. var pointers = this.inputs.attached["pointers"];
  14874. if (pointers)
  14875. return pointers.angularSensibilityY;
  14876. },
  14877. set: function (value) {
  14878. var pointers = this.inputs.attached["pointers"];
  14879. if (pointers) {
  14880. pointers.angularSensibilityY = value;
  14881. }
  14882. },
  14883. enumerable: true,
  14884. configurable: true
  14885. });
  14886. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  14887. get: function () {
  14888. var pointers = this.inputs.attached["pointers"];
  14889. if (pointers)
  14890. return pointers.pinchPrecision;
  14891. },
  14892. set: function (value) {
  14893. var pointers = this.inputs.attached["pointers"];
  14894. if (pointers) {
  14895. pointers.pinchPrecision = value;
  14896. }
  14897. },
  14898. enumerable: true,
  14899. configurable: true
  14900. });
  14901. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  14902. get: function () {
  14903. var pointers = this.inputs.attached["pointers"];
  14904. if (pointers)
  14905. return pointers.panningSensibility;
  14906. },
  14907. set: function (value) {
  14908. var pointers = this.inputs.attached["pointers"];
  14909. if (pointers) {
  14910. pointers.panningSensibility = value;
  14911. }
  14912. },
  14913. enumerable: true,
  14914. configurable: true
  14915. });
  14916. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  14917. get: function () {
  14918. var keyboard = this.inputs.attached["keyboard"];
  14919. if (keyboard)
  14920. return keyboard.keysUp;
  14921. },
  14922. set: function (value) {
  14923. var keyboard = this.inputs.attached["keyboard"];
  14924. if (keyboard)
  14925. keyboard.keysUp = value;
  14926. },
  14927. enumerable: true,
  14928. configurable: true
  14929. });
  14930. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  14931. get: function () {
  14932. var keyboard = this.inputs.attached["keyboard"];
  14933. if (keyboard)
  14934. return keyboard.keysDown;
  14935. },
  14936. set: function (value) {
  14937. var keyboard = this.inputs.attached["keyboard"];
  14938. if (keyboard)
  14939. keyboard.keysDown = value;
  14940. },
  14941. enumerable: true,
  14942. configurable: true
  14943. });
  14944. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  14945. get: function () {
  14946. var keyboard = this.inputs.attached["keyboard"];
  14947. if (keyboard)
  14948. return keyboard.keysLeft;
  14949. },
  14950. set: function (value) {
  14951. var keyboard = this.inputs.attached["keyboard"];
  14952. if (keyboard)
  14953. keyboard.keysLeft = value;
  14954. },
  14955. enumerable: true,
  14956. configurable: true
  14957. });
  14958. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  14959. get: function () {
  14960. var keyboard = this.inputs.attached["keyboard"];
  14961. if (keyboard)
  14962. return keyboard.keysRight;
  14963. },
  14964. set: function (value) {
  14965. var keyboard = this.inputs.attached["keyboard"];
  14966. if (keyboard)
  14967. keyboard.keysRight = value;
  14968. },
  14969. enumerable: true,
  14970. configurable: true
  14971. });
  14972. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  14973. get: function () {
  14974. var mousewheel = this.inputs.attached["mousewheel"];
  14975. if (mousewheel)
  14976. return mousewheel.wheelPrecision;
  14977. },
  14978. set: function (value) {
  14979. var mousewheel = this.inputs.attached["mousewheel"];
  14980. if (mousewheel)
  14981. mousewheel.wheelPrecision = value;
  14982. },
  14983. enumerable: true,
  14984. configurable: true
  14985. });
  14986. // Cache
  14987. ArcRotateCamera.prototype._initCache = function () {
  14988. _super.prototype._initCache.call(this);
  14989. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14990. this._cache.alpha = undefined;
  14991. this._cache.beta = undefined;
  14992. this._cache.radius = undefined;
  14993. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  14994. };
  14995. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  14996. if (!ignoreParentClass) {
  14997. _super.prototype._updateCache.call(this);
  14998. }
  14999. this._cache.target.copyFrom(this._getTargetPosition());
  15000. this._cache.alpha = this.alpha;
  15001. this._cache.beta = this.beta;
  15002. this._cache.radius = this.radius;
  15003. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15004. };
  15005. ArcRotateCamera.prototype._getTargetPosition = function () {
  15006. if (this.target.getAbsolutePosition) {
  15007. return this.target.getAbsolutePosition();
  15008. }
  15009. return this.target;
  15010. };
  15011. // Synchronized
  15012. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15013. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15014. return false;
  15015. return this._cache.target.equals(this.target)
  15016. && this._cache.alpha === this.alpha
  15017. && this._cache.beta === this.beta
  15018. && this._cache.radius === this.radius
  15019. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15020. };
  15021. // Methods
  15022. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15023. var _this = this;
  15024. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15025. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15026. this._useCtrlForPanning = useCtrlForPanning;
  15027. this._panningMouseButton = panningMouseButton;
  15028. this.inputs.attachElement(element, noPreventDefault);
  15029. this._reset = function () {
  15030. _this.inertialAlphaOffset = 0;
  15031. _this.inertialBetaOffset = 0;
  15032. _this.inertialRadiusOffset = 0;
  15033. };
  15034. };
  15035. ArcRotateCamera.prototype.detachControl = function (element) {
  15036. this.inputs.detachElement(element);
  15037. if (this._reset) {
  15038. this._reset();
  15039. }
  15040. };
  15041. ArcRotateCamera.prototype._checkInputs = function () {
  15042. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15043. if (this._collisionTriggered) {
  15044. return;
  15045. }
  15046. this.inputs.checkInputs();
  15047. // Inertia
  15048. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15049. this.beta += this.inertialBetaOffset;
  15050. if (this.getScene().useRightHandedSystem) {
  15051. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15052. }
  15053. else {
  15054. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15055. }
  15056. this.radius -= this.inertialRadiusOffset;
  15057. this.inertialAlphaOffset *= this.inertia;
  15058. this.inertialBetaOffset *= this.inertia;
  15059. this.inertialRadiusOffset *= this.inertia;
  15060. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15061. this.inertialAlphaOffset = 0;
  15062. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15063. this.inertialBetaOffset = 0;
  15064. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15065. this.inertialRadiusOffset = 0;
  15066. }
  15067. // Panning inertia
  15068. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15069. if (!this._localDirection) {
  15070. this._localDirection = BABYLON.Vector3.Zero();
  15071. this._transformedDirection = BABYLON.Vector3.Zero();
  15072. }
  15073. this.inertialPanningX *= this.inertia;
  15074. this.inertialPanningY *= this.inertia;
  15075. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15076. this.inertialPanningX = 0;
  15077. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15078. this.inertialPanningY = 0;
  15079. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15080. this._localDirection.multiplyInPlace(this.panningAxis);
  15081. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15082. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15083. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15084. if (!this.panningAxis.y) {
  15085. this._transformedDirection.y = 0;
  15086. }
  15087. if (!this.target.getAbsolutePosition) {
  15088. this.target.addInPlace(this._transformedDirection);
  15089. }
  15090. }
  15091. // Limits
  15092. this._checkLimits();
  15093. _super.prototype._checkInputs.call(this);
  15094. };
  15095. ArcRotateCamera.prototype._checkLimits = function () {
  15096. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15097. if (this.allowUpsideDown && this.beta > Math.PI) {
  15098. this.beta = this.beta - (2 * Math.PI);
  15099. }
  15100. }
  15101. else {
  15102. if (this.beta < this.lowerBetaLimit) {
  15103. this.beta = this.lowerBetaLimit;
  15104. }
  15105. }
  15106. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15107. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15108. this.beta = this.beta + (2 * Math.PI);
  15109. }
  15110. }
  15111. else {
  15112. if (this.beta > this.upperBetaLimit) {
  15113. this.beta = this.upperBetaLimit;
  15114. }
  15115. }
  15116. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15117. this.alpha = this.lowerAlphaLimit;
  15118. }
  15119. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15120. this.alpha = this.upperAlphaLimit;
  15121. }
  15122. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15123. this.radius = this.lowerRadiusLimit;
  15124. }
  15125. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15126. this.radius = this.upperRadiusLimit;
  15127. }
  15128. };
  15129. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15130. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15131. this.radius = radiusv3.length();
  15132. // Alpha
  15133. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15134. if (radiusv3.z < 0) {
  15135. this.alpha = 2 * Math.PI - this.alpha;
  15136. }
  15137. // Beta
  15138. this.beta = Math.acos(radiusv3.y / this.radius);
  15139. this._checkLimits();
  15140. };
  15141. ArcRotateCamera.prototype.setPosition = function (position) {
  15142. if (this.position.equals(position)) {
  15143. return;
  15144. }
  15145. this.position.copyFrom(position);
  15146. this.rebuildAnglesAndRadius();
  15147. };
  15148. ArcRotateCamera.prototype.setTarget = function (target) {
  15149. if (this._getTargetPosition().equals(target)) {
  15150. return;
  15151. }
  15152. this.target = target;
  15153. this.rebuildAnglesAndRadius();
  15154. };
  15155. ArcRotateCamera.prototype._getViewMatrix = function () {
  15156. // Compute
  15157. var cosa = Math.cos(this.alpha);
  15158. var sina = Math.sin(this.alpha);
  15159. var cosb = Math.cos(this.beta);
  15160. var sinb = Math.sin(this.beta);
  15161. if (sinb === 0) {
  15162. sinb = 0.0001;
  15163. }
  15164. var target = this._getTargetPosition();
  15165. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15166. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15167. this._collider.radius = this.collisionRadius;
  15168. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15169. this._collisionTriggered = true;
  15170. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15171. }
  15172. else {
  15173. this.position.copyFrom(this._newPosition);
  15174. var up = this.upVector;
  15175. if (this.allowUpsideDown && this.beta < 0) {
  15176. up = up.clone();
  15177. up = up.negate();
  15178. }
  15179. if (this.getScene().useRightHandedSystem) {
  15180. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15181. }
  15182. else {
  15183. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15184. }
  15185. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15186. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15187. }
  15188. return this._viewMatrix;
  15189. };
  15190. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15191. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15192. meshes = meshes || this.getScene().meshes;
  15193. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15194. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15195. this.radius = distance * this.zoomOnFactor;
  15196. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15197. };
  15198. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15199. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15200. var meshesOrMinMaxVector;
  15201. var distance;
  15202. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15203. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15204. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15205. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15206. }
  15207. else {
  15208. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15209. distance = meshesOrMinMaxVectorAndDistance.distance;
  15210. }
  15211. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15212. if (!doNotUpdateMaxZ) {
  15213. this.maxZ = distance * 2;
  15214. }
  15215. };
  15216. /**
  15217. * @override
  15218. * Override Camera.createRigCamera
  15219. */
  15220. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15221. var alphaShift;
  15222. switch (this.cameraRigMode) {
  15223. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15224. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15225. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15226. case BABYLON.Camera.RIG_MODE_VR:
  15227. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15228. break;
  15229. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15230. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15231. break;
  15232. }
  15233. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15234. rigCam._cameraRigParams = {};
  15235. return rigCam;
  15236. };
  15237. /**
  15238. * @override
  15239. * Override Camera._updateRigCameras
  15240. */
  15241. ArcRotateCamera.prototype._updateRigCameras = function () {
  15242. var camLeft = this._rigCameras[0];
  15243. var camRight = this._rigCameras[1];
  15244. camLeft.beta = camRight.beta = this.beta;
  15245. camLeft.radius = camRight.radius = this.radius;
  15246. switch (this.cameraRigMode) {
  15247. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15248. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15249. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15250. case BABYLON.Camera.RIG_MODE_VR:
  15251. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15252. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15253. break;
  15254. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15255. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15256. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15257. break;
  15258. }
  15259. _super.prototype._updateRigCameras.call(this);
  15260. };
  15261. ArcRotateCamera.prototype.dispose = function () {
  15262. this.inputs.clear();
  15263. _super.prototype.dispose.call(this);
  15264. };
  15265. ArcRotateCamera.prototype.getTypeName = function () {
  15266. return "ArcRotateCamera";
  15267. };
  15268. __decorate([
  15269. BABYLON.serialize()
  15270. ], ArcRotateCamera.prototype, "alpha", void 0);
  15271. __decorate([
  15272. BABYLON.serialize()
  15273. ], ArcRotateCamera.prototype, "beta", void 0);
  15274. __decorate([
  15275. BABYLON.serialize()
  15276. ], ArcRotateCamera.prototype, "radius", void 0);
  15277. __decorate([
  15278. BABYLON.serializeAsVector3()
  15279. ], ArcRotateCamera.prototype, "target", void 0);
  15280. __decorate([
  15281. BABYLON.serialize()
  15282. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15283. __decorate([
  15284. BABYLON.serialize()
  15285. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15286. __decorate([
  15287. BABYLON.serialize()
  15288. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15289. __decorate([
  15290. BABYLON.serialize()
  15291. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15292. __decorate([
  15293. BABYLON.serialize()
  15294. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15295. __decorate([
  15296. BABYLON.serialize()
  15297. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15298. __decorate([
  15299. BABYLON.serialize()
  15300. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15301. __decorate([
  15302. BABYLON.serialize()
  15303. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15304. __decorate([
  15305. BABYLON.serialize()
  15306. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15307. __decorate([
  15308. BABYLON.serialize()
  15309. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15310. __decorate([
  15311. BABYLON.serialize()
  15312. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15313. __decorate([
  15314. BABYLON.serialize()
  15315. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15316. __decorate([
  15317. BABYLON.serialize()
  15318. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15319. return ArcRotateCamera;
  15320. })(BABYLON.TargetCamera);
  15321. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15322. })(BABYLON || (BABYLON = {}));
  15323. var BABYLON;
  15324. (function (BABYLON) {
  15325. var ArcRotateCameraInputsManager = (function (_super) {
  15326. __extends(ArcRotateCameraInputsManager, _super);
  15327. function ArcRotateCameraInputsManager(camera) {
  15328. _super.call(this, camera);
  15329. }
  15330. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15331. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15332. return this;
  15333. };
  15334. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15335. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15336. return this;
  15337. };
  15338. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15339. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15340. return this;
  15341. };
  15342. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15343. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15344. return this;
  15345. };
  15346. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15347. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15348. return this;
  15349. };
  15350. return ArcRotateCameraInputsManager;
  15351. })(BABYLON.CameraInputsManager);
  15352. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15353. })(BABYLON || (BABYLON = {}));
  15354. var BABYLON;
  15355. (function (BABYLON) {
  15356. var RenderingManager = (function () {
  15357. function RenderingManager(scene) {
  15358. this._renderingGroups = new Array();
  15359. this._autoClearDepthStencil = {};
  15360. this._customOpaqueSortCompareFn = {};
  15361. this._customAlphaTestSortCompareFn = {};
  15362. this._customTransparentSortCompareFn = {};
  15363. this._scene = scene;
  15364. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15365. this._autoClearDepthStencil[i] = true;
  15366. }
  15367. }
  15368. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15369. if (this._scene._activeParticleSystems.length === 0) {
  15370. return;
  15371. }
  15372. // Particles
  15373. var activeCamera = this._scene.activeCamera;
  15374. this._scene._particlesDuration.beginMonitoring();
  15375. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15376. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15377. if (particleSystem.renderingGroupId !== index) {
  15378. continue;
  15379. }
  15380. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15381. continue;
  15382. }
  15383. this._clearDepthStencilBuffer();
  15384. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15385. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15386. }
  15387. }
  15388. this._scene._particlesDuration.endMonitoring(false);
  15389. };
  15390. RenderingManager.prototype._renderSprites = function (index) {
  15391. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15392. return;
  15393. }
  15394. // Sprites
  15395. var activeCamera = this._scene.activeCamera;
  15396. this._scene._spritesDuration.beginMonitoring();
  15397. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15398. var spriteManager = this._scene.spriteManagers[id];
  15399. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15400. this._clearDepthStencilBuffer();
  15401. spriteManager.render();
  15402. }
  15403. }
  15404. this._scene._spritesDuration.endMonitoring(false);
  15405. };
  15406. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15407. if (this._depthStencilBufferAlreadyCleaned) {
  15408. return;
  15409. }
  15410. this._scene.getEngine().clear(0, false, true, true);
  15411. this._depthStencilBufferAlreadyCleaned = true;
  15412. };
  15413. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15414. if (this._currentRenderSprites) {
  15415. this._renderSprites(this._currentIndex);
  15416. }
  15417. if (this._currentRenderParticles) {
  15418. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15419. }
  15420. };
  15421. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15422. this._currentActiveMeshes = activeMeshes;
  15423. this._currentRenderParticles = renderParticles;
  15424. this._currentRenderSprites = renderSprites;
  15425. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15426. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15427. var renderingGroup = this._renderingGroups[index];
  15428. var needToStepBack = false;
  15429. this._currentIndex = index;
  15430. if (renderingGroup) {
  15431. if (this._autoClearDepthStencil[index]) {
  15432. this._clearDepthStencilBuffer();
  15433. }
  15434. if (!renderingGroup.onBeforeTransparentRendering) {
  15435. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15436. }
  15437. if (!renderingGroup.render(customRenderFunction)) {
  15438. this._renderingGroups.splice(index, 1);
  15439. needToStepBack = true;
  15440. this._renderSpritesAndParticles();
  15441. }
  15442. }
  15443. else {
  15444. this._renderSpritesAndParticles();
  15445. }
  15446. if (needToStepBack) {
  15447. index--;
  15448. }
  15449. }
  15450. };
  15451. RenderingManager.prototype.reset = function () {
  15452. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15453. var renderingGroup = this._renderingGroups[index];
  15454. if (renderingGroup) {
  15455. renderingGroup.prepare();
  15456. }
  15457. }
  15458. };
  15459. RenderingManager.prototype.dispatch = function (subMesh) {
  15460. var mesh = subMesh.getMesh();
  15461. var renderingGroupId = mesh.renderingGroupId || 0;
  15462. if (!this._renderingGroups[renderingGroupId]) {
  15463. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15464. }
  15465. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15466. };
  15467. /**
  15468. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15469. * This allowed control for front to back rendering or reversly depending of the special needs.
  15470. *
  15471. * @param renderingGroupId The rendering group id corresponding to its index
  15472. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15473. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15474. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15475. */
  15476. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15477. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15478. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15479. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15480. if (this._renderingGroups[renderingGroupId]) {
  15481. var group = this._renderingGroups[renderingGroupId];
  15482. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15483. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15484. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15485. }
  15486. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15487. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15488. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15489. };
  15490. /**
  15491. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15492. *
  15493. * @param renderingGroupId The rendering group id corresponding to its index
  15494. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15495. */
  15496. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15497. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15498. };
  15499. /**
  15500. * The max id used for rendering groups (not included)
  15501. */
  15502. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15503. /**
  15504. * The min id used for rendering groups (included)
  15505. */
  15506. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15507. return RenderingManager;
  15508. })();
  15509. BABYLON.RenderingManager = RenderingManager;
  15510. })(BABYLON || (BABYLON = {}));
  15511. var BABYLON;
  15512. (function (BABYLON) {
  15513. var RenderingGroup = (function () {
  15514. /**
  15515. * Creates a new rendering group.
  15516. * @param index The rendering group index
  15517. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15518. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15519. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15520. */
  15521. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15522. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15523. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15524. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15525. this.index = index;
  15526. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15527. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15528. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15529. this._scene = scene;
  15530. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15531. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15532. this.transparentSortCompareFn = transparentSortCompareFn;
  15533. }
  15534. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15535. /**
  15536. * Set the opaque sort comparison function.
  15537. * If null the sub meshes will be render in the order they were created
  15538. */
  15539. set: function (value) {
  15540. this._opaqueSortCompareFn = value;
  15541. if (value) {
  15542. this._renderOpaque = this.renderOpaqueSorted;
  15543. }
  15544. else {
  15545. this._renderOpaque = RenderingGroup.renderUnsorted;
  15546. }
  15547. },
  15548. enumerable: true,
  15549. configurable: true
  15550. });
  15551. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15552. /**
  15553. * Set the alpha test sort comparison function.
  15554. * If null the sub meshes will be render in the order they were created
  15555. */
  15556. set: function (value) {
  15557. this._alphaTestSortCompareFn = value;
  15558. if (value) {
  15559. this._renderAlphaTest = this.renderAlphaTestSorted;
  15560. }
  15561. else {
  15562. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15563. }
  15564. },
  15565. enumerable: true,
  15566. configurable: true
  15567. });
  15568. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15569. /**
  15570. * Set the transparent sort comparison function.
  15571. * If null the sub meshes will be render in the order they were created
  15572. */
  15573. set: function (value) {
  15574. if (value) {
  15575. this._transparentSortCompareFn = value;
  15576. }
  15577. else {
  15578. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15579. }
  15580. this._renderTransparent = this.renderTransparentSorted;
  15581. },
  15582. enumerable: true,
  15583. configurable: true
  15584. });
  15585. /**
  15586. * Render all the sub meshes contained in the group.
  15587. * @param customRenderFunction Used to override the default render behaviour of the group.
  15588. * @returns true if rendered some submeshes.
  15589. */
  15590. RenderingGroup.prototype.render = function (customRenderFunction) {
  15591. if (customRenderFunction) {
  15592. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15593. return true;
  15594. }
  15595. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15596. if (this.onBeforeTransparentRendering) {
  15597. this.onBeforeTransparentRendering();
  15598. }
  15599. return false;
  15600. }
  15601. var engine = this._scene.getEngine();
  15602. // Opaque
  15603. this._renderOpaque(this._opaqueSubMeshes);
  15604. // Alpha test
  15605. engine.setAlphaTesting(true);
  15606. this._renderAlphaTest(this._alphaTestSubMeshes);
  15607. engine.setAlphaTesting(false);
  15608. if (this.onBeforeTransparentRendering) {
  15609. this.onBeforeTransparentRendering();
  15610. }
  15611. // Transparent
  15612. this._renderTransparent(this._transparentSubMeshes);
  15613. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15614. return true;
  15615. };
  15616. /**
  15617. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15618. * @param subMeshes The submeshes to render
  15619. */
  15620. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15621. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15622. };
  15623. /**
  15624. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15625. * @param subMeshes The submeshes to render
  15626. */
  15627. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15628. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15629. };
  15630. /**
  15631. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15632. * @param subMeshes The submeshes to render
  15633. */
  15634. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15635. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15636. };
  15637. /**
  15638. * Renders the submeshes in a specified order.
  15639. * @param subMeshes The submeshes to sort before render
  15640. * @param sortCompareFn The comparison function use to sort
  15641. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15642. * @param transparent Specifies to activate blending if true
  15643. */
  15644. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15645. var subIndex = 0;
  15646. var subMesh;
  15647. for (; subIndex < subMeshes.length; subIndex++) {
  15648. subMesh = subMeshes.data[subIndex];
  15649. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15650. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15651. }
  15652. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15653. sortedArray.sort(sortCompareFn);
  15654. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15655. subMesh = sortedArray[subIndex];
  15656. subMesh.render(transparent);
  15657. }
  15658. };
  15659. /**
  15660. * Renders the submeshes in the order they were dispatched (no sort applied).
  15661. * @param subMeshes The submeshes to render
  15662. */
  15663. RenderingGroup.renderUnsorted = function (subMeshes) {
  15664. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15665. var submesh = subMeshes.data[subIndex];
  15666. submesh.render(false);
  15667. }
  15668. };
  15669. /**
  15670. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15671. * are rendered back to front if in the same alpha index.
  15672. *
  15673. * @param a The first submesh
  15674. * @param b The second submesh
  15675. * @returns The result of the comparison
  15676. */
  15677. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15678. // Alpha index first
  15679. if (a._alphaIndex > b._alphaIndex) {
  15680. return 1;
  15681. }
  15682. if (a._alphaIndex < b._alphaIndex) {
  15683. return -1;
  15684. }
  15685. // Then distance to camera
  15686. return RenderingGroup.backToFrontSortCompare(a, b);
  15687. };
  15688. /**
  15689. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15690. * are rendered back to front.
  15691. *
  15692. * @param a The first submesh
  15693. * @param b The second submesh
  15694. * @returns The result of the comparison
  15695. */
  15696. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15697. // Then distance to camera
  15698. if (a._distanceToCamera < b._distanceToCamera) {
  15699. return 1;
  15700. }
  15701. if (a._distanceToCamera > b._distanceToCamera) {
  15702. return -1;
  15703. }
  15704. return 0;
  15705. };
  15706. /**
  15707. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15708. * are rendered front to back (prevent overdraw).
  15709. *
  15710. * @param a The first submesh
  15711. * @param b The second submesh
  15712. * @returns The result of the comparison
  15713. */
  15714. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15715. // Then distance to camera
  15716. if (a._distanceToCamera < b._distanceToCamera) {
  15717. return -1;
  15718. }
  15719. if (a._distanceToCamera > b._distanceToCamera) {
  15720. return 1;
  15721. }
  15722. return 0;
  15723. };
  15724. /**
  15725. * Resets the different lists of submeshes to prepare a new frame.
  15726. */
  15727. RenderingGroup.prototype.prepare = function () {
  15728. this._opaqueSubMeshes.reset();
  15729. this._transparentSubMeshes.reset();
  15730. this._alphaTestSubMeshes.reset();
  15731. };
  15732. /**
  15733. * Inserts the submesh in its correct queue depending on its material.
  15734. * @param subMesh The submesh to dispatch
  15735. */
  15736. RenderingGroup.prototype.dispatch = function (subMesh) {
  15737. var material = subMesh.getMaterial();
  15738. var mesh = subMesh.getMesh();
  15739. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15740. this._transparentSubMeshes.push(subMesh);
  15741. }
  15742. else if (material.needAlphaTesting()) {
  15743. this._alphaTestSubMeshes.push(subMesh);
  15744. }
  15745. else {
  15746. this._opaqueSubMeshes.push(subMesh); // Opaque
  15747. }
  15748. };
  15749. return RenderingGroup;
  15750. })();
  15751. BABYLON.RenderingGroup = RenderingGroup;
  15752. })(BABYLON || (BABYLON = {}));
  15753. var BABYLON;
  15754. (function (BABYLON) {
  15755. var PointerEventTypes = (function () {
  15756. function PointerEventTypes() {
  15757. }
  15758. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15759. get: function () {
  15760. return PointerEventTypes._POINTERDOWN;
  15761. },
  15762. enumerable: true,
  15763. configurable: true
  15764. });
  15765. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15766. get: function () {
  15767. return PointerEventTypes._POINTERUP;
  15768. },
  15769. enumerable: true,
  15770. configurable: true
  15771. });
  15772. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15773. get: function () {
  15774. return PointerEventTypes._POINTERMOVE;
  15775. },
  15776. enumerable: true,
  15777. configurable: true
  15778. });
  15779. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15780. get: function () {
  15781. return PointerEventTypes._POINTERWHEEL;
  15782. },
  15783. enumerable: true,
  15784. configurable: true
  15785. });
  15786. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15787. get: function () {
  15788. return PointerEventTypes._POINTERPICK;
  15789. },
  15790. enumerable: true,
  15791. configurable: true
  15792. });
  15793. PointerEventTypes._POINTERDOWN = 0x01;
  15794. PointerEventTypes._POINTERUP = 0x02;
  15795. PointerEventTypes._POINTERMOVE = 0x04;
  15796. PointerEventTypes._POINTERWHEEL = 0x08;
  15797. PointerEventTypes._POINTERPICK = 0x10;
  15798. return PointerEventTypes;
  15799. })();
  15800. BABYLON.PointerEventTypes = PointerEventTypes;
  15801. var PointerInfoBase = (function () {
  15802. function PointerInfoBase(type, event) {
  15803. this.type = type;
  15804. this.event = event;
  15805. }
  15806. return PointerInfoBase;
  15807. })();
  15808. BABYLON.PointerInfoBase = PointerInfoBase;
  15809. /**
  15810. * This class is used to store pointer related info for the onPrePointerObservable event.
  15811. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15812. */
  15813. var PointerInfoPre = (function (_super) {
  15814. __extends(PointerInfoPre, _super);
  15815. function PointerInfoPre(type, event, localX, localY) {
  15816. _super.call(this, type, event);
  15817. this.skipOnPointerObservable = false;
  15818. this.localPosition = new BABYLON.Vector2(localX, localY);
  15819. }
  15820. return PointerInfoPre;
  15821. })(PointerInfoBase);
  15822. BABYLON.PointerInfoPre = PointerInfoPre;
  15823. /**
  15824. * This type contains all the data related to a pointer event in Babylon.js.
  15825. * 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.
  15826. */
  15827. var PointerInfo = (function (_super) {
  15828. __extends(PointerInfo, _super);
  15829. function PointerInfo(type, event, pickInfo) {
  15830. _super.call(this, type, event);
  15831. this.pickInfo = pickInfo;
  15832. }
  15833. return PointerInfo;
  15834. })(PointerInfoBase);
  15835. BABYLON.PointerInfo = PointerInfo;
  15836. /**
  15837. * Represents a scene to be rendered by the engine.
  15838. * @see http://doc.babylonjs.com/page.php?p=21911
  15839. */
  15840. var Scene = (function () {
  15841. /**
  15842. * @constructor
  15843. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15844. */
  15845. function Scene(engine) {
  15846. // Members
  15847. this.autoClear = true;
  15848. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15849. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15850. this.forceWireframe = false;
  15851. this.forcePointsCloud = false;
  15852. this.forceShowBoundingBoxes = false;
  15853. this.animationsEnabled = true;
  15854. this.constantlyUpdateMeshUnderPointer = false;
  15855. this.useRightHandedSystem = false;
  15856. this.hoverCursor = "pointer";
  15857. // Events
  15858. /**
  15859. * An event triggered when the scene is disposed.
  15860. * @type {BABYLON.Observable}
  15861. */
  15862. this.onDisposeObservable = new BABYLON.Observable();
  15863. /**
  15864. * An event triggered before rendering the scene
  15865. * @type {BABYLON.Observable}
  15866. */
  15867. this.onBeforeRenderObservable = new BABYLON.Observable();
  15868. /**
  15869. * An event triggered after rendering the scene
  15870. * @type {BABYLON.Observable}
  15871. */
  15872. this.onAfterRenderObservable = new BABYLON.Observable();
  15873. /**
  15874. * An event triggered when the scene is ready
  15875. * @type {BABYLON.Observable}
  15876. */
  15877. this.onReadyObservable = new BABYLON.Observable();
  15878. /**
  15879. * An event triggered before rendering a camera
  15880. * @type {BABYLON.Observable}
  15881. */
  15882. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15883. /**
  15884. * An event triggered after rendering a camera
  15885. * @type {BABYLON.Observable}
  15886. */
  15887. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15888. /**
  15889. * An event triggered when a camera is created
  15890. * @type {BABYLON.Observable}
  15891. */
  15892. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15893. /**
  15894. * An event triggered when a camera is removed
  15895. * @type {BABYLON.Observable}
  15896. */
  15897. this.onCameraRemovedObservable = new BABYLON.Observable();
  15898. /**
  15899. * An event triggered when a light is created
  15900. * @type {BABYLON.Observable}
  15901. */
  15902. this.onNewLightAddedObservable = new BABYLON.Observable();
  15903. /**
  15904. * An event triggered when a light is removed
  15905. * @type {BABYLON.Observable}
  15906. */
  15907. this.onLightRemovedObservable = new BABYLON.Observable();
  15908. /**
  15909. * An event triggered when a geometry is created
  15910. * @type {BABYLON.Observable}
  15911. */
  15912. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15913. /**
  15914. * An event triggered when a geometry is removed
  15915. * @type {BABYLON.Observable}
  15916. */
  15917. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15918. /**
  15919. * An event triggered when a mesh is created
  15920. * @type {BABYLON.Observable}
  15921. */
  15922. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15923. /**
  15924. * An event triggered when a mesh is removed
  15925. * @type {BABYLON.Observable}
  15926. */
  15927. this.onMeshRemovedObservable = new BABYLON.Observable();
  15928. // Animations
  15929. this.animations = [];
  15930. /**
  15931. * 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).
  15932. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15933. */
  15934. this.onPrePointerObservable = new BABYLON.Observable();
  15935. /**
  15936. * Observable event triggered each time an input event is received from the rendering canvas
  15937. */
  15938. this.onPointerObservable = new BABYLON.Observable();
  15939. 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
  15940. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15941. this._startingPointerTime = 0;
  15942. // Fog
  15943. /**
  15944. * is fog enabled on this scene.
  15945. * @type {boolean}
  15946. */
  15947. this.fogEnabled = true;
  15948. this.fogMode = Scene.FOGMODE_NONE;
  15949. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15950. this.fogDensity = 0.1;
  15951. this.fogStart = 0;
  15952. this.fogEnd = 1000.0;
  15953. // Lights
  15954. /**
  15955. * is shadow enabled on this scene.
  15956. * @type {boolean}
  15957. */
  15958. this.shadowsEnabled = true;
  15959. /**
  15960. * is light enabled on this scene.
  15961. * @type {boolean}
  15962. */
  15963. this.lightsEnabled = true;
  15964. /**
  15965. * All of the lights added to this scene.
  15966. * @see BABYLON.Light
  15967. * @type {BABYLON.Light[]}
  15968. */
  15969. this.lights = new Array();
  15970. // Cameras
  15971. /**
  15972. * All of the cameras added to this scene.
  15973. * @see BABYLON.Camera
  15974. * @type {BABYLON.Camera[]}
  15975. */
  15976. this.cameras = new Array();
  15977. this.activeCameras = new Array();
  15978. // Meshes
  15979. /**
  15980. * All of the (abstract) meshes added to this scene.
  15981. * @see BABYLON.AbstractMesh
  15982. * @type {BABYLON.AbstractMesh[]}
  15983. */
  15984. this.meshes = new Array();
  15985. // Geometries
  15986. this._geometries = new Array();
  15987. this.materials = new Array();
  15988. this.multiMaterials = new Array();
  15989. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15990. // Textures
  15991. this.texturesEnabled = true;
  15992. this.textures = new Array();
  15993. // Particles
  15994. this.particlesEnabled = true;
  15995. this.particleSystems = new Array();
  15996. // Sprites
  15997. this.spritesEnabled = true;
  15998. this.spriteManagers = new Array();
  15999. // Layers
  16000. this.layers = new Array();
  16001. // Skeletons
  16002. this.skeletonsEnabled = true;
  16003. this.skeletons = new Array();
  16004. // Lens flares
  16005. this.lensFlaresEnabled = true;
  16006. this.lensFlareSystems = new Array();
  16007. // Collisions
  16008. this.collisionsEnabled = true;
  16009. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16010. // Postprocesses
  16011. this.postProcessesEnabled = true;
  16012. // Customs render targets
  16013. this.renderTargetsEnabled = true;
  16014. this.dumpNextRenderTargets = false;
  16015. this.customRenderTargets = new Array();
  16016. // Imported meshes
  16017. this.importedMeshesFiles = new Array();
  16018. // Probes
  16019. this.probesEnabled = true;
  16020. this.reflectionProbes = new Array();
  16021. this._actionManagers = new Array();
  16022. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16023. // Procedural textures
  16024. this.proceduralTexturesEnabled = true;
  16025. this._proceduralTextures = new Array();
  16026. this.soundTracks = new Array();
  16027. this._audioEnabled = true;
  16028. this._headphone = false;
  16029. // Performance counters
  16030. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16031. this._totalLightsCounter = new BABYLON.PerfCounter();
  16032. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16033. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16034. this._totalVertices = new BABYLON.PerfCounter();
  16035. this._activeIndices = new BABYLON.PerfCounter();
  16036. this._activeParticles = new BABYLON.PerfCounter();
  16037. this._lastFrameDuration = new BABYLON.PerfCounter();
  16038. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16039. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16040. this._particlesDuration = new BABYLON.PerfCounter();
  16041. this._renderDuration = new BABYLON.PerfCounter();
  16042. this._spritesDuration = new BABYLON.PerfCounter();
  16043. this._activeBones = new BABYLON.PerfCounter();
  16044. this._renderId = 0;
  16045. this._executeWhenReadyTimeoutId = -1;
  16046. this._intermediateRendering = false;
  16047. this._toBeDisposed = new BABYLON.SmartArray(256);
  16048. this._pendingData = []; //ANY
  16049. this._activeMeshes = new BABYLON.SmartArray(256);
  16050. this._processedMaterials = new BABYLON.SmartArray(256);
  16051. this._renderTargets = new BABYLON.SmartArray(256);
  16052. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16053. this._activeSkeletons = new BABYLON.SmartArray(32);
  16054. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16055. this._activeAnimatables = new Array();
  16056. this._transformMatrix = BABYLON.Matrix.Zero();
  16057. this._edgesRenderers = new BABYLON.SmartArray(16);
  16058. this._uniqueIdCounter = 0;
  16059. this._engine = engine;
  16060. engine.scenes.push(this);
  16061. this._renderingManager = new BABYLON.RenderingManager(this);
  16062. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16063. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16064. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16065. if (BABYLON.OutlineRenderer) {
  16066. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16067. }
  16068. this.attachControl();
  16069. if (BABYLON.SoundTrack) {
  16070. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16071. }
  16072. //simplification queue
  16073. if (BABYLON.SimplificationQueue) {
  16074. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16075. }
  16076. //collision coordinator initialization. For now legacy per default.
  16077. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16078. }
  16079. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16080. get: function () {
  16081. return Scene._FOGMODE_NONE;
  16082. },
  16083. enumerable: true,
  16084. configurable: true
  16085. });
  16086. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16087. get: function () {
  16088. return Scene._FOGMODE_EXP;
  16089. },
  16090. enumerable: true,
  16091. configurable: true
  16092. });
  16093. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16094. get: function () {
  16095. return Scene._FOGMODE_EXP2;
  16096. },
  16097. enumerable: true,
  16098. configurable: true
  16099. });
  16100. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16101. get: function () {
  16102. return Scene._FOGMODE_LINEAR;
  16103. },
  16104. enumerable: true,
  16105. configurable: true
  16106. });
  16107. Object.defineProperty(Scene.prototype, "onDispose", {
  16108. set: function (callback) {
  16109. if (this._onDisposeObserver) {
  16110. this.onDisposeObservable.remove(this._onDisposeObserver);
  16111. }
  16112. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16113. },
  16114. enumerable: true,
  16115. configurable: true
  16116. });
  16117. Object.defineProperty(Scene.prototype, "beforeRender", {
  16118. set: function (callback) {
  16119. if (this._onBeforeRenderObserver) {
  16120. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16121. }
  16122. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16123. },
  16124. enumerable: true,
  16125. configurable: true
  16126. });
  16127. Object.defineProperty(Scene.prototype, "afterRender", {
  16128. set: function (callback) {
  16129. if (this._onAfterRenderObserver) {
  16130. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16131. }
  16132. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16133. },
  16134. enumerable: true,
  16135. configurable: true
  16136. });
  16137. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16138. set: function (callback) {
  16139. if (this._onBeforeCameraRenderObserver) {
  16140. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16141. }
  16142. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16143. },
  16144. enumerable: true,
  16145. configurable: true
  16146. });
  16147. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16148. set: function (callback) {
  16149. if (this._onAfterCameraRenderObserver) {
  16150. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16151. }
  16152. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16153. },
  16154. enumerable: true,
  16155. configurable: true
  16156. });
  16157. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16158. get: function () {
  16159. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16160. },
  16161. enumerable: true,
  16162. configurable: true
  16163. });
  16164. Object.defineProperty(Scene.prototype, "debugLayer", {
  16165. // Properties
  16166. get: function () {
  16167. if (!this._debugLayer) {
  16168. this._debugLayer = new BABYLON.DebugLayer(this);
  16169. }
  16170. return this._debugLayer;
  16171. },
  16172. enumerable: true,
  16173. configurable: true
  16174. });
  16175. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16176. get: function () {
  16177. return this._workerCollisions;
  16178. },
  16179. set: function (enabled) {
  16180. enabled = (enabled && !!Worker);
  16181. this._workerCollisions = enabled;
  16182. if (this.collisionCoordinator) {
  16183. this.collisionCoordinator.destroy();
  16184. }
  16185. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16186. this.collisionCoordinator.init(this);
  16187. },
  16188. enumerable: true,
  16189. configurable: true
  16190. });
  16191. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16192. get: function () {
  16193. return this._selectionOctree;
  16194. },
  16195. enumerable: true,
  16196. configurable: true
  16197. });
  16198. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16199. /**
  16200. * The mesh that is currently under the pointer.
  16201. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16202. */
  16203. get: function () {
  16204. return this._pointerOverMesh;
  16205. },
  16206. enumerable: true,
  16207. configurable: true
  16208. });
  16209. Object.defineProperty(Scene.prototype, "pointerX", {
  16210. /**
  16211. * Current on-screen X position of the pointer
  16212. * @return {number} X position of the pointer
  16213. */
  16214. get: function () {
  16215. return this._pointerX;
  16216. },
  16217. enumerable: true,
  16218. configurable: true
  16219. });
  16220. Object.defineProperty(Scene.prototype, "pointerY", {
  16221. /**
  16222. * Current on-screen Y position of the pointer
  16223. * @return {number} Y position of the pointer
  16224. */
  16225. get: function () {
  16226. return this._pointerY;
  16227. },
  16228. enumerable: true,
  16229. configurable: true
  16230. });
  16231. Scene.prototype.getCachedMaterial = function () {
  16232. return this._cachedMaterial;
  16233. };
  16234. Scene.prototype.getBoundingBoxRenderer = function () {
  16235. return this._boundingBoxRenderer;
  16236. };
  16237. Scene.prototype.getOutlineRenderer = function () {
  16238. return this._outlineRenderer;
  16239. };
  16240. Scene.prototype.getEngine = function () {
  16241. return this._engine;
  16242. };
  16243. Scene.prototype.getTotalVertices = function () {
  16244. return this._totalVertices.current;
  16245. };
  16246. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16247. get: function () {
  16248. return this._totalVertices;
  16249. },
  16250. enumerable: true,
  16251. configurable: true
  16252. });
  16253. Scene.prototype.getActiveIndices = function () {
  16254. return this._activeIndices.current;
  16255. };
  16256. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16257. get: function () {
  16258. return this._activeIndices;
  16259. },
  16260. enumerable: true,
  16261. configurable: true
  16262. });
  16263. Scene.prototype.getActiveParticles = function () {
  16264. return this._activeParticles.current;
  16265. };
  16266. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16267. get: function () {
  16268. return this._activeParticles;
  16269. },
  16270. enumerable: true,
  16271. configurable: true
  16272. });
  16273. Scene.prototype.getActiveBones = function () {
  16274. return this._activeBones.current;
  16275. };
  16276. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16277. get: function () {
  16278. return this._activeBones;
  16279. },
  16280. enumerable: true,
  16281. configurable: true
  16282. });
  16283. // Stats
  16284. Scene.prototype.getLastFrameDuration = function () {
  16285. return this._lastFrameDuration.current;
  16286. };
  16287. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16288. get: function () {
  16289. return this._lastFrameDuration;
  16290. },
  16291. enumerable: true,
  16292. configurable: true
  16293. });
  16294. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16295. return this._evaluateActiveMeshesDuration.current;
  16296. };
  16297. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16298. get: function () {
  16299. return this._evaluateActiveMeshesDuration;
  16300. },
  16301. enumerable: true,
  16302. configurable: true
  16303. });
  16304. Scene.prototype.getActiveMeshes = function () {
  16305. return this._activeMeshes;
  16306. };
  16307. Scene.prototype.getRenderTargetsDuration = function () {
  16308. return this._renderTargetsDuration.current;
  16309. };
  16310. Scene.prototype.getRenderDuration = function () {
  16311. return this._renderDuration.current;
  16312. };
  16313. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16314. get: function () {
  16315. return this._renderDuration;
  16316. },
  16317. enumerable: true,
  16318. configurable: true
  16319. });
  16320. Scene.prototype.getParticlesDuration = function () {
  16321. return this._particlesDuration.current;
  16322. };
  16323. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16324. get: function () {
  16325. return this._particlesDuration;
  16326. },
  16327. enumerable: true,
  16328. configurable: true
  16329. });
  16330. Scene.prototype.getSpritesDuration = function () {
  16331. return this._spritesDuration.current;
  16332. };
  16333. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16334. get: function () {
  16335. return this._spritesDuration;
  16336. },
  16337. enumerable: true,
  16338. configurable: true
  16339. });
  16340. Scene.prototype.getAnimationRatio = function () {
  16341. return this._animationRatio;
  16342. };
  16343. Scene.prototype.getRenderId = function () {
  16344. return this._renderId;
  16345. };
  16346. Scene.prototype.incrementRenderId = function () {
  16347. this._renderId++;
  16348. };
  16349. Scene.prototype._updatePointerPosition = function (evt) {
  16350. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16351. this._pointerX = evt.clientX - canvasRect.left;
  16352. this._pointerY = evt.clientY - canvasRect.top;
  16353. this._unTranslatedPointerX = this._pointerX;
  16354. this._unTranslatedPointerY = this._pointerY;
  16355. if (this.cameraToUseForPointers) {
  16356. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16357. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16358. }
  16359. };
  16360. // Pointers handling
  16361. /**
  16362. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16363. * @param attachUp defines if you want to attach events to pointerup
  16364. * @param attachDown defines if you want to attach events to pointerdown
  16365. * @param attachMove defines if you want to attach events to pointermove
  16366. */
  16367. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16368. var _this = this;
  16369. if (attachUp === void 0) { attachUp = true; }
  16370. if (attachDown === void 0) { attachDown = true; }
  16371. if (attachMove === void 0) { attachMove = true; }
  16372. var spritePredicate = function (sprite) {
  16373. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16374. };
  16375. this._onPointerMove = function (evt) {
  16376. _this._updatePointerPosition(evt);
  16377. // PreObservable support
  16378. if (_this.onPrePointerObservable.hasObservers()) {
  16379. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16380. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16381. _this.onPrePointerObservable.notifyObservers(pi, type);
  16382. if (pi.skipOnPointerObservable) {
  16383. return;
  16384. }
  16385. }
  16386. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16387. return;
  16388. }
  16389. var canvas = _this._engine.getRenderingCanvas();
  16390. if (!_this.pointerMovePredicate) {
  16391. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16392. }
  16393. // Meshes
  16394. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16395. if (pickResult.hit && pickResult.pickedMesh) {
  16396. _this.setPointerOverSprite(null);
  16397. _this.setPointerOverMesh(pickResult.pickedMesh);
  16398. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16399. canvas.style.cursor = _this.hoverCursor;
  16400. }
  16401. else {
  16402. canvas.style.cursor = "";
  16403. }
  16404. }
  16405. else {
  16406. _this.setPointerOverMesh(null);
  16407. // Sprites
  16408. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16409. if (pickResult.hit && pickResult.pickedSprite) {
  16410. canvas.style.cursor = _this.hoverCursor;
  16411. _this.setPointerOverSprite(pickResult.pickedSprite);
  16412. }
  16413. else {
  16414. _this.setPointerOverSprite(null);
  16415. // Restore pointer
  16416. canvas.style.cursor = "";
  16417. }
  16418. }
  16419. if (_this.onPointerMove) {
  16420. _this.onPointerMove(evt, pickResult);
  16421. }
  16422. if (_this.onPointerObservable.hasObservers()) {
  16423. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16424. var pi = new PointerInfo(type, evt, pickResult);
  16425. _this.onPointerObservable.notifyObservers(pi, type);
  16426. }
  16427. };
  16428. this._onPointerDown = function (evt) {
  16429. _this._updatePointerPosition(evt);
  16430. // PreObservable support
  16431. if (_this.onPrePointerObservable.hasObservers()) {
  16432. var type = PointerEventTypes.POINTERDOWN;
  16433. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16434. _this.onPrePointerObservable.notifyObservers(pi, type);
  16435. if (pi.skipOnPointerObservable) {
  16436. return;
  16437. }
  16438. }
  16439. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16440. return;
  16441. }
  16442. _this._startingPointerPosition.x = _this._pointerX;
  16443. _this._startingPointerPosition.y = _this._pointerY;
  16444. _this._startingPointerTime = new Date().getTime();
  16445. if (!_this.pointerDownPredicate) {
  16446. _this.pointerDownPredicate = function (mesh) {
  16447. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16448. };
  16449. }
  16450. // Meshes
  16451. _this._pickedDownMesh = null;
  16452. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16453. if (pickResult.hit && pickResult.pickedMesh) {
  16454. if (pickResult.pickedMesh.actionManager) {
  16455. _this._pickedDownMesh = pickResult.pickedMesh;
  16456. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16457. switch (evt.button) {
  16458. case 0:
  16459. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16460. break;
  16461. case 1:
  16462. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16463. break;
  16464. case 2:
  16465. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16466. break;
  16467. }
  16468. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16469. }
  16470. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16471. var that = _this;
  16472. window.setTimeout(function () {
  16473. 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);
  16474. if (pickResult.hit && pickResult.pickedMesh) {
  16475. if (pickResult.pickedMesh.actionManager) {
  16476. 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)) {
  16477. that._startingPointerTime = 0;
  16478. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16479. }
  16480. }
  16481. }
  16482. }, BABYLON.ActionManager.LongPressDelay);
  16483. }
  16484. }
  16485. }
  16486. if (_this.onPointerDown) {
  16487. _this.onPointerDown(evt, pickResult);
  16488. }
  16489. if (_this.onPointerObservable.hasObservers()) {
  16490. var type = PointerEventTypes.POINTERDOWN;
  16491. var pi = new PointerInfo(type, evt, pickResult);
  16492. _this.onPointerObservable.notifyObservers(pi, type);
  16493. }
  16494. // Sprites
  16495. _this._pickedDownSprite = null;
  16496. if (_this.spriteManagers.length > 0) {
  16497. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16498. if (pickResult.hit && pickResult.pickedSprite) {
  16499. if (pickResult.pickedSprite.actionManager) {
  16500. _this._pickedDownSprite = pickResult.pickedSprite;
  16501. switch (evt.button) {
  16502. case 0:
  16503. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16504. break;
  16505. case 1:
  16506. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16507. break;
  16508. case 2:
  16509. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16510. break;
  16511. }
  16512. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16513. }
  16514. }
  16515. }
  16516. };
  16517. this._onPointerUp = function (evt) {
  16518. _this._updatePointerPosition(evt);
  16519. // PreObservable support
  16520. if (_this.onPrePointerObservable.hasObservers()) {
  16521. var type = PointerEventTypes.POINTERUP;
  16522. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16523. _this.onPrePointerObservable.notifyObservers(pi, type);
  16524. if (pi.skipOnPointerObservable) {
  16525. return;
  16526. }
  16527. }
  16528. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16529. return;
  16530. }
  16531. if (!_this.pointerUpPredicate) {
  16532. _this.pointerUpPredicate = function (mesh) {
  16533. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16534. };
  16535. }
  16536. // Meshes
  16537. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16538. if (pickResult.hit && pickResult.pickedMesh) {
  16539. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16540. if (_this.onPointerPick) {
  16541. _this.onPointerPick(evt, pickResult);
  16542. }
  16543. if (_this.onPointerObservable.hasObservers()) {
  16544. var type = PointerEventTypes.POINTERPICK;
  16545. var pi = new PointerInfo(type, evt, pickResult);
  16546. _this.onPointerObservable.notifyObservers(pi, type);
  16547. }
  16548. }
  16549. if (pickResult.pickedMesh.actionManager) {
  16550. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16551. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16552. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16553. }
  16554. }
  16555. }
  16556. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16557. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16558. }
  16559. if (_this.onPointerUp) {
  16560. _this.onPointerUp(evt, pickResult);
  16561. }
  16562. if (_this.onPointerObservable.hasObservers()) {
  16563. var type = PointerEventTypes.POINTERUP;
  16564. var pi = new PointerInfo(type, evt, pickResult);
  16565. _this.onPointerObservable.notifyObservers(pi, type);
  16566. }
  16567. _this._startingPointerTime = 0;
  16568. // Sprites
  16569. if (_this.spriteManagers.length > 0) {
  16570. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16571. if (pickResult.hit && pickResult.pickedSprite) {
  16572. if (pickResult.pickedSprite.actionManager) {
  16573. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16574. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16575. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16576. }
  16577. }
  16578. }
  16579. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  16580. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  16581. }
  16582. }
  16583. };
  16584. this._onKeyDown = function (evt) {
  16585. if (_this.actionManager) {
  16586. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16587. }
  16588. };
  16589. this._onKeyUp = function (evt) {
  16590. if (_this.actionManager) {
  16591. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16592. }
  16593. };
  16594. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16595. var canvas = this._engine.getRenderingCanvas();
  16596. if (attachMove) {
  16597. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16598. // Wheel
  16599. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16600. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16601. }
  16602. if (attachDown) {
  16603. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16604. }
  16605. if (attachUp) {
  16606. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16607. }
  16608. canvas.tabIndex = 1;
  16609. canvas.addEventListener("keydown", this._onKeyDown, false);
  16610. canvas.addEventListener("keyup", this._onKeyUp, false);
  16611. };
  16612. Scene.prototype.detachControl = function () {
  16613. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16614. var canvas = this._engine.getRenderingCanvas();
  16615. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16616. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16617. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16618. // Wheel
  16619. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16620. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16621. canvas.removeEventListener("keydown", this._onKeyDown);
  16622. canvas.removeEventListener("keyup", this._onKeyUp);
  16623. };
  16624. // Ready
  16625. Scene.prototype.isReady = function () {
  16626. if (this._pendingData.length > 0) {
  16627. return false;
  16628. }
  16629. var index;
  16630. for (index = 0; index < this._geometries.length; index++) {
  16631. var geometry = this._geometries[index];
  16632. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16633. return false;
  16634. }
  16635. }
  16636. for (index = 0; index < this.meshes.length; index++) {
  16637. var mesh = this.meshes[index];
  16638. if (!mesh.isReady()) {
  16639. return false;
  16640. }
  16641. var mat = mesh.material;
  16642. if (mat) {
  16643. if (!mat.isReady(mesh)) {
  16644. return false;
  16645. }
  16646. }
  16647. }
  16648. return true;
  16649. };
  16650. Scene.prototype.resetCachedMaterial = function () {
  16651. this._cachedMaterial = null;
  16652. };
  16653. Scene.prototype.registerBeforeRender = function (func) {
  16654. this.onBeforeRenderObservable.add(func);
  16655. };
  16656. Scene.prototype.unregisterBeforeRender = function (func) {
  16657. this.onBeforeRenderObservable.removeCallback(func);
  16658. };
  16659. Scene.prototype.registerAfterRender = function (func) {
  16660. this.onAfterRenderObservable.add(func);
  16661. };
  16662. Scene.prototype.unregisterAfterRender = function (func) {
  16663. this.onAfterRenderObservable.removeCallback(func);
  16664. };
  16665. Scene.prototype._addPendingData = function (data) {
  16666. this._pendingData.push(data);
  16667. };
  16668. Scene.prototype._removePendingData = function (data) {
  16669. var index = this._pendingData.indexOf(data);
  16670. if (index !== -1) {
  16671. this._pendingData.splice(index, 1);
  16672. }
  16673. };
  16674. Scene.prototype.getWaitingItemsCount = function () {
  16675. return this._pendingData.length;
  16676. };
  16677. /**
  16678. * Registers a function to be executed when the scene is ready.
  16679. * @param {Function} func - the function to be executed.
  16680. */
  16681. Scene.prototype.executeWhenReady = function (func) {
  16682. var _this = this;
  16683. this.onReadyObservable.add(func);
  16684. if (this._executeWhenReadyTimeoutId !== -1) {
  16685. return;
  16686. }
  16687. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16688. _this._checkIsReady();
  16689. }, 150);
  16690. };
  16691. Scene.prototype._checkIsReady = function () {
  16692. var _this = this;
  16693. if (this.isReady()) {
  16694. this.onReadyObservable.notifyObservers(this);
  16695. this.onReadyObservable.clear();
  16696. this._executeWhenReadyTimeoutId = -1;
  16697. return;
  16698. }
  16699. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16700. _this._checkIsReady();
  16701. }, 150);
  16702. };
  16703. // Animations
  16704. /**
  16705. * Will start the animation sequence of a given target
  16706. * @param target - the target
  16707. * @param {number} from - from which frame should animation start
  16708. * @param {number} to - till which frame should animation run.
  16709. * @param {boolean} [loop] - should the animation loop
  16710. * @param {number} [speedRatio] - the speed in which to run the animation
  16711. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16712. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16713. * @return {BABYLON.Animatable} the animatable object created for this animation
  16714. * @see BABYLON.Animatable
  16715. * @see http://doc.babylonjs.com/page.php?p=22081
  16716. */
  16717. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16718. if (speedRatio === void 0) { speedRatio = 1.0; }
  16719. this.stopAnimation(target);
  16720. if (!animatable) {
  16721. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16722. }
  16723. // Local animations
  16724. if (target.animations) {
  16725. animatable.appendAnimations(target, target.animations);
  16726. }
  16727. // Children animations
  16728. if (target.getAnimatables) {
  16729. var animatables = target.getAnimatables();
  16730. for (var index = 0; index < animatables.length; index++) {
  16731. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16732. }
  16733. }
  16734. animatable.reset();
  16735. return animatable;
  16736. };
  16737. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16738. if (speedRatio === undefined) {
  16739. speedRatio = 1.0;
  16740. }
  16741. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16742. return animatable;
  16743. };
  16744. Scene.prototype.getAnimatableByTarget = function (target) {
  16745. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16746. if (this._activeAnimatables[index].target === target) {
  16747. return this._activeAnimatables[index];
  16748. }
  16749. }
  16750. return null;
  16751. };
  16752. Object.defineProperty(Scene.prototype, "Animatables", {
  16753. get: function () {
  16754. return this._activeAnimatables;
  16755. },
  16756. enumerable: true,
  16757. configurable: true
  16758. });
  16759. /**
  16760. * Will stop the animation of the given target
  16761. * @param target - the target
  16762. * @see beginAnimation
  16763. */
  16764. Scene.prototype.stopAnimation = function (target) {
  16765. var animatable = this.getAnimatableByTarget(target);
  16766. if (animatable) {
  16767. animatable.stop();
  16768. }
  16769. };
  16770. Scene.prototype._animate = function () {
  16771. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16772. return;
  16773. }
  16774. if (!this._animationStartDate) {
  16775. if (this._pendingData.length > 0) {
  16776. return;
  16777. }
  16778. this._animationStartDate = BABYLON.Tools.Now;
  16779. }
  16780. // Getting time
  16781. var now = BABYLON.Tools.Now;
  16782. var delay = now - this._animationStartDate;
  16783. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16784. this._activeAnimatables[index]._animate(delay);
  16785. }
  16786. };
  16787. // Matrix
  16788. Scene.prototype.getViewMatrix = function () {
  16789. return this._viewMatrix;
  16790. };
  16791. Scene.prototype.getProjectionMatrix = function () {
  16792. return this._projectionMatrix;
  16793. };
  16794. Scene.prototype.getTransformMatrix = function () {
  16795. return this._transformMatrix;
  16796. };
  16797. Scene.prototype.setTransformMatrix = function (view, projection) {
  16798. this._viewMatrix = view;
  16799. this._projectionMatrix = projection;
  16800. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16801. // Update frustum
  16802. if (!this._frustumPlanes) {
  16803. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16804. }
  16805. else {
  16806. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16807. }
  16808. };
  16809. // Methods
  16810. Scene.prototype.addMesh = function (newMesh) {
  16811. newMesh.uniqueId = this._uniqueIdCounter++;
  16812. var position = this.meshes.push(newMesh);
  16813. //notify the collision coordinator
  16814. this.collisionCoordinator.onMeshAdded(newMesh);
  16815. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16816. };
  16817. Scene.prototype.removeMesh = function (toRemove) {
  16818. var index = this.meshes.indexOf(toRemove);
  16819. if (index !== -1) {
  16820. // Remove from the scene if mesh found
  16821. this.meshes.splice(index, 1);
  16822. }
  16823. //notify the collision coordinator
  16824. this.collisionCoordinator.onMeshRemoved(toRemove);
  16825. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16826. return index;
  16827. };
  16828. Scene.prototype.removeSkeleton = function (toRemove) {
  16829. var index = this.skeletons.indexOf(toRemove);
  16830. if (index !== -1) {
  16831. // Remove from the scene if mesh found
  16832. this.skeletons.splice(index, 1);
  16833. }
  16834. return index;
  16835. };
  16836. Scene.prototype.removeLight = function (toRemove) {
  16837. var index = this.lights.indexOf(toRemove);
  16838. if (index !== -1) {
  16839. // Remove from the scene if mesh found
  16840. this.lights.splice(index, 1);
  16841. }
  16842. this.onLightRemovedObservable.notifyObservers(toRemove);
  16843. return index;
  16844. };
  16845. Scene.prototype.removeCamera = function (toRemove) {
  16846. var index = this.cameras.indexOf(toRemove);
  16847. if (index !== -1) {
  16848. // Remove from the scene if mesh found
  16849. this.cameras.splice(index, 1);
  16850. }
  16851. // Remove from activeCameras
  16852. var index2 = this.activeCameras.indexOf(toRemove);
  16853. if (index2 !== -1) {
  16854. // Remove from the scene if mesh found
  16855. this.activeCameras.splice(index2, 1);
  16856. }
  16857. // Reset the activeCamera
  16858. if (this.activeCamera === toRemove) {
  16859. if (this.cameras.length > 0) {
  16860. this.activeCamera = this.cameras[0];
  16861. }
  16862. else {
  16863. this.activeCamera = null;
  16864. }
  16865. }
  16866. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16867. return index;
  16868. };
  16869. Scene.prototype.addLight = function (newLight) {
  16870. newLight.uniqueId = this._uniqueIdCounter++;
  16871. var position = this.lights.push(newLight);
  16872. this.onNewLightAddedObservable.notifyObservers(newLight);
  16873. };
  16874. Scene.prototype.addCamera = function (newCamera) {
  16875. newCamera.uniqueId = this._uniqueIdCounter++;
  16876. var position = this.cameras.push(newCamera);
  16877. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16878. };
  16879. /**
  16880. * Switch active camera
  16881. * @param {Camera} newCamera - new active camera
  16882. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16883. */
  16884. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16885. if (attachControl === void 0) { attachControl = true; }
  16886. var canvas = this._engine.getRenderingCanvas();
  16887. this.activeCamera.detachControl(canvas);
  16888. this.activeCamera = newCamera;
  16889. if (attachControl) {
  16890. newCamera.attachControl(canvas);
  16891. }
  16892. };
  16893. /**
  16894. * sets the active camera of the scene using its ID
  16895. * @param {string} id - the camera's ID
  16896. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16897. * @see activeCamera
  16898. */
  16899. Scene.prototype.setActiveCameraByID = function (id) {
  16900. var camera = this.getCameraByID(id);
  16901. if (camera) {
  16902. this.activeCamera = camera;
  16903. return camera;
  16904. }
  16905. return null;
  16906. };
  16907. /**
  16908. * sets the active camera of the scene using its name
  16909. * @param {string} name - the camera's name
  16910. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16911. * @see activeCamera
  16912. */
  16913. Scene.prototype.setActiveCameraByName = function (name) {
  16914. var camera = this.getCameraByName(name);
  16915. if (camera) {
  16916. this.activeCamera = camera;
  16917. return camera;
  16918. }
  16919. return null;
  16920. };
  16921. /**
  16922. * get a material using its id
  16923. * @param {string} the material's ID
  16924. * @return {BABYLON.Material|null} the material or null if none found.
  16925. */
  16926. Scene.prototype.getMaterialByID = function (id) {
  16927. for (var index = 0; index < this.materials.length; index++) {
  16928. if (this.materials[index].id === id) {
  16929. return this.materials[index];
  16930. }
  16931. }
  16932. return null;
  16933. };
  16934. /**
  16935. * get a material using its name
  16936. * @param {string} the material's name
  16937. * @return {BABYLON.Material|null} the material or null if none found.
  16938. */
  16939. Scene.prototype.getMaterialByName = function (name) {
  16940. for (var index = 0; index < this.materials.length; index++) {
  16941. if (this.materials[index].name === name) {
  16942. return this.materials[index];
  16943. }
  16944. }
  16945. return null;
  16946. };
  16947. Scene.prototype.getLensFlareSystemByName = function (name) {
  16948. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16949. if (this.lensFlareSystems[index].name === name) {
  16950. return this.lensFlareSystems[index];
  16951. }
  16952. }
  16953. return null;
  16954. };
  16955. Scene.prototype.getLensFlareSystemByID = function (id) {
  16956. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16957. if (this.lensFlareSystems[index].id === id) {
  16958. return this.lensFlareSystems[index];
  16959. }
  16960. }
  16961. return null;
  16962. };
  16963. Scene.prototype.getCameraByID = function (id) {
  16964. for (var index = 0; index < this.cameras.length; index++) {
  16965. if (this.cameras[index].id === id) {
  16966. return this.cameras[index];
  16967. }
  16968. }
  16969. return null;
  16970. };
  16971. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16972. for (var index = 0; index < this.cameras.length; index++) {
  16973. if (this.cameras[index].uniqueId === uniqueId) {
  16974. return this.cameras[index];
  16975. }
  16976. }
  16977. return null;
  16978. };
  16979. /**
  16980. * get a camera using its name
  16981. * @param {string} the camera's name
  16982. * @return {BABYLON.Camera|null} the camera or null if none found.
  16983. */
  16984. Scene.prototype.getCameraByName = function (name) {
  16985. for (var index = 0; index < this.cameras.length; index++) {
  16986. if (this.cameras[index].name === name) {
  16987. return this.cameras[index];
  16988. }
  16989. }
  16990. return null;
  16991. };
  16992. /**
  16993. * get a bone using its id
  16994. * @param {string} the bone's id
  16995. * @return {BABYLON.Bone|null} the bone or null if not found
  16996. */
  16997. Scene.prototype.getBoneByID = function (id) {
  16998. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16999. var skeleton = this.skeletons[skeletonIndex];
  17000. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17001. if (skeleton.bones[boneIndex].id === id) {
  17002. return skeleton.bones[boneIndex];
  17003. }
  17004. }
  17005. }
  17006. return null;
  17007. };
  17008. /**
  17009. * get a bone using its id
  17010. * @param {string} the bone's name
  17011. * @return {BABYLON.Bone|null} the bone or null if not found
  17012. */
  17013. Scene.prototype.getBoneByName = function (name) {
  17014. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17015. var skeleton = this.skeletons[skeletonIndex];
  17016. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17017. if (skeleton.bones[boneIndex].name === name) {
  17018. return skeleton.bones[boneIndex];
  17019. }
  17020. }
  17021. }
  17022. return null;
  17023. };
  17024. /**
  17025. * get a light node using its name
  17026. * @param {string} the light's name
  17027. * @return {BABYLON.Light|null} the light or null if none found.
  17028. */
  17029. Scene.prototype.getLightByName = function (name) {
  17030. for (var index = 0; index < this.lights.length; index++) {
  17031. if (this.lights[index].name === name) {
  17032. return this.lights[index];
  17033. }
  17034. }
  17035. return null;
  17036. };
  17037. /**
  17038. * get a light node using its ID
  17039. * @param {string} the light's id
  17040. * @return {BABYLON.Light|null} the light or null if none found.
  17041. */
  17042. Scene.prototype.getLightByID = function (id) {
  17043. for (var index = 0; index < this.lights.length; index++) {
  17044. if (this.lights[index].id === id) {
  17045. return this.lights[index];
  17046. }
  17047. }
  17048. return null;
  17049. };
  17050. /**
  17051. * get a light node using its scene-generated unique ID
  17052. * @param {number} the light's unique id
  17053. * @return {BABYLON.Light|null} the light or null if none found.
  17054. */
  17055. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17056. for (var index = 0; index < this.lights.length; index++) {
  17057. if (this.lights[index].uniqueId === uniqueId) {
  17058. return this.lights[index];
  17059. }
  17060. }
  17061. return null;
  17062. };
  17063. /**
  17064. * get a particle system by id
  17065. * @param id {number} the particle system id
  17066. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17067. */
  17068. Scene.prototype.getParticleSystemByID = function (id) {
  17069. for (var index = 0; index < this.particleSystems.length; index++) {
  17070. if (this.particleSystems[index].id === id) {
  17071. return this.particleSystems[index];
  17072. }
  17073. }
  17074. return null;
  17075. };
  17076. /**
  17077. * get a geometry using its ID
  17078. * @param {string} the geometry's id
  17079. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17080. */
  17081. Scene.prototype.getGeometryByID = function (id) {
  17082. for (var index = 0; index < this._geometries.length; index++) {
  17083. if (this._geometries[index].id === id) {
  17084. return this._geometries[index];
  17085. }
  17086. }
  17087. return null;
  17088. };
  17089. /**
  17090. * add a new geometry to this scene.
  17091. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17092. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17093. * @return {boolean} was the geometry added or not
  17094. */
  17095. Scene.prototype.pushGeometry = function (geometry, force) {
  17096. if (!force && this.getGeometryByID(geometry.id)) {
  17097. return false;
  17098. }
  17099. this._geometries.push(geometry);
  17100. //notify the collision coordinator
  17101. this.collisionCoordinator.onGeometryAdded(geometry);
  17102. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17103. return true;
  17104. };
  17105. /**
  17106. * Removes an existing geometry
  17107. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17108. * @return {boolean} was the geometry removed or not
  17109. */
  17110. Scene.prototype.removeGeometry = function (geometry) {
  17111. var index = this._geometries.indexOf(geometry);
  17112. if (index > -1) {
  17113. this._geometries.splice(index, 1);
  17114. //notify the collision coordinator
  17115. this.collisionCoordinator.onGeometryDeleted(geometry);
  17116. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17117. return true;
  17118. }
  17119. return false;
  17120. };
  17121. Scene.prototype.getGeometries = function () {
  17122. return this._geometries;
  17123. };
  17124. /**
  17125. * Get the first added mesh found of a given ID
  17126. * @param {string} id - the id to search for
  17127. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17128. */
  17129. Scene.prototype.getMeshByID = function (id) {
  17130. for (var index = 0; index < this.meshes.length; index++) {
  17131. if (this.meshes[index].id === id) {
  17132. return this.meshes[index];
  17133. }
  17134. }
  17135. return null;
  17136. };
  17137. Scene.prototype.getMeshesByID = function (id) {
  17138. return this.meshes.filter(function (m) {
  17139. return m.id === id;
  17140. });
  17141. };
  17142. /**
  17143. * Get a mesh with its auto-generated unique id
  17144. * @param {number} uniqueId - the unique id to search for
  17145. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17146. */
  17147. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17148. for (var index = 0; index < this.meshes.length; index++) {
  17149. if (this.meshes[index].uniqueId === uniqueId) {
  17150. return this.meshes[index];
  17151. }
  17152. }
  17153. return null;
  17154. };
  17155. /**
  17156. * Get a the last added mesh found of a given ID
  17157. * @param {string} id - the id to search for
  17158. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17159. */
  17160. Scene.prototype.getLastMeshByID = function (id) {
  17161. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17162. if (this.meshes[index].id === id) {
  17163. return this.meshes[index];
  17164. }
  17165. }
  17166. return null;
  17167. };
  17168. /**
  17169. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17170. * @param {string} id - the id to search for
  17171. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17172. */
  17173. Scene.prototype.getLastEntryByID = function (id) {
  17174. var index;
  17175. for (index = this.meshes.length - 1; index >= 0; index--) {
  17176. if (this.meshes[index].id === id) {
  17177. return this.meshes[index];
  17178. }
  17179. }
  17180. for (index = this.cameras.length - 1; index >= 0; index--) {
  17181. if (this.cameras[index].id === id) {
  17182. return this.cameras[index];
  17183. }
  17184. }
  17185. for (index = this.lights.length - 1; index >= 0; index--) {
  17186. if (this.lights[index].id === id) {
  17187. return this.lights[index];
  17188. }
  17189. }
  17190. return null;
  17191. };
  17192. Scene.prototype.getNodeByID = function (id) {
  17193. var mesh = this.getMeshByID(id);
  17194. if (mesh) {
  17195. return mesh;
  17196. }
  17197. var light = this.getLightByID(id);
  17198. if (light) {
  17199. return light;
  17200. }
  17201. var camera = this.getCameraByID(id);
  17202. if (camera) {
  17203. return camera;
  17204. }
  17205. var bone = this.getBoneByID(id);
  17206. return bone;
  17207. };
  17208. Scene.prototype.getNodeByName = function (name) {
  17209. var mesh = this.getMeshByName(name);
  17210. if (mesh) {
  17211. return mesh;
  17212. }
  17213. var light = this.getLightByName(name);
  17214. if (light) {
  17215. return light;
  17216. }
  17217. var camera = this.getCameraByName(name);
  17218. if (camera) {
  17219. return camera;
  17220. }
  17221. var bone = this.getBoneByName(name);
  17222. return bone;
  17223. };
  17224. Scene.prototype.getMeshByName = function (name) {
  17225. for (var index = 0; index < this.meshes.length; index++) {
  17226. if (this.meshes[index].name === name) {
  17227. return this.meshes[index];
  17228. }
  17229. }
  17230. return null;
  17231. };
  17232. Scene.prototype.getSoundByName = function (name) {
  17233. var index;
  17234. if (BABYLON.AudioEngine) {
  17235. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17236. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17237. return this.mainSoundTrack.soundCollection[index];
  17238. }
  17239. }
  17240. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17241. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17242. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17243. return this.soundTracks[sdIndex].soundCollection[index];
  17244. }
  17245. }
  17246. }
  17247. }
  17248. return null;
  17249. };
  17250. Scene.prototype.getLastSkeletonByID = function (id) {
  17251. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17252. if (this.skeletons[index].id === id) {
  17253. return this.skeletons[index];
  17254. }
  17255. }
  17256. return null;
  17257. };
  17258. Scene.prototype.getSkeletonById = function (id) {
  17259. for (var index = 0; index < this.skeletons.length; index++) {
  17260. if (this.skeletons[index].id === id) {
  17261. return this.skeletons[index];
  17262. }
  17263. }
  17264. return null;
  17265. };
  17266. Scene.prototype.getSkeletonByName = function (name) {
  17267. for (var index = 0; index < this.skeletons.length; index++) {
  17268. if (this.skeletons[index].name === name) {
  17269. return this.skeletons[index];
  17270. }
  17271. }
  17272. return null;
  17273. };
  17274. Scene.prototype.isActiveMesh = function (mesh) {
  17275. return (this._activeMeshes.indexOf(mesh) !== -1);
  17276. };
  17277. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17278. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17279. var material = subMesh.getMaterial();
  17280. if (mesh.showSubMeshesBoundingBox) {
  17281. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  17282. }
  17283. if (material) {
  17284. // Render targets
  17285. if (material.getRenderTargetTextures) {
  17286. if (this._processedMaterials.indexOf(material) === -1) {
  17287. this._processedMaterials.push(material);
  17288. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17289. }
  17290. }
  17291. // Dispatch
  17292. this._activeIndices.addCount(subMesh.indexCount, false);
  17293. this._renderingManager.dispatch(subMesh);
  17294. }
  17295. }
  17296. };
  17297. Scene.prototype._isInIntermediateRendering = function () {
  17298. return this._intermediateRendering;
  17299. };
  17300. Scene.prototype._evaluateActiveMeshes = function () {
  17301. this.activeCamera._activeMeshes.reset();
  17302. this._activeMeshes.reset();
  17303. this._renderingManager.reset();
  17304. this._processedMaterials.reset();
  17305. this._activeParticleSystems.reset();
  17306. this._activeSkeletons.reset();
  17307. this._softwareSkinnedMeshes.reset();
  17308. this._boundingBoxRenderer.reset();
  17309. this._edgesRenderers.reset();
  17310. // Meshes
  17311. var meshes;
  17312. var len;
  17313. if (this._selectionOctree) {
  17314. var selection = this._selectionOctree.select(this._frustumPlanes);
  17315. meshes = selection.data;
  17316. len = selection.length;
  17317. }
  17318. else {
  17319. len = this.meshes.length;
  17320. meshes = this.meshes;
  17321. }
  17322. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17323. var mesh = meshes[meshIndex];
  17324. if (mesh.isBlocked) {
  17325. continue;
  17326. }
  17327. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17328. if (!mesh.isReady() || !mesh.isEnabled()) {
  17329. continue;
  17330. }
  17331. mesh.computeWorldMatrix();
  17332. // Intersections
  17333. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17334. this._meshesForIntersections.pushNoDuplicate(mesh);
  17335. }
  17336. // Switch to current LOD
  17337. var meshLOD = mesh.getLOD(this.activeCamera);
  17338. if (!meshLOD) {
  17339. continue;
  17340. }
  17341. mesh._preActivate();
  17342. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17343. this._activeMeshes.push(mesh);
  17344. this.activeCamera._activeMeshes.push(mesh);
  17345. mesh._activate(this._renderId);
  17346. this._activeMesh(mesh, meshLOD);
  17347. }
  17348. }
  17349. // Particle systems
  17350. this._particlesDuration.beginMonitoring();
  17351. var beforeParticlesDate = BABYLON.Tools.Now;
  17352. if (this.particlesEnabled) {
  17353. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17354. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17355. var particleSystem = this.particleSystems[particleIndex];
  17356. if (!particleSystem.isStarted()) {
  17357. continue;
  17358. }
  17359. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17360. this._activeParticleSystems.push(particleSystem);
  17361. particleSystem.animate();
  17362. }
  17363. }
  17364. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17365. }
  17366. this._particlesDuration.endMonitoring(false);
  17367. };
  17368. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17369. if (mesh.skeleton && this.skeletonsEnabled) {
  17370. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17371. mesh.skeleton.prepare();
  17372. }
  17373. if (!mesh.computeBonesUsingShaders) {
  17374. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17375. }
  17376. }
  17377. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17378. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17379. }
  17380. if (sourceMesh._edgesRenderer) {
  17381. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17382. }
  17383. if (mesh && mesh.subMeshes) {
  17384. // Submeshes Octrees
  17385. var len;
  17386. var subMeshes;
  17387. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17388. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17389. len = intersections.length;
  17390. subMeshes = intersections.data;
  17391. }
  17392. else {
  17393. subMeshes = mesh.subMeshes;
  17394. len = subMeshes.length;
  17395. }
  17396. for (var subIndex = 0; subIndex < len; subIndex++) {
  17397. var subMesh = subMeshes[subIndex];
  17398. this._evaluateSubMesh(subMesh, mesh);
  17399. }
  17400. }
  17401. };
  17402. Scene.prototype.updateTransformMatrix = function (force) {
  17403. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17404. };
  17405. Scene.prototype._renderForCamera = function (camera) {
  17406. var engine = this._engine;
  17407. var startTime = BABYLON.Tools.Now;
  17408. this.activeCamera = camera;
  17409. if (!this.activeCamera)
  17410. throw new Error("Active camera not set");
  17411. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17412. // Viewport
  17413. engine.setViewport(this.activeCamera.viewport);
  17414. // Camera
  17415. this.resetCachedMaterial();
  17416. this._renderId++;
  17417. this.updateTransformMatrix();
  17418. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17419. // Meshes
  17420. this._evaluateActiveMeshesDuration.beginMonitoring();
  17421. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17422. this._evaluateActiveMeshes();
  17423. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17424. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17425. // Software skinning
  17426. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17427. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17428. mesh.applySkeleton(mesh.skeleton);
  17429. }
  17430. // Render targets
  17431. this._renderTargetsDuration.beginMonitoring();
  17432. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17433. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17434. this._intermediateRendering = true;
  17435. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17436. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17437. var renderTarget = this._renderTargets.data[renderIndex];
  17438. if (renderTarget._shouldRender()) {
  17439. this._renderId++;
  17440. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17441. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17442. }
  17443. }
  17444. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17445. this._intermediateRendering = false;
  17446. this._renderId++;
  17447. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17448. }
  17449. this._renderTargetsDuration.endMonitoring(false);
  17450. // Prepare Frame
  17451. this.postProcessManager._prepareFrame();
  17452. this._renderDuration.beginMonitoring();
  17453. // Backgrounds
  17454. var layerIndex;
  17455. var layer;
  17456. if (this.layers.length) {
  17457. engine.setDepthBuffer(false);
  17458. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17459. layer = this.layers[layerIndex];
  17460. if (layer.isBackground) {
  17461. layer.render();
  17462. }
  17463. }
  17464. engine.setDepthBuffer(true);
  17465. }
  17466. // Render
  17467. BABYLON.Tools.StartPerformanceCounter("Main render");
  17468. this._renderingManager.render(null, null, true, true);
  17469. BABYLON.Tools.EndPerformanceCounter("Main render");
  17470. // Bounding boxes
  17471. this._boundingBoxRenderer.render();
  17472. // Edges
  17473. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17474. this._edgesRenderers.data[edgesRendererIndex].render();
  17475. }
  17476. // Lens flares
  17477. if (this.lensFlaresEnabled) {
  17478. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17479. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17480. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17481. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17482. lensFlareSystem.render();
  17483. }
  17484. }
  17485. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17486. }
  17487. // Foregrounds
  17488. if (this.layers.length) {
  17489. engine.setDepthBuffer(false);
  17490. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17491. layer = this.layers[layerIndex];
  17492. if (!layer.isBackground) {
  17493. layer.render();
  17494. }
  17495. }
  17496. engine.setDepthBuffer(true);
  17497. }
  17498. this._renderDuration.endMonitoring(false);
  17499. // Finalize frame
  17500. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17501. // Update camera
  17502. this.activeCamera._updateFromScene();
  17503. // Reset some special arrays
  17504. this._renderTargets.reset();
  17505. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17506. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17507. };
  17508. Scene.prototype._processSubCameras = function (camera) {
  17509. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17510. this._renderForCamera(camera);
  17511. return;
  17512. }
  17513. // rig cameras
  17514. for (var index = 0; index < camera._rigCameras.length; index++) {
  17515. this._renderForCamera(camera._rigCameras[index]);
  17516. }
  17517. this.activeCamera = camera;
  17518. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17519. // Update camera
  17520. this.activeCamera._updateFromScene();
  17521. };
  17522. Scene.prototype._checkIntersections = function () {
  17523. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17524. var sourceMesh = this._meshesForIntersections.data[index];
  17525. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17526. var action = sourceMesh.actionManager.actions[actionIndex];
  17527. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17528. var parameters = action.getTriggerParameter();
  17529. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17530. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17531. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17532. if (areIntersecting && currentIntersectionInProgress === -1) {
  17533. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17534. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17535. sourceMesh._intersectionsInProgress.push(otherMesh);
  17536. }
  17537. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17538. sourceMesh._intersectionsInProgress.push(otherMesh);
  17539. }
  17540. }
  17541. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17542. //They intersected, and now they don't.
  17543. //is this trigger an exit trigger? execute an event.
  17544. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17545. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17546. }
  17547. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17548. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17549. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17550. }
  17551. }
  17552. }
  17553. }
  17554. }
  17555. };
  17556. Scene.prototype.render = function () {
  17557. this._lastFrameDuration.beginMonitoring();
  17558. this._particlesDuration.fetchNewFrame();
  17559. this._spritesDuration.fetchNewFrame();
  17560. this._activeParticles.fetchNewFrame();
  17561. this._renderDuration.fetchNewFrame();
  17562. this._renderTargetsDuration.fetchNewFrame();
  17563. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17564. this._totalVertices.fetchNewFrame();
  17565. this._activeIndices.fetchNewFrame();
  17566. this._activeBones.fetchNewFrame();
  17567. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17568. this._meshesForIntersections.reset();
  17569. this.resetCachedMaterial();
  17570. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17571. // Actions
  17572. if (this.actionManager) {
  17573. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17574. }
  17575. //Simplification Queue
  17576. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17577. this.simplificationQueue.executeNext();
  17578. }
  17579. // Animations
  17580. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17581. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17582. this._animate();
  17583. // Physics
  17584. if (this._physicsEngine) {
  17585. BABYLON.Tools.StartPerformanceCounter("Physics");
  17586. this._physicsEngine._step(deltaTime / 1000.0);
  17587. BABYLON.Tools.EndPerformanceCounter("Physics");
  17588. }
  17589. // Before render
  17590. this.onBeforeRenderObservable.notifyObservers(this);
  17591. // Customs render targets
  17592. this._renderTargetsDuration.beginMonitoring();
  17593. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17594. var engine = this.getEngine();
  17595. var currentActiveCamera = this.activeCamera;
  17596. if (this.renderTargetsEnabled) {
  17597. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17598. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17599. var renderTarget = this.customRenderTargets[customIndex];
  17600. if (renderTarget._shouldRender()) {
  17601. this._renderId++;
  17602. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17603. if (!this.activeCamera)
  17604. throw new Error("Active camera not set");
  17605. // Viewport
  17606. engine.setViewport(this.activeCamera.viewport);
  17607. // Camera
  17608. this.updateTransformMatrix();
  17609. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17610. }
  17611. }
  17612. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17613. this._renderId++;
  17614. }
  17615. if (this.customRenderTargets.length > 0) {
  17616. engine.restoreDefaultFramebuffer();
  17617. }
  17618. this._renderTargetsDuration.endMonitoring();
  17619. this.activeCamera = currentActiveCamera;
  17620. // Procedural textures
  17621. if (this.proceduralTexturesEnabled) {
  17622. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17623. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17624. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17625. if (proceduralTexture._shouldRender()) {
  17626. proceduralTexture.render();
  17627. }
  17628. }
  17629. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17630. }
  17631. // Clear
  17632. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  17633. // Shadows
  17634. if (this.shadowsEnabled) {
  17635. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17636. var light = this.lights[lightIndex];
  17637. var shadowGenerator = light.getShadowGenerator();
  17638. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  17639. this._renderTargets.push(shadowGenerator.getShadowMap());
  17640. }
  17641. }
  17642. }
  17643. // Depth renderer
  17644. if (this._depthRenderer) {
  17645. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17646. }
  17647. // RenderPipeline
  17648. this.postProcessRenderPipelineManager.update();
  17649. // Multi-cameras?
  17650. if (this.activeCameras.length > 0) {
  17651. var currentRenderId = this._renderId;
  17652. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17653. this._renderId = currentRenderId;
  17654. if (cameraIndex > 0) {
  17655. this._engine.clear(0, false, true, true);
  17656. }
  17657. this._processSubCameras(this.activeCameras[cameraIndex]);
  17658. }
  17659. }
  17660. else {
  17661. if (!this.activeCamera) {
  17662. throw new Error("No camera defined");
  17663. }
  17664. this._processSubCameras(this.activeCamera);
  17665. }
  17666. // Intersection checks
  17667. this._checkIntersections();
  17668. // Update the audio listener attached to the camera
  17669. if (BABYLON.AudioEngine) {
  17670. this._updateAudioParameters();
  17671. }
  17672. // After render
  17673. if (this.afterRender) {
  17674. this.afterRender();
  17675. }
  17676. this.onAfterRenderObservable.notifyObservers(this);
  17677. // Cleaning
  17678. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17679. this._toBeDisposed.data[index].dispose();
  17680. this._toBeDisposed[index] = null;
  17681. }
  17682. this._toBeDisposed.reset();
  17683. if (this.dumpNextRenderTargets) {
  17684. this.dumpNextRenderTargets = false;
  17685. }
  17686. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17687. this._lastFrameDuration.endMonitoring();
  17688. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17689. this._totalLightsCounter.addCount(this.lights.length, true);
  17690. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17691. this._totalTexturesCounter.addCount(this.textures.length, true);
  17692. this._activeBones.addCount(0, true);
  17693. this._activeIndices.addCount(0, true);
  17694. this._activeParticles.addCount(0, true);
  17695. };
  17696. Scene.prototype._updateAudioParameters = function () {
  17697. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17698. return;
  17699. }
  17700. var listeningCamera;
  17701. var audioEngine = BABYLON.Engine.audioEngine;
  17702. if (this.activeCameras.length > 0) {
  17703. listeningCamera = this.activeCameras[0];
  17704. }
  17705. else {
  17706. listeningCamera = this.activeCamera;
  17707. }
  17708. if (listeningCamera && audioEngine.canUseWebAudio) {
  17709. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17710. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17711. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17712. cameraDirection.normalize();
  17713. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17714. var i;
  17715. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17716. var sound = this.mainSoundTrack.soundCollection[i];
  17717. if (sound.useCustomAttenuation) {
  17718. sound.updateDistanceFromListener();
  17719. }
  17720. }
  17721. for (i = 0; i < this.soundTracks.length; i++) {
  17722. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17723. sound = this.soundTracks[i].soundCollection[j];
  17724. if (sound.useCustomAttenuation) {
  17725. sound.updateDistanceFromListener();
  17726. }
  17727. }
  17728. }
  17729. }
  17730. };
  17731. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17732. // Audio
  17733. get: function () {
  17734. return this._audioEnabled;
  17735. },
  17736. set: function (value) {
  17737. this._audioEnabled = value;
  17738. if (BABYLON.AudioEngine) {
  17739. if (this._audioEnabled) {
  17740. this._enableAudio();
  17741. }
  17742. else {
  17743. this._disableAudio();
  17744. }
  17745. }
  17746. },
  17747. enumerable: true,
  17748. configurable: true
  17749. });
  17750. Scene.prototype._disableAudio = function () {
  17751. var i;
  17752. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17753. this.mainSoundTrack.soundCollection[i].pause();
  17754. }
  17755. for (i = 0; i < this.soundTracks.length; i++) {
  17756. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17757. this.soundTracks[i].soundCollection[j].pause();
  17758. }
  17759. }
  17760. };
  17761. Scene.prototype._enableAudio = function () {
  17762. var i;
  17763. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17764. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17765. this.mainSoundTrack.soundCollection[i].play();
  17766. }
  17767. }
  17768. for (i = 0; i < this.soundTracks.length; i++) {
  17769. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17770. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17771. this.soundTracks[i].soundCollection[j].play();
  17772. }
  17773. }
  17774. }
  17775. };
  17776. Object.defineProperty(Scene.prototype, "headphone", {
  17777. get: function () {
  17778. return this._headphone;
  17779. },
  17780. set: function (value) {
  17781. this._headphone = value;
  17782. if (BABYLON.AudioEngine) {
  17783. if (this._headphone) {
  17784. this._switchAudioModeForHeadphones();
  17785. }
  17786. else {
  17787. this._switchAudioModeForNormalSpeakers();
  17788. }
  17789. }
  17790. },
  17791. enumerable: true,
  17792. configurable: true
  17793. });
  17794. Scene.prototype._switchAudioModeForHeadphones = function () {
  17795. this.mainSoundTrack.switchPanningModelToHRTF();
  17796. for (var i = 0; i < this.soundTracks.length; i++) {
  17797. this.soundTracks[i].switchPanningModelToHRTF();
  17798. }
  17799. };
  17800. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17801. this.mainSoundTrack.switchPanningModelToEqualPower();
  17802. for (var i = 0; i < this.soundTracks.length; i++) {
  17803. this.soundTracks[i].switchPanningModelToEqualPower();
  17804. }
  17805. };
  17806. Scene.prototype.enableDepthRenderer = function () {
  17807. if (this._depthRenderer) {
  17808. return this._depthRenderer;
  17809. }
  17810. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17811. return this._depthRenderer;
  17812. };
  17813. Scene.prototype.disableDepthRenderer = function () {
  17814. if (!this._depthRenderer) {
  17815. return;
  17816. }
  17817. this._depthRenderer.dispose();
  17818. this._depthRenderer = null;
  17819. };
  17820. Scene.prototype.freezeMaterials = function () {
  17821. for (var i = 0; i < this.materials.length; i++) {
  17822. this.materials[i].freeze();
  17823. }
  17824. };
  17825. Scene.prototype.unfreezeMaterials = function () {
  17826. for (var i = 0; i < this.materials.length; i++) {
  17827. this.materials[i].unfreeze();
  17828. }
  17829. };
  17830. Scene.prototype.dispose = function () {
  17831. this.beforeRender = null;
  17832. this.afterRender = null;
  17833. this.skeletons = [];
  17834. this._boundingBoxRenderer.dispose();
  17835. if (this._depthRenderer) {
  17836. this._depthRenderer.dispose();
  17837. }
  17838. // Debug layer
  17839. if (this._debugLayer) {
  17840. this._debugLayer.hide();
  17841. }
  17842. // Events
  17843. this.onDisposeObservable.notifyObservers(this);
  17844. this.onDisposeObservable.clear();
  17845. this.onBeforeRenderObservable.clear();
  17846. this.onAfterRenderObservable.clear();
  17847. this.detachControl();
  17848. // Release sounds & sounds tracks
  17849. if (BABYLON.AudioEngine) {
  17850. this.disposeSounds();
  17851. }
  17852. // Detach cameras
  17853. var canvas = this._engine.getRenderingCanvas();
  17854. var index;
  17855. for (index = 0; index < this.cameras.length; index++) {
  17856. this.cameras[index].detachControl(canvas);
  17857. }
  17858. // Release lights
  17859. while (this.lights.length) {
  17860. this.lights[0].dispose();
  17861. }
  17862. // Release meshes
  17863. while (this.meshes.length) {
  17864. this.meshes[0].dispose(true);
  17865. }
  17866. // Release cameras
  17867. while (this.cameras.length) {
  17868. this.cameras[0].dispose();
  17869. }
  17870. // Release materials
  17871. while (this.materials.length) {
  17872. this.materials[0].dispose();
  17873. }
  17874. // Release particles
  17875. while (this.particleSystems.length) {
  17876. this.particleSystems[0].dispose();
  17877. }
  17878. // Release sprites
  17879. while (this.spriteManagers.length) {
  17880. this.spriteManagers[0].dispose();
  17881. }
  17882. // Release layers
  17883. while (this.layers.length) {
  17884. this.layers[0].dispose();
  17885. }
  17886. // Release textures
  17887. while (this.textures.length) {
  17888. this.textures[0].dispose();
  17889. }
  17890. // Post-processes
  17891. this.postProcessManager.dispose();
  17892. // Physics
  17893. if (this._physicsEngine) {
  17894. this.disablePhysicsEngine();
  17895. }
  17896. // Remove from engine
  17897. index = this._engine.scenes.indexOf(this);
  17898. if (index > -1) {
  17899. this._engine.scenes.splice(index, 1);
  17900. }
  17901. this._engine.wipeCaches();
  17902. };
  17903. // Release sounds & sounds tracks
  17904. Scene.prototype.disposeSounds = function () {
  17905. this.mainSoundTrack.dispose();
  17906. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17907. this.soundTracks[scIndex].dispose();
  17908. }
  17909. };
  17910. // Octrees
  17911. Scene.prototype.getWorldExtends = function () {
  17912. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17913. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17914. for (var index = 0; index < this.meshes.length; index++) {
  17915. var mesh = this.meshes[index];
  17916. mesh.computeWorldMatrix(true);
  17917. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17918. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17919. BABYLON.Tools.CheckExtends(minBox, min, max);
  17920. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17921. }
  17922. return {
  17923. min: min,
  17924. max: max
  17925. };
  17926. };
  17927. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17928. if (maxCapacity === void 0) { maxCapacity = 64; }
  17929. if (maxDepth === void 0) { maxDepth = 2; }
  17930. if (!this._selectionOctree) {
  17931. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17932. }
  17933. var worldExtends = this.getWorldExtends();
  17934. // Update octree
  17935. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17936. return this._selectionOctree;
  17937. };
  17938. // Picking
  17939. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17940. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17941. var engine = this._engine;
  17942. if (!camera) {
  17943. if (!this.activeCamera)
  17944. throw new Error("Active camera not set");
  17945. camera = this.activeCamera;
  17946. }
  17947. var cameraViewport = camera.viewport;
  17948. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17949. // Moving coordinates to local viewport world
  17950. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17951. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17952. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17953. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17954. };
  17955. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17956. var engine = this._engine;
  17957. if (!camera) {
  17958. if (!this.activeCamera)
  17959. throw new Error("Active camera not set");
  17960. camera = this.activeCamera;
  17961. }
  17962. var cameraViewport = camera.viewport;
  17963. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17964. var identity = BABYLON.Matrix.Identity();
  17965. // Moving coordinates to local viewport world
  17966. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17967. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17968. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17969. };
  17970. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17971. var pickingInfo = null;
  17972. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17973. var mesh = this.meshes[meshIndex];
  17974. if (predicate) {
  17975. if (!predicate(mesh)) {
  17976. continue;
  17977. }
  17978. }
  17979. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17980. continue;
  17981. }
  17982. var world = mesh.getWorldMatrix();
  17983. var ray = rayFunction(world);
  17984. var result = mesh.intersects(ray, fastCheck);
  17985. if (!result || !result.hit)
  17986. continue;
  17987. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17988. continue;
  17989. pickingInfo = result;
  17990. if (fastCheck) {
  17991. break;
  17992. }
  17993. }
  17994. return pickingInfo || new BABYLON.PickingInfo();
  17995. };
  17996. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17997. var pickingInfo = null;
  17998. camera = camera || this.activeCamera;
  17999. if (this.spriteManagers.length > 0) {
  18000. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18001. var spriteManager = this.spriteManagers[spriteIndex];
  18002. if (!spriteManager.isPickable) {
  18003. continue;
  18004. }
  18005. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18006. if (!result || !result.hit)
  18007. continue;
  18008. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18009. continue;
  18010. pickingInfo = result;
  18011. if (fastCheck) {
  18012. break;
  18013. }
  18014. }
  18015. }
  18016. return pickingInfo || new BABYLON.PickingInfo();
  18017. };
  18018. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18019. var _this = this;
  18020. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18021. /// <param name="x">X position on screen</param>
  18022. /// <param name="y">Y position on screen</param>
  18023. /// <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>
  18024. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18025. /// <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>
  18026. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18027. };
  18028. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18029. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18030. /// <param name="x">X position on screen</param>
  18031. /// <param name="y">Y position on screen</param>
  18032. /// <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>
  18033. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18034. /// <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>
  18035. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18036. };
  18037. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18038. var _this = this;
  18039. return this._internalPick(function (world) {
  18040. if (!_this._pickWithRayInverseMatrix) {
  18041. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18042. }
  18043. world.invertToRef(_this._pickWithRayInverseMatrix);
  18044. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18045. }, predicate, fastCheck);
  18046. };
  18047. Scene.prototype.setPointerOverMesh = function (mesh) {
  18048. if (this._pointerOverMesh === mesh) {
  18049. return;
  18050. }
  18051. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18052. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18053. }
  18054. this._pointerOverMesh = mesh;
  18055. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18056. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18057. }
  18058. };
  18059. Scene.prototype.getPointerOverMesh = function () {
  18060. return this._pointerOverMesh;
  18061. };
  18062. Scene.prototype.setPointerOverSprite = function (sprite) {
  18063. if (this._pointerOverSprite === sprite) {
  18064. return;
  18065. }
  18066. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18067. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18068. }
  18069. this._pointerOverSprite = sprite;
  18070. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18071. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18072. }
  18073. };
  18074. Scene.prototype.getPointerOverSprite = function () {
  18075. return this._pointerOverSprite;
  18076. };
  18077. // Physics
  18078. Scene.prototype.getPhysicsEngine = function () {
  18079. return this._physicsEngine;
  18080. };
  18081. /**
  18082. * Enables physics to the current scene
  18083. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18084. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18085. * @return {boolean} was the physics engine initialized
  18086. */
  18087. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18088. if (this._physicsEngine) {
  18089. return true;
  18090. }
  18091. try {
  18092. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18093. return true;
  18094. }
  18095. catch (e) {
  18096. BABYLON.Tools.Error(e.message);
  18097. return false;
  18098. }
  18099. };
  18100. Scene.prototype.disablePhysicsEngine = function () {
  18101. if (!this._physicsEngine) {
  18102. return;
  18103. }
  18104. this._physicsEngine.dispose();
  18105. this._physicsEngine = undefined;
  18106. };
  18107. Scene.prototype.isPhysicsEnabled = function () {
  18108. return this._physicsEngine !== undefined;
  18109. };
  18110. /**
  18111. *
  18112. * Sets the gravity of the physics engine (and NOT of the scene)
  18113. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  18114. */
  18115. Scene.prototype.setGravity = function (gravity) {
  18116. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  18117. if (!this._physicsEngine) {
  18118. return;
  18119. }
  18120. this._physicsEngine.setGravity(gravity);
  18121. };
  18122. /**
  18123. * Legacy support, using the new API
  18124. * @Deprecated
  18125. */
  18126. Scene.prototype.createCompoundImpostor = function (parts, options) {
  18127. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  18128. if (parts.parts) {
  18129. options = parts;
  18130. parts = parts.parts;
  18131. }
  18132. var mainMesh = parts[0].mesh;
  18133. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  18134. for (var index = 1; index < parts.length; index++) {
  18135. var mesh = parts[index].mesh;
  18136. if (mesh.parent !== mainMesh) {
  18137. mesh.position = mesh.position.subtract(mainMesh.position);
  18138. mesh.parent = mainMesh;
  18139. }
  18140. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  18141. }
  18142. mainMesh.physicsImpostor.forceUpdate();
  18143. };
  18144. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18145. var mesh = compound.parts[0].mesh;
  18146. mesh.physicsImpostor.dispose();
  18147. mesh.physicsImpostor = null;
  18148. };
  18149. // Misc.
  18150. Scene.prototype.createDefaultCameraOrLight = function () {
  18151. // Light
  18152. if (this.lights.length === 0) {
  18153. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18154. }
  18155. // Camera
  18156. if (!this.activeCamera) {
  18157. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  18158. // Compute position
  18159. var worldExtends = this.getWorldExtends();
  18160. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  18161. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  18162. camera.setTarget(worldCenter);
  18163. this.activeCamera = camera;
  18164. }
  18165. };
  18166. // Tags
  18167. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18168. if (tagsQuery === undefined) {
  18169. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18170. return list;
  18171. }
  18172. var listByTags = [];
  18173. forEach = forEach || (function (item) { return; });
  18174. for (var i in list) {
  18175. var item = list[i];
  18176. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18177. listByTags.push(item);
  18178. forEach(item);
  18179. }
  18180. }
  18181. return listByTags;
  18182. };
  18183. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18184. return this._getByTags(this.meshes, tagsQuery, forEach);
  18185. };
  18186. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18187. return this._getByTags(this.cameras, tagsQuery, forEach);
  18188. };
  18189. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18190. return this._getByTags(this.lights, tagsQuery, forEach);
  18191. };
  18192. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18193. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18194. };
  18195. /**
  18196. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18197. * This allowed control for front to back rendering or reversly depending of the special needs.
  18198. *
  18199. * @param renderingGroupId The rendering group id corresponding to its index
  18200. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18201. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18202. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18203. */
  18204. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18205. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18206. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18207. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18208. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18209. };
  18210. /**
  18211. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18212. *
  18213. * @param renderingGroupId The rendering group id corresponding to its index
  18214. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18215. */
  18216. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  18217. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  18218. };
  18219. // Statics
  18220. Scene._FOGMODE_NONE = 0;
  18221. Scene._FOGMODE_EXP = 1;
  18222. Scene._FOGMODE_EXP2 = 2;
  18223. Scene._FOGMODE_LINEAR = 3;
  18224. Scene.MinDeltaTime = 1.0;
  18225. Scene.MaxDeltaTime = 1000.0;
  18226. return Scene;
  18227. })();
  18228. BABYLON.Scene = Scene;
  18229. })(BABYLON || (BABYLON = {}));
  18230. var BABYLON;
  18231. (function (BABYLON) {
  18232. var Buffer = (function () {
  18233. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18234. if (engine instanceof BABYLON.Mesh) {
  18235. this._engine = engine.getScene().getEngine();
  18236. }
  18237. else {
  18238. this._engine = engine;
  18239. }
  18240. this._updatable = updatable;
  18241. this._data = data;
  18242. this._strideSize = stride;
  18243. if (!postponeInternalCreation) {
  18244. this.create();
  18245. }
  18246. this._instanced = instanced;
  18247. }
  18248. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18249. // a lot of these parameters are ignored as they are overriden by the buffer
  18250. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18251. };
  18252. // Properties
  18253. Buffer.prototype.isUpdatable = function () {
  18254. return this._updatable;
  18255. };
  18256. Buffer.prototype.getData = function () {
  18257. return this._data;
  18258. };
  18259. Buffer.prototype.getBuffer = function () {
  18260. return this._buffer;
  18261. };
  18262. Buffer.prototype.getStrideSize = function () {
  18263. return this._strideSize;
  18264. };
  18265. Buffer.prototype.getIsInstanced = function () {
  18266. return this._instanced;
  18267. };
  18268. // Methods
  18269. Buffer.prototype.create = function (data) {
  18270. if (!data && this._buffer) {
  18271. return; // nothing to do
  18272. }
  18273. data = data || this._data;
  18274. if (!this._buffer) {
  18275. if (this._updatable) {
  18276. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18277. this._data = data;
  18278. }
  18279. else {
  18280. this._buffer = this._engine.createVertexBuffer(data);
  18281. }
  18282. }
  18283. else if (this._updatable) {
  18284. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18285. this._data = data;
  18286. }
  18287. };
  18288. Buffer.prototype.update = function (data) {
  18289. this.create(data);
  18290. };
  18291. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18292. if (!this._buffer) {
  18293. return;
  18294. }
  18295. if (this._updatable) {
  18296. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18297. this._data = null;
  18298. }
  18299. };
  18300. Buffer.prototype.dispose = function () {
  18301. if (!this._buffer) {
  18302. return;
  18303. }
  18304. if (this._engine._releaseBuffer(this._buffer)) {
  18305. this._buffer = null;
  18306. }
  18307. };
  18308. return Buffer;
  18309. })();
  18310. BABYLON.Buffer = Buffer;
  18311. })(BABYLON || (BABYLON = {}));
  18312. var BABYLON;
  18313. (function (BABYLON) {
  18314. var VertexBuffer = (function () {
  18315. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18316. if (!stride) {
  18317. // Deduce stride from kind
  18318. switch (kind) {
  18319. case VertexBuffer.PositionKind:
  18320. stride = 3;
  18321. break;
  18322. case VertexBuffer.NormalKind:
  18323. stride = 3;
  18324. break;
  18325. case VertexBuffer.UVKind:
  18326. case VertexBuffer.UV2Kind:
  18327. case VertexBuffer.UV3Kind:
  18328. case VertexBuffer.UV4Kind:
  18329. case VertexBuffer.UV5Kind:
  18330. case VertexBuffer.UV6Kind:
  18331. stride = 2;
  18332. break;
  18333. case VertexBuffer.ColorKind:
  18334. stride = 4;
  18335. break;
  18336. case VertexBuffer.MatricesIndicesKind:
  18337. case VertexBuffer.MatricesIndicesExtraKind:
  18338. stride = 4;
  18339. break;
  18340. case VertexBuffer.MatricesWeightsKind:
  18341. case VertexBuffer.MatricesWeightsExtraKind:
  18342. stride = 4;
  18343. break;
  18344. }
  18345. }
  18346. if (data instanceof BABYLON.Buffer) {
  18347. if (!stride) {
  18348. stride = data.getStrideSize();
  18349. }
  18350. this._buffer = data;
  18351. this._ownsBuffer = false;
  18352. }
  18353. else {
  18354. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18355. this._ownsBuffer = true;
  18356. }
  18357. this._stride = stride;
  18358. this._offset = offset ? offset : 0;
  18359. this._size = size ? size : stride;
  18360. this._kind = kind;
  18361. }
  18362. VertexBuffer.prototype.getKind = function () {
  18363. return this._kind;
  18364. };
  18365. // Properties
  18366. VertexBuffer.prototype.isUpdatable = function () {
  18367. return this._buffer.isUpdatable();
  18368. };
  18369. VertexBuffer.prototype.getData = function () {
  18370. return this._buffer.getData();
  18371. };
  18372. VertexBuffer.prototype.getBuffer = function () {
  18373. return this._buffer.getBuffer();
  18374. };
  18375. VertexBuffer.prototype.getStrideSize = function () {
  18376. return this._stride;
  18377. };
  18378. VertexBuffer.prototype.getOffset = function () {
  18379. return this._offset;
  18380. };
  18381. VertexBuffer.prototype.getSize = function () {
  18382. return this._size;
  18383. };
  18384. VertexBuffer.prototype.getIsInstanced = function () {
  18385. return this._buffer.getIsInstanced();
  18386. };
  18387. // Methods
  18388. VertexBuffer.prototype.create = function (data) {
  18389. return this._buffer.create(data);
  18390. };
  18391. VertexBuffer.prototype.update = function (data) {
  18392. return this._buffer.update(data);
  18393. };
  18394. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18395. return this._buffer.updateDirectly(data, offset);
  18396. };
  18397. VertexBuffer.prototype.dispose = function () {
  18398. if (this._ownsBuffer) {
  18399. this._buffer.dispose();
  18400. }
  18401. };
  18402. Object.defineProperty(VertexBuffer, "PositionKind", {
  18403. get: function () {
  18404. return VertexBuffer._PositionKind;
  18405. },
  18406. enumerable: true,
  18407. configurable: true
  18408. });
  18409. Object.defineProperty(VertexBuffer, "NormalKind", {
  18410. get: function () {
  18411. return VertexBuffer._NormalKind;
  18412. },
  18413. enumerable: true,
  18414. configurable: true
  18415. });
  18416. Object.defineProperty(VertexBuffer, "UVKind", {
  18417. get: function () {
  18418. return VertexBuffer._UVKind;
  18419. },
  18420. enumerable: true,
  18421. configurable: true
  18422. });
  18423. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18424. get: function () {
  18425. return VertexBuffer._UV2Kind;
  18426. },
  18427. enumerable: true,
  18428. configurable: true
  18429. });
  18430. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18431. get: function () {
  18432. return VertexBuffer._UV3Kind;
  18433. },
  18434. enumerable: true,
  18435. configurable: true
  18436. });
  18437. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18438. get: function () {
  18439. return VertexBuffer._UV4Kind;
  18440. },
  18441. enumerable: true,
  18442. configurable: true
  18443. });
  18444. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18445. get: function () {
  18446. return VertexBuffer._UV5Kind;
  18447. },
  18448. enumerable: true,
  18449. configurable: true
  18450. });
  18451. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18452. get: function () {
  18453. return VertexBuffer._UV6Kind;
  18454. },
  18455. enumerable: true,
  18456. configurable: true
  18457. });
  18458. Object.defineProperty(VertexBuffer, "ColorKind", {
  18459. get: function () {
  18460. return VertexBuffer._ColorKind;
  18461. },
  18462. enumerable: true,
  18463. configurable: true
  18464. });
  18465. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18466. get: function () {
  18467. return VertexBuffer._MatricesIndicesKind;
  18468. },
  18469. enumerable: true,
  18470. configurable: true
  18471. });
  18472. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18473. get: function () {
  18474. return VertexBuffer._MatricesWeightsKind;
  18475. },
  18476. enumerable: true,
  18477. configurable: true
  18478. });
  18479. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18480. get: function () {
  18481. return VertexBuffer._MatricesIndicesExtraKind;
  18482. },
  18483. enumerable: true,
  18484. configurable: true
  18485. });
  18486. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18487. get: function () {
  18488. return VertexBuffer._MatricesWeightsExtraKind;
  18489. },
  18490. enumerable: true,
  18491. configurable: true
  18492. });
  18493. // Enums
  18494. VertexBuffer._PositionKind = "position";
  18495. VertexBuffer._NormalKind = "normal";
  18496. VertexBuffer._UVKind = "uv";
  18497. VertexBuffer._UV2Kind = "uv2";
  18498. VertexBuffer._UV3Kind = "uv3";
  18499. VertexBuffer._UV4Kind = "uv4";
  18500. VertexBuffer._UV5Kind = "uv5";
  18501. VertexBuffer._UV6Kind = "uv6";
  18502. VertexBuffer._ColorKind = "color";
  18503. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18504. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18505. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18506. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18507. return VertexBuffer;
  18508. })();
  18509. BABYLON.VertexBuffer = VertexBuffer;
  18510. })(BABYLON || (BABYLON = {}));
  18511. var BABYLON;
  18512. (function (BABYLON) {
  18513. /**
  18514. * Creates an instance based on a source mesh.
  18515. */
  18516. var InstancedMesh = (function (_super) {
  18517. __extends(InstancedMesh, _super);
  18518. function InstancedMesh(name, source) {
  18519. _super.call(this, name, source.getScene());
  18520. source.instances.push(this);
  18521. this._sourceMesh = source;
  18522. this.position.copyFrom(source.position);
  18523. this.rotation.copyFrom(source.rotation);
  18524. this.scaling.copyFrom(source.scaling);
  18525. if (source.rotationQuaternion) {
  18526. this.rotationQuaternion = source.rotationQuaternion.clone();
  18527. }
  18528. this.infiniteDistance = source.infiniteDistance;
  18529. this.setPivotMatrix(source.getPivotMatrix());
  18530. this.refreshBoundingInfo();
  18531. this._syncSubMeshes();
  18532. }
  18533. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  18534. // Methods
  18535. get: function () {
  18536. return this._sourceMesh.receiveShadows;
  18537. },
  18538. enumerable: true,
  18539. configurable: true
  18540. });
  18541. Object.defineProperty(InstancedMesh.prototype, "material", {
  18542. get: function () {
  18543. return this._sourceMesh.material;
  18544. },
  18545. enumerable: true,
  18546. configurable: true
  18547. });
  18548. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  18549. get: function () {
  18550. return this._sourceMesh.visibility;
  18551. },
  18552. enumerable: true,
  18553. configurable: true
  18554. });
  18555. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  18556. get: function () {
  18557. return this._sourceMesh.skeleton;
  18558. },
  18559. enumerable: true,
  18560. configurable: true
  18561. });
  18562. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  18563. get: function () {
  18564. return this._sourceMesh.renderingGroupId;
  18565. },
  18566. enumerable: true,
  18567. configurable: true
  18568. });
  18569. InstancedMesh.prototype.getTotalVertices = function () {
  18570. return this._sourceMesh.getTotalVertices();
  18571. };
  18572. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  18573. get: function () {
  18574. return this._sourceMesh;
  18575. },
  18576. enumerable: true,
  18577. configurable: true
  18578. });
  18579. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18580. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  18581. };
  18582. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  18583. return this._sourceMesh.isVerticesDataPresent(kind);
  18584. };
  18585. InstancedMesh.prototype.getIndices = function () {
  18586. return this._sourceMesh.getIndices();
  18587. };
  18588. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  18589. get: function () {
  18590. return this._sourceMesh._positions;
  18591. },
  18592. enumerable: true,
  18593. configurable: true
  18594. });
  18595. InstancedMesh.prototype.refreshBoundingInfo = function () {
  18596. var meshBB = this._sourceMesh.getBoundingInfo();
  18597. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  18598. this._updateBoundingInfo();
  18599. };
  18600. InstancedMesh.prototype._preActivate = function () {
  18601. if (this._currentLOD) {
  18602. this._currentLOD._preActivate();
  18603. }
  18604. };
  18605. InstancedMesh.prototype._activate = function (renderId) {
  18606. if (this._currentLOD) {
  18607. this._currentLOD._registerInstanceForRenderId(this, renderId);
  18608. }
  18609. };
  18610. InstancedMesh.prototype.getLOD = function (camera) {
  18611. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  18612. if (this._currentLOD === this.sourceMesh) {
  18613. return this;
  18614. }
  18615. return this._currentLOD;
  18616. };
  18617. InstancedMesh.prototype._syncSubMeshes = function () {
  18618. this.releaseSubMeshes();
  18619. if (this._sourceMesh.subMeshes) {
  18620. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  18621. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  18622. }
  18623. }
  18624. };
  18625. InstancedMesh.prototype._generatePointsArray = function () {
  18626. return this._sourceMesh._generatePointsArray();
  18627. };
  18628. // Clone
  18629. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18630. var result = this._sourceMesh.createInstance(name);
  18631. // Deep copy
  18632. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  18633. // Bounding info
  18634. this.refreshBoundingInfo();
  18635. // Parent
  18636. if (newParent) {
  18637. result.parent = newParent;
  18638. }
  18639. if (!doNotCloneChildren) {
  18640. // Children
  18641. for (var index = 0; index < this.getScene().meshes.length; index++) {
  18642. var mesh = this.getScene().meshes[index];
  18643. if (mesh.parent === this) {
  18644. mesh.clone(mesh.name, result);
  18645. }
  18646. }
  18647. }
  18648. result.computeWorldMatrix(true);
  18649. return result;
  18650. };
  18651. // Dispoe
  18652. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  18653. // Remove from mesh
  18654. var index = this._sourceMesh.instances.indexOf(this);
  18655. this._sourceMesh.instances.splice(index, 1);
  18656. _super.prototype.dispose.call(this, doNotRecurse);
  18657. };
  18658. return InstancedMesh;
  18659. })(BABYLON.AbstractMesh);
  18660. BABYLON.InstancedMesh = InstancedMesh;
  18661. })(BABYLON || (BABYLON = {}));
  18662. var BABYLON;
  18663. (function (BABYLON) {
  18664. var _InstancesBatch = (function () {
  18665. function _InstancesBatch() {
  18666. this.mustReturn = false;
  18667. this.visibleInstances = new Array();
  18668. this.renderSelf = new Array();
  18669. }
  18670. return _InstancesBatch;
  18671. })();
  18672. BABYLON._InstancesBatch = _InstancesBatch;
  18673. var Mesh = (function (_super) {
  18674. __extends(Mesh, _super);
  18675. /**
  18676. * @constructor
  18677. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18678. * @param {Scene} scene The scene to add this mesh to.
  18679. * @param {Node} parent The parent of this mesh, if it has one
  18680. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18681. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18682. * When false, achieved by calling a clone(), also passing False.
  18683. * This will make creation of children, recursive.
  18684. */
  18685. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18686. if (parent === void 0) { parent = null; }
  18687. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18688. _super.call(this, name, scene);
  18689. // Events
  18690. /**
  18691. * An event triggered before rendering the mesh
  18692. * @type {BABYLON.Observable}
  18693. */
  18694. this.onBeforeRenderObservable = new BABYLON.Observable();
  18695. /**
  18696. * An event triggered after rendering the mesh
  18697. * @type {BABYLON.Observable}
  18698. */
  18699. this.onAfterRenderObservable = new BABYLON.Observable();
  18700. /**
  18701. * An event triggered before drawing the mesh
  18702. * @type {BABYLON.Observable}
  18703. */
  18704. this.onBeforeDrawObservable = new BABYLON.Observable();
  18705. // Members
  18706. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18707. this.instances = new Array();
  18708. this._LODLevels = new Array();
  18709. this._visibleInstances = {};
  18710. this._renderIdForInstances = new Array();
  18711. this._batchCache = new _InstancesBatch();
  18712. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18713. this._sideOrientation = Mesh._DEFAULTSIDE;
  18714. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18715. if (source) {
  18716. // Geometry
  18717. if (source._geometry) {
  18718. source._geometry.applyToMesh(this);
  18719. }
  18720. // Deep copy
  18721. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  18722. // Pivot
  18723. this.setPivotMatrix(source.getPivotMatrix());
  18724. this.id = name + "." + source.id;
  18725. // Material
  18726. this.material = source.material;
  18727. var index;
  18728. if (!doNotCloneChildren) {
  18729. // Children
  18730. for (index = 0; index < scene.meshes.length; index++) {
  18731. var mesh = scene.meshes[index];
  18732. if (mesh.parent === source) {
  18733. // doNotCloneChildren is always going to be False
  18734. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  18735. }
  18736. }
  18737. }
  18738. // Physics clone
  18739. var physicsEngine = this.getScene().getPhysicsEngine();
  18740. if (clonePhysicsImpostor && physicsEngine) {
  18741. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18742. if (impostor) {
  18743. this.physicsImpostor = impostor.clone(this);
  18744. }
  18745. }
  18746. // Particles
  18747. for (index = 0; index < scene.particleSystems.length; index++) {
  18748. var system = scene.particleSystems[index];
  18749. if (system.emitter === source) {
  18750. system.clone(system.name, this);
  18751. }
  18752. }
  18753. this.computeWorldMatrix(true);
  18754. }
  18755. // Parent
  18756. if (parent !== null) {
  18757. this.parent = parent;
  18758. }
  18759. }
  18760. Object.defineProperty(Mesh, "FRONTSIDE", {
  18761. /**
  18762. * Mesh side orientation : usually the external or front surface
  18763. */
  18764. get: function () {
  18765. return Mesh._FRONTSIDE;
  18766. },
  18767. enumerable: true,
  18768. configurable: true
  18769. });
  18770. Object.defineProperty(Mesh, "BACKSIDE", {
  18771. /**
  18772. * Mesh side orientation : usually the internal or back surface
  18773. */
  18774. get: function () {
  18775. return Mesh._BACKSIDE;
  18776. },
  18777. enumerable: true,
  18778. configurable: true
  18779. });
  18780. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18781. /**
  18782. * Mesh side orientation : both internal and external or front and back surfaces
  18783. */
  18784. get: function () {
  18785. return Mesh._DOUBLESIDE;
  18786. },
  18787. enumerable: true,
  18788. configurable: true
  18789. });
  18790. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18791. /**
  18792. * Mesh side orientation : by default, `FRONTSIDE`
  18793. */
  18794. get: function () {
  18795. return Mesh._DEFAULTSIDE;
  18796. },
  18797. enumerable: true,
  18798. configurable: true
  18799. });
  18800. Object.defineProperty(Mesh, "NO_CAP", {
  18801. /**
  18802. * Mesh cap setting : no cap
  18803. */
  18804. get: function () {
  18805. return Mesh._NO_CAP;
  18806. },
  18807. enumerable: true,
  18808. configurable: true
  18809. });
  18810. Object.defineProperty(Mesh, "CAP_START", {
  18811. /**
  18812. * Mesh cap setting : one cap at the beginning of the mesh
  18813. */
  18814. get: function () {
  18815. return Mesh._CAP_START;
  18816. },
  18817. enumerable: true,
  18818. configurable: true
  18819. });
  18820. Object.defineProperty(Mesh, "CAP_END", {
  18821. /**
  18822. * Mesh cap setting : one cap at the end of the mesh
  18823. */
  18824. get: function () {
  18825. return Mesh._CAP_END;
  18826. },
  18827. enumerable: true,
  18828. configurable: true
  18829. });
  18830. Object.defineProperty(Mesh, "CAP_ALL", {
  18831. /**
  18832. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18833. */
  18834. get: function () {
  18835. return Mesh._CAP_ALL;
  18836. },
  18837. enumerable: true,
  18838. configurable: true
  18839. });
  18840. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18841. set: function (callback) {
  18842. if (this._onBeforeDrawObserver) {
  18843. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18844. }
  18845. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18846. },
  18847. enumerable: true,
  18848. configurable: true
  18849. });
  18850. // Methods
  18851. /**
  18852. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18853. */
  18854. Mesh.prototype.toString = function (fullDetails) {
  18855. var ret = _super.prototype.toString.call(this, fullDetails);
  18856. ret += ", n vertices: " + this.getTotalVertices();
  18857. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18858. if (this.animations) {
  18859. for (var i = 0; i < this.animations.length; i++) {
  18860. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18861. }
  18862. }
  18863. if (fullDetails) {
  18864. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18865. }
  18866. return ret;
  18867. };
  18868. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18869. get: function () {
  18870. return this._LODLevels.length > 0;
  18871. },
  18872. enumerable: true,
  18873. configurable: true
  18874. });
  18875. Mesh.prototype._sortLODLevels = function () {
  18876. this._LODLevels.sort(function (a, b) {
  18877. if (a.distance < b.distance) {
  18878. return 1;
  18879. }
  18880. if (a.distance > b.distance) {
  18881. return -1;
  18882. }
  18883. return 0;
  18884. });
  18885. };
  18886. /**
  18887. * Add a mesh as LOD level triggered at the given distance.
  18888. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18889. * @param {number} distance The distance from the center of the object to show this level
  18890. * @param {Mesh} mesh The mesh to be added as LOD level
  18891. * @return {Mesh} This mesh (for chaining)
  18892. */
  18893. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18894. if (mesh && mesh._masterMesh) {
  18895. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18896. return this;
  18897. }
  18898. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18899. this._LODLevels.push(level);
  18900. if (mesh) {
  18901. mesh._masterMesh = this;
  18902. }
  18903. this._sortLODLevels();
  18904. return this;
  18905. };
  18906. /**
  18907. * Returns the LOD level mesh at the passed distance or null if not found.
  18908. * It is related to the method `addLODLevel(distance, mesh)`.
  18909. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18910. */
  18911. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18912. for (var index = 0; index < this._LODLevels.length; index++) {
  18913. var level = this._LODLevels[index];
  18914. if (level.distance === distance) {
  18915. return level.mesh;
  18916. }
  18917. }
  18918. return null;
  18919. };
  18920. /**
  18921. * Remove a mesh from the LOD array
  18922. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18923. * @param {Mesh} mesh The mesh to be removed.
  18924. * @return {Mesh} This mesh (for chaining)
  18925. */
  18926. Mesh.prototype.removeLODLevel = function (mesh) {
  18927. for (var index = 0; index < this._LODLevels.length; index++) {
  18928. if (this._LODLevels[index].mesh === mesh) {
  18929. this._LODLevels.splice(index, 1);
  18930. if (mesh) {
  18931. mesh._masterMesh = null;
  18932. }
  18933. }
  18934. }
  18935. this._sortLODLevels();
  18936. return this;
  18937. };
  18938. /**
  18939. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18940. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18941. */
  18942. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18943. if (!this._LODLevels || this._LODLevels.length === 0) {
  18944. return this;
  18945. }
  18946. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18947. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18948. if (this.onLODLevelSelection) {
  18949. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18950. }
  18951. return this;
  18952. }
  18953. for (var index = 0; index < this._LODLevels.length; index++) {
  18954. var level = this._LODLevels[index];
  18955. if (level.distance < distanceToCamera) {
  18956. if (level.mesh) {
  18957. level.mesh._preActivate();
  18958. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18959. }
  18960. if (this.onLODLevelSelection) {
  18961. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18962. }
  18963. return level.mesh;
  18964. }
  18965. }
  18966. if (this.onLODLevelSelection) {
  18967. this.onLODLevelSelection(distanceToCamera, this, this);
  18968. }
  18969. return this;
  18970. };
  18971. Object.defineProperty(Mesh.prototype, "geometry", {
  18972. /**
  18973. * Returns the mesh internal Geometry object.
  18974. */
  18975. get: function () {
  18976. return this._geometry;
  18977. },
  18978. enumerable: true,
  18979. configurable: true
  18980. });
  18981. /**
  18982. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18983. */
  18984. Mesh.prototype.getTotalVertices = function () {
  18985. if (!this._geometry) {
  18986. return 0;
  18987. }
  18988. return this._geometry.getTotalVertices();
  18989. };
  18990. /**
  18991. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18992. * 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.
  18993. * Returns null if the mesh has no geometry or no vertex buffer.
  18994. * Possible `kind` values :
  18995. * - BABYLON.VertexBuffer.PositionKind
  18996. * - BABYLON.VertexBuffer.UVKind
  18997. * - BABYLON.VertexBuffer.UV2Kind
  18998. * - BABYLON.VertexBuffer.UV3Kind
  18999. * - BABYLON.VertexBuffer.UV4Kind
  19000. * - BABYLON.VertexBuffer.UV5Kind
  19001. * - BABYLON.VertexBuffer.UV6Kind
  19002. * - BABYLON.VertexBuffer.ColorKind
  19003. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19004. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19005. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19006. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19007. */
  19008. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19009. if (!this._geometry) {
  19010. return null;
  19011. }
  19012. return this._geometry.getVerticesData(kind, copyWhenShared);
  19013. };
  19014. /**
  19015. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19016. * Returns `undefined` if the mesh has no geometry.
  19017. * Possible `kind` values :
  19018. * - BABYLON.VertexBuffer.PositionKind
  19019. * - BABYLON.VertexBuffer.UVKind
  19020. * - BABYLON.VertexBuffer.UV2Kind
  19021. * - BABYLON.VertexBuffer.UV3Kind
  19022. * - BABYLON.VertexBuffer.UV4Kind
  19023. * - BABYLON.VertexBuffer.UV5Kind
  19024. * - BABYLON.VertexBuffer.UV6Kind
  19025. * - BABYLON.VertexBuffer.ColorKind
  19026. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19027. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19028. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19029. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19030. */
  19031. Mesh.prototype.getVertexBuffer = function (kind) {
  19032. if (!this._geometry) {
  19033. return undefined;
  19034. }
  19035. return this._geometry.getVertexBuffer(kind);
  19036. };
  19037. /**
  19038. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19039. * Possible `kind` values :
  19040. * - BABYLON.VertexBuffer.PositionKind
  19041. * - BABYLON.VertexBuffer.UVKind
  19042. * - BABYLON.VertexBuffer.UV2Kind
  19043. * - BABYLON.VertexBuffer.UV3Kind
  19044. * - BABYLON.VertexBuffer.UV4Kind
  19045. * - BABYLON.VertexBuffer.UV5Kind
  19046. * - BABYLON.VertexBuffer.UV6Kind
  19047. * - BABYLON.VertexBuffer.ColorKind
  19048. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19049. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19050. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19051. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19052. */
  19053. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19054. if (!this._geometry) {
  19055. if (this._delayInfo) {
  19056. return this._delayInfo.indexOf(kind) !== -1;
  19057. }
  19058. return false;
  19059. }
  19060. return this._geometry.isVerticesDataPresent(kind);
  19061. };
  19062. /**
  19063. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19064. * Possible `kind` values :
  19065. * - BABYLON.VertexBuffer.PositionKind
  19066. * - BABYLON.VertexBuffer.UVKind
  19067. * - BABYLON.VertexBuffer.UV2Kind
  19068. * - BABYLON.VertexBuffer.UV3Kind
  19069. * - BABYLON.VertexBuffer.UV4Kind
  19070. * - BABYLON.VertexBuffer.UV5Kind
  19071. * - BABYLON.VertexBuffer.UV6Kind
  19072. * - BABYLON.VertexBuffer.ColorKind
  19073. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19074. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19075. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19076. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19077. */
  19078. Mesh.prototype.getVerticesDataKinds = function () {
  19079. if (!this._geometry) {
  19080. var result = [];
  19081. if (this._delayInfo) {
  19082. for (var kind in this._delayInfo) {
  19083. result.push(kind);
  19084. }
  19085. }
  19086. return result;
  19087. }
  19088. return this._geometry.getVerticesDataKinds();
  19089. };
  19090. /**
  19091. * Returns a positive integer : the total number of indices in this mesh geometry.
  19092. * Returns zero if the mesh has no geometry.
  19093. */
  19094. Mesh.prototype.getTotalIndices = function () {
  19095. if (!this._geometry) {
  19096. return 0;
  19097. }
  19098. return this._geometry.getTotalIndices();
  19099. };
  19100. /**
  19101. * Returns an array of integers or a Int32Array populated with the mesh indices.
  19102. * 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.
  19103. * Returns an empty array if the mesh has no geometry.
  19104. */
  19105. Mesh.prototype.getIndices = function (copyWhenShared) {
  19106. if (!this._geometry) {
  19107. return [];
  19108. }
  19109. return this._geometry.getIndices(copyWhenShared);
  19110. };
  19111. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19112. get: function () {
  19113. return this._masterMesh !== null && this._masterMesh !== undefined;
  19114. },
  19115. enumerable: true,
  19116. configurable: true
  19117. });
  19118. /**
  19119. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19120. */
  19121. Mesh.prototype.isReady = function () {
  19122. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19123. return false;
  19124. }
  19125. return _super.prototype.isReady.call(this);
  19126. };
  19127. /**
  19128. * Boolean : true if the mesh has been disposed.
  19129. */
  19130. Mesh.prototype.isDisposed = function () {
  19131. return this._isDisposed;
  19132. };
  19133. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19134. get: function () {
  19135. return this._sideOrientation;
  19136. },
  19137. /**
  19138. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19139. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19140. */
  19141. set: function (sideO) {
  19142. this._sideOrientation = sideO;
  19143. },
  19144. enumerable: true,
  19145. configurable: true
  19146. });
  19147. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19148. /**
  19149. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19150. * This property is pertinent only for updatable parametric shapes.
  19151. */
  19152. get: function () {
  19153. return this._areNormalsFrozen;
  19154. },
  19155. enumerable: true,
  19156. configurable: true
  19157. });
  19158. /**
  19159. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19160. * It has no effect at all on other shapes.
  19161. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19162. */
  19163. Mesh.prototype.freezeNormals = function () {
  19164. this._areNormalsFrozen = true;
  19165. };
  19166. /**
  19167. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19168. * It has no effect at all on other shapes.
  19169. * It reactivates the mesh normals computation if it was previously frozen.
  19170. */
  19171. Mesh.prototype.unfreezeNormals = function () {
  19172. this._areNormalsFrozen = false;
  19173. };
  19174. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19175. /**
  19176. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19177. */
  19178. set: function (count) {
  19179. this._overridenInstanceCount = count;
  19180. },
  19181. enumerable: true,
  19182. configurable: true
  19183. });
  19184. // Methods
  19185. Mesh.prototype._preActivate = function () {
  19186. var sceneRenderId = this.getScene().getRenderId();
  19187. if (this._preActivateId === sceneRenderId) {
  19188. return;
  19189. }
  19190. this._preActivateId = sceneRenderId;
  19191. this._visibleInstances = null;
  19192. };
  19193. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19194. if (this._visibleInstances) {
  19195. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19196. }
  19197. };
  19198. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19199. if (!this._visibleInstances) {
  19200. this._visibleInstances = {};
  19201. this._visibleInstances.defaultRenderId = renderId;
  19202. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19203. }
  19204. if (!this._visibleInstances[renderId]) {
  19205. this._visibleInstances[renderId] = new Array();
  19206. }
  19207. this._visibleInstances[renderId].push(instance);
  19208. };
  19209. /**
  19210. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19211. * This means the mesh underlying bounding box and sphere are recomputed.
  19212. */
  19213. Mesh.prototype.refreshBoundingInfo = function () {
  19214. if (this._boundingInfo.isLocked) {
  19215. return;
  19216. }
  19217. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19218. if (data) {
  19219. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19220. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19221. }
  19222. if (this.subMeshes) {
  19223. for (var index = 0; index < this.subMeshes.length; index++) {
  19224. this.subMeshes[index].refreshBoundingInfo();
  19225. }
  19226. }
  19227. this._updateBoundingInfo();
  19228. };
  19229. Mesh.prototype._createGlobalSubMesh = function () {
  19230. var totalVertices = this.getTotalVertices();
  19231. if (!totalVertices || !this.getIndices()) {
  19232. return null;
  19233. }
  19234. this.releaseSubMeshes();
  19235. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19236. };
  19237. Mesh.prototype.subdivide = function (count) {
  19238. if (count < 1) {
  19239. return;
  19240. }
  19241. var totalIndices = this.getTotalIndices();
  19242. var subdivisionSize = (totalIndices / count) | 0;
  19243. var offset = 0;
  19244. // Ensure that subdivisionSize is a multiple of 3
  19245. while (subdivisionSize % 3 !== 0) {
  19246. subdivisionSize++;
  19247. }
  19248. this.releaseSubMeshes();
  19249. for (var index = 0; index < count; index++) {
  19250. if (offset >= totalIndices) {
  19251. break;
  19252. }
  19253. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19254. offset += subdivisionSize;
  19255. }
  19256. this.synchronizeInstances();
  19257. };
  19258. /**
  19259. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19260. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19261. * The `data` are either a numeric array either a Float32Array.
  19262. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19263. * 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).
  19264. * Note that a new underlying VertexBuffer object is created each call.
  19265. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19266. *
  19267. * Possible `kind` values :
  19268. * - BABYLON.VertexBuffer.PositionKind
  19269. * - BABYLON.VertexBuffer.UVKind
  19270. * - BABYLON.VertexBuffer.UV2Kind
  19271. * - BABYLON.VertexBuffer.UV3Kind
  19272. * - BABYLON.VertexBuffer.UV4Kind
  19273. * - BABYLON.VertexBuffer.UV5Kind
  19274. * - BABYLON.VertexBuffer.UV6Kind
  19275. * - BABYLON.VertexBuffer.ColorKind
  19276. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19277. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19278. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19279. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19280. */
  19281. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19282. if (!this._geometry) {
  19283. var vertexData = new BABYLON.VertexData();
  19284. vertexData.set(data, kind);
  19285. var scene = this.getScene();
  19286. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19287. }
  19288. else {
  19289. this._geometry.setVerticesData(kind, data, updatable, stride);
  19290. }
  19291. };
  19292. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19293. if (!this._geometry) {
  19294. var scene = this.getScene();
  19295. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19296. }
  19297. this._geometry.setVerticesBuffer(buffer);
  19298. };
  19299. /**
  19300. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19301. * If the mesh has no geometry, it is simply returned as it is.
  19302. * The `data` are either a numeric array either a Float32Array.
  19303. * No new underlying VertexBuffer object is created.
  19304. * 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.
  19305. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19306. *
  19307. * Possible `kind` values :
  19308. * - BABYLON.VertexBuffer.PositionKind
  19309. * - BABYLON.VertexBuffer.UVKind
  19310. * - BABYLON.VertexBuffer.UV2Kind
  19311. * - BABYLON.VertexBuffer.UV3Kind
  19312. * - BABYLON.VertexBuffer.UV4Kind
  19313. * - BABYLON.VertexBuffer.UV5Kind
  19314. * - BABYLON.VertexBuffer.UV6Kind
  19315. * - BABYLON.VertexBuffer.ColorKind
  19316. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19317. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19318. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19319. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19320. */
  19321. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19322. if (!this._geometry) {
  19323. return;
  19324. }
  19325. if (!makeItUnique) {
  19326. this._geometry.updateVerticesData(kind, data, updateExtends);
  19327. }
  19328. else {
  19329. this.makeGeometryUnique();
  19330. this.updateVerticesData(kind, data, updateExtends, false);
  19331. }
  19332. };
  19333. /**
  19334. * Deprecated since BabylonJS v2.3
  19335. */
  19336. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19337. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19338. if (!this._geometry) {
  19339. return;
  19340. }
  19341. if (!makeItUnique) {
  19342. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19343. }
  19344. else {
  19345. this.makeGeometryUnique();
  19346. this.updateVerticesDataDirectly(kind, data, offset, false);
  19347. }
  19348. };
  19349. /**
  19350. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19351. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19352. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19353. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19354. */
  19355. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19356. if (computeNormals === void 0) { computeNormals = true; }
  19357. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19358. positionFunction(positions);
  19359. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19360. if (computeNormals) {
  19361. var indices = this.getIndices();
  19362. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19363. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19364. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19365. }
  19366. };
  19367. Mesh.prototype.makeGeometryUnique = function () {
  19368. if (!this._geometry) {
  19369. return;
  19370. }
  19371. var oldGeometry = this._geometry;
  19372. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19373. oldGeometry.releaseForMesh(this, true);
  19374. geometry.applyToMesh(this);
  19375. };
  19376. /**
  19377. * Sets the mesh indices.
  19378. * Expects an array populated with integers or a Int32Array.
  19379. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19380. * This method creates a new index buffer each call.
  19381. */
  19382. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19383. if (!this._geometry) {
  19384. var vertexData = new BABYLON.VertexData();
  19385. vertexData.indices = indices;
  19386. var scene = this.getScene();
  19387. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19388. }
  19389. else {
  19390. this._geometry.setIndices(indices, totalVertices);
  19391. }
  19392. };
  19393. /**
  19394. * Invert the geometry to move from a right handed system to a left handed one.
  19395. */
  19396. Mesh.prototype.toLeftHanded = function () {
  19397. if (!this._geometry) {
  19398. return;
  19399. }
  19400. this._geometry.toLeftHanded();
  19401. };
  19402. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19403. var engine = this.getScene().getEngine();
  19404. // Wireframe
  19405. var indexToBind;
  19406. if (this._unIndexed) {
  19407. indexToBind = null;
  19408. }
  19409. else {
  19410. switch (fillMode) {
  19411. case BABYLON.Material.PointFillMode:
  19412. indexToBind = null;
  19413. break;
  19414. case BABYLON.Material.WireFrameFillMode:
  19415. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19416. break;
  19417. default:
  19418. case BABYLON.Material.TriangleFillMode:
  19419. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19420. break;
  19421. }
  19422. }
  19423. // VBOs
  19424. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19425. };
  19426. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19427. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19428. return;
  19429. }
  19430. this.onBeforeDrawObservable.notifyObservers(this);
  19431. var engine = this.getScene().getEngine();
  19432. // Draw order
  19433. switch (fillMode) {
  19434. case BABYLON.Material.PointFillMode:
  19435. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19436. break;
  19437. case BABYLON.Material.WireFrameFillMode:
  19438. if (this._unIndexed) {
  19439. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19440. }
  19441. else {
  19442. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19443. }
  19444. break;
  19445. default:
  19446. if (this._unIndexed) {
  19447. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19448. }
  19449. else {
  19450. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19451. }
  19452. }
  19453. };
  19454. /**
  19455. * Registers for this mesh a javascript function called just before the rendering process.
  19456. * This function is passed the current mesh and doesn't return anything.
  19457. */
  19458. Mesh.prototype.registerBeforeRender = function (func) {
  19459. this.onBeforeRenderObservable.add(func);
  19460. };
  19461. /**
  19462. * Disposes a previously registered javascript function called before the rendering.
  19463. * This function is passed the current mesh and doesn't return anything.
  19464. */
  19465. Mesh.prototype.unregisterBeforeRender = function (func) {
  19466. this.onBeforeRenderObservable.removeCallback(func);
  19467. };
  19468. /**
  19469. * Registers for this mesh a javascript function called just after the rendering is complete.
  19470. * This function is passed the current mesh and doesn't return anything.
  19471. */
  19472. Mesh.prototype.registerAfterRender = function (func) {
  19473. this.onAfterRenderObservable.add(func);
  19474. };
  19475. /**
  19476. * Disposes a previously registered javascript function called after the rendering.
  19477. * This function is passed the current mesh and doesn't return anything.
  19478. */
  19479. Mesh.prototype.unregisterAfterRender = function (func) {
  19480. this.onAfterRenderObservable.removeCallback(func);
  19481. };
  19482. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19483. var scene = this.getScene();
  19484. this._batchCache.mustReturn = false;
  19485. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19486. this._batchCache.visibleInstances[subMeshId] = null;
  19487. if (this._visibleInstances) {
  19488. var currentRenderId = scene.getRenderId();
  19489. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19490. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19491. var selfRenderId = this._renderId;
  19492. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19493. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19494. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19495. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19496. }
  19497. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19498. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19499. this._batchCache.mustReturn = true;
  19500. return this._batchCache;
  19501. }
  19502. if (currentRenderId !== selfRenderId) {
  19503. this._batchCache.renderSelf[subMeshId] = false;
  19504. }
  19505. }
  19506. this._renderIdForInstances[subMeshId] = currentRenderId;
  19507. }
  19508. return this._batchCache;
  19509. };
  19510. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19511. var visibleInstances = batch.visibleInstances[subMesh._id];
  19512. var matricesCount = visibleInstances.length + 1;
  19513. var bufferSize = matricesCount * 16 * 4;
  19514. var currentInstancesBufferSize = this._instancesBufferSize;
  19515. var instancesBuffer = this._instancesBuffer;
  19516. while (this._instancesBufferSize < bufferSize) {
  19517. this._instancesBufferSize *= 2;
  19518. }
  19519. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19520. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19521. }
  19522. var offset = 0;
  19523. var instancesCount = 0;
  19524. var world = this.getWorldMatrix();
  19525. if (batch.renderSelf[subMesh._id]) {
  19526. world.copyToArray(this._instancesData, offset);
  19527. offset += 16;
  19528. instancesCount++;
  19529. }
  19530. if (visibleInstances) {
  19531. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19532. var instance = visibleInstances[instanceIndex];
  19533. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19534. offset += 16;
  19535. instancesCount++;
  19536. }
  19537. }
  19538. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19539. if (instancesBuffer) {
  19540. instancesBuffer.dispose();
  19541. }
  19542. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19543. this._instancesBuffer = instancesBuffer;
  19544. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19545. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19546. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19547. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19548. }
  19549. else {
  19550. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19551. }
  19552. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  19553. this._draw(subMesh, fillMode, instancesCount);
  19554. engine.unbindInstanceAttributes();
  19555. };
  19556. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19557. var scene = this.getScene();
  19558. var engine = scene.getEngine();
  19559. if (hardwareInstancedRendering) {
  19560. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19561. }
  19562. else {
  19563. if (batch.renderSelf[subMesh._id]) {
  19564. // Draw
  19565. if (onBeforeDraw) {
  19566. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19567. }
  19568. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19569. }
  19570. if (batch.visibleInstances[subMesh._id]) {
  19571. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19572. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19573. // World
  19574. var world = instance.getWorldMatrix();
  19575. if (onBeforeDraw) {
  19576. onBeforeDraw(true, world, effectiveMaterial);
  19577. }
  19578. // Draw
  19579. this._draw(subMesh, fillMode);
  19580. }
  19581. }
  19582. }
  19583. };
  19584. /**
  19585. * Triggers the draw call for the mesh.
  19586. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19587. */
  19588. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19589. var scene = this.getScene();
  19590. // Managing instances
  19591. var batch = this._getInstancesRenderList(subMesh._id);
  19592. if (batch.mustReturn) {
  19593. return;
  19594. }
  19595. // Checking geometry state
  19596. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19597. return;
  19598. }
  19599. var callbackIndex;
  19600. this.onBeforeRenderObservable.notifyObservers(this);
  19601. var engine = scene.getEngine();
  19602. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19603. // Material
  19604. var effectiveMaterial = subMesh.getMaterial();
  19605. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19606. return;
  19607. }
  19608. // Outline - step 1
  19609. var savedDepthWrite = engine.getDepthWrite();
  19610. if (this.renderOutline) {
  19611. engine.setDepthWrite(false);
  19612. scene.getOutlineRenderer().render(subMesh, batch);
  19613. engine.setDepthWrite(savedDepthWrite);
  19614. }
  19615. effectiveMaterial._preBind();
  19616. var effect = effectiveMaterial.getEffect();
  19617. // Bind
  19618. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19619. this._bind(subMesh, effect, fillMode);
  19620. var world = this.getWorldMatrix();
  19621. effectiveMaterial.bind(world, this);
  19622. // Alpha mode
  19623. if (enableAlphaMode) {
  19624. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19625. }
  19626. // Draw
  19627. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  19628. // Unbind
  19629. effectiveMaterial.unbind();
  19630. // Outline - step 2
  19631. if (this.renderOutline && savedDepthWrite) {
  19632. engine.setDepthWrite(true);
  19633. engine.setColorWrite(false);
  19634. scene.getOutlineRenderer().render(subMesh, batch);
  19635. engine.setColorWrite(true);
  19636. }
  19637. // Overlay
  19638. if (this.renderOverlay) {
  19639. var currentMode = engine.getAlphaMode();
  19640. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19641. scene.getOutlineRenderer().render(subMesh, batch, true);
  19642. engine.setAlphaMode(currentMode);
  19643. }
  19644. this.onAfterRenderObservable.notifyObservers(this);
  19645. };
  19646. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19647. if (isInstance) {
  19648. effectiveMaterial.bindOnlyWorldMatrix(world);
  19649. }
  19650. };
  19651. /**
  19652. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19653. */
  19654. Mesh.prototype.getEmittedParticleSystems = function () {
  19655. var results = new Array();
  19656. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19657. var particleSystem = this.getScene().particleSystems[index];
  19658. if (particleSystem.emitter === this) {
  19659. results.push(particleSystem);
  19660. }
  19661. }
  19662. return results;
  19663. };
  19664. /**
  19665. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19666. */
  19667. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19668. var results = new Array();
  19669. var descendants = this.getDescendants();
  19670. descendants.push(this);
  19671. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19672. var particleSystem = this.getScene().particleSystems[index];
  19673. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19674. results.push(particleSystem);
  19675. }
  19676. }
  19677. return results;
  19678. };
  19679. Mesh.prototype._checkDelayState = function () {
  19680. var scene = this.getScene();
  19681. if (this._geometry) {
  19682. this._geometry.load(scene);
  19683. }
  19684. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19685. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19686. this._queueLoad(this, scene);
  19687. }
  19688. };
  19689. Mesh.prototype._queueLoad = function (mesh, scene) {
  19690. var _this = this;
  19691. scene._addPendingData(mesh);
  19692. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19693. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19694. if (data instanceof ArrayBuffer) {
  19695. _this._delayLoadingFunction(data, _this);
  19696. }
  19697. else {
  19698. _this._delayLoadingFunction(JSON.parse(data), _this);
  19699. }
  19700. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19701. scene._removePendingData(_this);
  19702. }, function () { }, scene.database, getBinaryData);
  19703. };
  19704. /**
  19705. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19706. */
  19707. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19708. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19709. return false;
  19710. }
  19711. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19712. return false;
  19713. }
  19714. this._checkDelayState();
  19715. return true;
  19716. };
  19717. /**
  19718. * Sets the mesh material by the material or multiMaterial `id` property.
  19719. * The material `id` is a string identifying the material or the multiMaterial.
  19720. * This method returns nothing.
  19721. */
  19722. Mesh.prototype.setMaterialByID = function (id) {
  19723. var materials = this.getScene().materials;
  19724. var index;
  19725. for (index = 0; index < materials.length; index++) {
  19726. if (materials[index].id === id) {
  19727. this.material = materials[index];
  19728. return;
  19729. }
  19730. }
  19731. // Multi
  19732. var multiMaterials = this.getScene().multiMaterials;
  19733. for (index = 0; index < multiMaterials.length; index++) {
  19734. if (multiMaterials[index].id === id) {
  19735. this.material = multiMaterials[index];
  19736. return;
  19737. }
  19738. }
  19739. };
  19740. /**
  19741. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19742. */
  19743. Mesh.prototype.getAnimatables = function () {
  19744. var results = [];
  19745. if (this.material) {
  19746. results.push(this.material);
  19747. }
  19748. if (this.skeleton) {
  19749. results.push(this.skeleton);
  19750. }
  19751. return results;
  19752. };
  19753. /**
  19754. * Modifies the mesh geometry according to the passed transformation matrix.
  19755. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19756. * The mesh normals are modified accordingly the same transformation.
  19757. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19758. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19759. */
  19760. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19761. // Position
  19762. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19763. return;
  19764. }
  19765. var submeshes = this.subMeshes.splice(0);
  19766. this._resetPointsArrayCache();
  19767. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19768. var temp = [];
  19769. var index;
  19770. for (index = 0; index < data.length; index += 3) {
  19771. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19772. }
  19773. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19774. // Normals
  19775. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19776. return;
  19777. }
  19778. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19779. temp = [];
  19780. for (index = 0; index < data.length; index += 3) {
  19781. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19782. }
  19783. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19784. // flip faces?
  19785. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19786. this.flipFaces();
  19787. }
  19788. // Restore submeshes
  19789. this.releaseSubMeshes();
  19790. this.subMeshes = submeshes;
  19791. };
  19792. /**
  19793. * Modifies the mesh geometry according to its own current World Matrix.
  19794. * The mesh World Matrix is then reset.
  19795. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19796. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19797. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19798. */
  19799. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19800. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19801. this.scaling.copyFromFloats(1, 1, 1);
  19802. this.position.copyFromFloats(0, 0, 0);
  19803. this.rotation.copyFromFloats(0, 0, 0);
  19804. //only if quaternion is already set
  19805. if (this.rotationQuaternion) {
  19806. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19807. }
  19808. this._worldMatrix = BABYLON.Matrix.Identity();
  19809. };
  19810. // Cache
  19811. Mesh.prototype._resetPointsArrayCache = function () {
  19812. this._positions = null;
  19813. };
  19814. Mesh.prototype._generatePointsArray = function () {
  19815. if (this._positions)
  19816. return true;
  19817. this._positions = [];
  19818. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19819. if (!data) {
  19820. return false;
  19821. }
  19822. for (var index = 0; index < data.length; index += 3) {
  19823. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19824. }
  19825. return true;
  19826. };
  19827. /**
  19828. * Returns a new Mesh object generated from the current mesh properties.
  19829. * This method must not get confused with createInstance().
  19830. * The parameter `name` is a string, the name given to the new mesh.
  19831. * The optional parameter `newParent` can be any Node object (default `null`).
  19832. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19833. * 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.
  19834. */
  19835. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19836. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19837. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19838. };
  19839. /**
  19840. * Disposes the mesh.
  19841. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19842. */
  19843. Mesh.prototype.dispose = function (doNotRecurse) {
  19844. if (this._geometry) {
  19845. this._geometry.releaseForMesh(this, true);
  19846. }
  19847. // Instances
  19848. if (this._instancesBuffer) {
  19849. this._instancesBuffer.dispose();
  19850. this._instancesBuffer = null;
  19851. }
  19852. while (this.instances.length) {
  19853. this.instances[0].dispose();
  19854. }
  19855. _super.prototype.dispose.call(this, doNotRecurse);
  19856. };
  19857. /**
  19858. * Modifies the mesh geometry according to a displacement map.
  19859. * 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.
  19860. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19861. * This method returns nothing.
  19862. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19863. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19864. * 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.
  19865. */
  19866. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  19867. var _this = this;
  19868. var scene = this.getScene();
  19869. var onload = function (img) {
  19870. // Getting height map data
  19871. var canvas = document.createElement("canvas");
  19872. var context = canvas.getContext("2d");
  19873. var heightMapWidth = img.width;
  19874. var heightMapHeight = img.height;
  19875. canvas.width = heightMapWidth;
  19876. canvas.height = heightMapHeight;
  19877. context.drawImage(img, 0, 0);
  19878. // Create VertexData from map data
  19879. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19880. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19881. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  19882. //execute success callback, if set
  19883. if (onSuccess) {
  19884. onSuccess(_this);
  19885. }
  19886. };
  19887. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19888. };
  19889. /**
  19890. * Modifies the mesh geometry according to a displacementMap buffer.
  19891. * 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.
  19892. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19893. * This method returns nothing.
  19894. * 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.
  19895. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19896. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19897. */
  19898. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  19899. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19900. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19901. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19902. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19903. return;
  19904. }
  19905. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19906. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19907. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19908. var position = BABYLON.Vector3.Zero();
  19909. var normal = BABYLON.Vector3.Zero();
  19910. var uv = BABYLON.Vector2.Zero();
  19911. for (var index = 0; index < positions.length; index += 3) {
  19912. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19913. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19914. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19915. // Compute height
  19916. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  19917. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  19918. var pos = (u + v * heightMapWidth) * 4;
  19919. var r = buffer[pos] / 255.0;
  19920. var g = buffer[pos + 1] / 255.0;
  19921. var b = buffer[pos + 2] / 255.0;
  19922. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19923. normal.normalize();
  19924. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19925. position = position.add(normal);
  19926. position.toArray(positions, index);
  19927. }
  19928. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19929. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19930. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19931. };
  19932. /**
  19933. * Modify the mesh to get a flat shading rendering.
  19934. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19935. * This method returns nothing.
  19936. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19937. */
  19938. Mesh.prototype.convertToFlatShadedMesh = function () {
  19939. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19940. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19941. var kinds = this.getVerticesDataKinds();
  19942. var vbs = [];
  19943. var data = [];
  19944. var newdata = [];
  19945. var updatableNormals = false;
  19946. var kindIndex;
  19947. var kind;
  19948. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19949. kind = kinds[kindIndex];
  19950. var vertexBuffer = this.getVertexBuffer(kind);
  19951. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19952. updatableNormals = vertexBuffer.isUpdatable();
  19953. kinds.splice(kindIndex, 1);
  19954. kindIndex--;
  19955. continue;
  19956. }
  19957. vbs[kind] = vertexBuffer;
  19958. data[kind] = vbs[kind].getData();
  19959. newdata[kind] = [];
  19960. }
  19961. // Save previous submeshes
  19962. var previousSubmeshes = this.subMeshes.slice(0);
  19963. var indices = this.getIndices();
  19964. var totalIndices = this.getTotalIndices();
  19965. // Generating unique vertices per face
  19966. var index;
  19967. for (index = 0; index < totalIndices; index++) {
  19968. var vertexIndex = indices[index];
  19969. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19970. kind = kinds[kindIndex];
  19971. var stride = vbs[kind].getStrideSize();
  19972. for (var offset = 0; offset < stride; offset++) {
  19973. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19974. }
  19975. }
  19976. }
  19977. // Updating faces & normal
  19978. var normals = [];
  19979. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19980. for (index = 0; index < totalIndices; index += 3) {
  19981. indices[index] = index;
  19982. indices[index + 1] = index + 1;
  19983. indices[index + 2] = index + 2;
  19984. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19985. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19986. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19987. var p1p2 = p1.subtract(p2);
  19988. var p3p2 = p3.subtract(p2);
  19989. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19990. // Store same normals for every vertex
  19991. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19992. normals.push(normal.x);
  19993. normals.push(normal.y);
  19994. normals.push(normal.z);
  19995. }
  19996. }
  19997. this.setIndices(indices);
  19998. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19999. // Updating vertex buffers
  20000. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20001. kind = kinds[kindIndex];
  20002. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20003. }
  20004. // Updating submeshes
  20005. this.releaseSubMeshes();
  20006. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20007. var previousOne = previousSubmeshes[submeshIndex];
  20008. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20009. }
  20010. this.synchronizeInstances();
  20011. };
  20012. /**
  20013. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20014. * In other words, more vertices, no more indices and a single bigger VBO.
  20015. * This method returns nothing.
  20016. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20017. *
  20018. */
  20019. Mesh.prototype.convertToUnIndexedMesh = function () {
  20020. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20021. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20022. var kinds = this.getVerticesDataKinds();
  20023. var vbs = [];
  20024. var data = [];
  20025. var newdata = [];
  20026. var updatableNormals = false;
  20027. var kindIndex;
  20028. var kind;
  20029. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20030. kind = kinds[kindIndex];
  20031. var vertexBuffer = this.getVertexBuffer(kind);
  20032. vbs[kind] = vertexBuffer;
  20033. data[kind] = vbs[kind].getData();
  20034. newdata[kind] = [];
  20035. }
  20036. // Save previous submeshes
  20037. var previousSubmeshes = this.subMeshes.slice(0);
  20038. var indices = this.getIndices();
  20039. var totalIndices = this.getTotalIndices();
  20040. // Generating unique vertices per face
  20041. var index;
  20042. for (index = 0; index < totalIndices; index++) {
  20043. var vertexIndex = indices[index];
  20044. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20045. kind = kinds[kindIndex];
  20046. var stride = vbs[kind].getStrideSize();
  20047. for (var offset = 0; offset < stride; offset++) {
  20048. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20049. }
  20050. }
  20051. }
  20052. // Updating indices
  20053. for (index = 0; index < totalIndices; index += 3) {
  20054. indices[index] = index;
  20055. indices[index + 1] = index + 1;
  20056. indices[index + 2] = index + 2;
  20057. }
  20058. this.setIndices(indices);
  20059. // Updating vertex buffers
  20060. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20061. kind = kinds[kindIndex];
  20062. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20063. }
  20064. // Updating submeshes
  20065. this.releaseSubMeshes();
  20066. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20067. var previousOne = previousSubmeshes[submeshIndex];
  20068. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20069. }
  20070. this._unIndexed = true;
  20071. this.synchronizeInstances();
  20072. };
  20073. /**
  20074. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20075. * This method returns nothing.
  20076. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20077. */
  20078. Mesh.prototype.flipFaces = function (flipNormals) {
  20079. if (flipNormals === void 0) { flipNormals = false; }
  20080. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20081. var i;
  20082. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20083. for (i = 0; i < vertex_data.normals.length; i++) {
  20084. vertex_data.normals[i] *= -1;
  20085. }
  20086. }
  20087. var temp;
  20088. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20089. // reassign indices
  20090. temp = vertex_data.indices[i + 1];
  20091. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20092. vertex_data.indices[i + 2] = temp;
  20093. }
  20094. vertex_data.applyToMesh(this);
  20095. };
  20096. // Instances
  20097. /**
  20098. * Creates a new InstancedMesh object from the mesh model.
  20099. * An instance shares the same properties and the same material than its model.
  20100. * Only these properties of each instance can then be set individually :
  20101. * - position
  20102. * - rotation
  20103. * - rotationQuaternion
  20104. * - setPivotMatrix
  20105. * - scaling
  20106. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20107. * Warning : this method is not supported for Line mesh and LineSystem
  20108. */
  20109. Mesh.prototype.createInstance = function (name) {
  20110. return new BABYLON.InstancedMesh(name, this);
  20111. };
  20112. /**
  20113. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20114. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20115. * This method returns nothing.
  20116. */
  20117. Mesh.prototype.synchronizeInstances = function () {
  20118. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20119. var instance = this.instances[instanceIndex];
  20120. instance._syncSubMeshes();
  20121. }
  20122. };
  20123. /**
  20124. * Simplify the mesh according to the given array of settings.
  20125. * Function will return immediately and will simplify async. It returns nothing.
  20126. * @param settings a collection of simplification settings.
  20127. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20128. * @param type the type of simplification to run.
  20129. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20130. */
  20131. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20132. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20133. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20134. this.getScene().simplificationQueue.addTask({
  20135. settings: settings,
  20136. parallelProcessing: parallelProcessing,
  20137. mesh: this,
  20138. simplificationType: simplificationType,
  20139. successCallback: successCallback
  20140. });
  20141. };
  20142. /**
  20143. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20144. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20145. * This should be used together with the simplification to avoid disappearing triangles.
  20146. * @param successCallback an optional success callback to be called after the optimization finished.
  20147. */
  20148. Mesh.prototype.optimizeIndices = function (successCallback) {
  20149. var _this = this;
  20150. var indices = this.getIndices();
  20151. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20152. var vectorPositions = [];
  20153. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20154. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20155. }
  20156. var dupes = [];
  20157. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20158. var realPos = vectorPositions.length - 1 - iteration;
  20159. var testedPosition = vectorPositions[realPos];
  20160. for (var j = 0; j < realPos; ++j) {
  20161. var againstPosition = vectorPositions[j];
  20162. if (testedPosition.equals(againstPosition)) {
  20163. dupes[realPos] = j;
  20164. break;
  20165. }
  20166. }
  20167. }, function () {
  20168. for (var i = 0; i < indices.length; ++i) {
  20169. indices[i] = dupes[indices[i]] || indices[i];
  20170. }
  20171. //indices are now reordered
  20172. var originalSubMeshes = _this.subMeshes.slice(0);
  20173. _this.setIndices(indices);
  20174. _this.subMeshes = originalSubMeshes;
  20175. if (successCallback) {
  20176. successCallback(_this);
  20177. }
  20178. });
  20179. };
  20180. // Statics
  20181. /**
  20182. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20183. * The parameter `parsedMesh` is the mesh to be copied.
  20184. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20185. */
  20186. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20187. var mesh = new Mesh(parsedMesh.name, scene);
  20188. mesh.id = parsedMesh.id;
  20189. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20190. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20191. if (parsedMesh.rotationQuaternion) {
  20192. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20193. }
  20194. else if (parsedMesh.rotation) {
  20195. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20196. }
  20197. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20198. if (parsedMesh.localMatrix) {
  20199. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20200. }
  20201. else if (parsedMesh.pivotMatrix) {
  20202. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20203. }
  20204. mesh.setEnabled(parsedMesh.isEnabled);
  20205. mesh.isVisible = parsedMesh.isVisible;
  20206. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20207. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20208. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20209. if (parsedMesh.applyFog !== undefined) {
  20210. mesh.applyFog = parsedMesh.applyFog;
  20211. }
  20212. if (parsedMesh.pickable !== undefined) {
  20213. mesh.isPickable = parsedMesh.pickable;
  20214. }
  20215. if (parsedMesh.alphaIndex !== undefined) {
  20216. mesh.alphaIndex = parsedMesh.alphaIndex;
  20217. }
  20218. mesh.receiveShadows = parsedMesh.receiveShadows;
  20219. mesh.billboardMode = parsedMesh.billboardMode;
  20220. if (parsedMesh.visibility !== undefined) {
  20221. mesh.visibility = parsedMesh.visibility;
  20222. }
  20223. mesh.checkCollisions = parsedMesh.checkCollisions;
  20224. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20225. // freezeWorldMatrix
  20226. if (parsedMesh.freezeWorldMatrix) {
  20227. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20228. }
  20229. // Parent
  20230. if (parsedMesh.parentId) {
  20231. mesh._waitingParentId = parsedMesh.parentId;
  20232. }
  20233. // Actions
  20234. if (parsedMesh.actions !== undefined) {
  20235. mesh._waitingActions = parsedMesh.actions;
  20236. }
  20237. // Geometry
  20238. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20239. if (parsedMesh.delayLoadingFile) {
  20240. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20241. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20242. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20243. if (parsedMesh._binaryInfo) {
  20244. mesh._binaryInfo = parsedMesh._binaryInfo;
  20245. }
  20246. mesh._delayInfo = [];
  20247. if (parsedMesh.hasUVs) {
  20248. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20249. }
  20250. if (parsedMesh.hasUVs2) {
  20251. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20252. }
  20253. if (parsedMesh.hasUVs3) {
  20254. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20255. }
  20256. if (parsedMesh.hasUVs4) {
  20257. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20258. }
  20259. if (parsedMesh.hasUVs5) {
  20260. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20261. }
  20262. if (parsedMesh.hasUVs6) {
  20263. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20264. }
  20265. if (parsedMesh.hasColors) {
  20266. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20267. }
  20268. if (parsedMesh.hasMatricesIndices) {
  20269. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20270. }
  20271. if (parsedMesh.hasMatricesWeights) {
  20272. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20273. }
  20274. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20275. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20276. mesh._checkDelayState();
  20277. }
  20278. }
  20279. else {
  20280. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20281. }
  20282. // Material
  20283. if (parsedMesh.materialId) {
  20284. mesh.setMaterialByID(parsedMesh.materialId);
  20285. }
  20286. else {
  20287. mesh.material = null;
  20288. }
  20289. // Skeleton
  20290. if (parsedMesh.skeletonId > -1) {
  20291. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20292. if (parsedMesh.numBoneInfluencers) {
  20293. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20294. }
  20295. }
  20296. // Animations
  20297. if (parsedMesh.animations) {
  20298. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20299. var parsedAnimation = parsedMesh.animations[animationIndex];
  20300. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20301. }
  20302. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20303. }
  20304. if (parsedMesh.autoAnimate) {
  20305. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20306. }
  20307. // Layer Mask
  20308. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20309. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20310. }
  20311. else {
  20312. mesh.layerMask = 0x0FFFFFFF;
  20313. }
  20314. //(Deprecated) physics
  20315. if (parsedMesh.physicsImpostor) {
  20316. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20317. mass: parsedMesh.physicsMass,
  20318. friction: parsedMesh.physicsFriction,
  20319. restitution: parsedMesh.physicsRestitution
  20320. }, scene);
  20321. }
  20322. // Instances
  20323. if (parsedMesh.instances) {
  20324. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20325. var parsedInstance = parsedMesh.instances[index];
  20326. var instance = mesh.createInstance(parsedInstance.name);
  20327. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20328. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20329. if (parsedInstance.parentId) {
  20330. instance._waitingParentId = parsedInstance.parentId;
  20331. }
  20332. if (parsedInstance.rotationQuaternion) {
  20333. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20334. }
  20335. else if (parsedInstance.rotation) {
  20336. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20337. }
  20338. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20339. instance.checkCollisions = mesh.checkCollisions;
  20340. if (parsedMesh.animations) {
  20341. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20342. parsedAnimation = parsedMesh.animations[animationIndex];
  20343. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20344. }
  20345. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20346. }
  20347. }
  20348. }
  20349. return mesh;
  20350. };
  20351. /**
  20352. * Creates a ribbon mesh.
  20353. * Please consider using the same method from the MeshBuilder class instead.
  20354. * 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.
  20355. *
  20356. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20357. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20358. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20359. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20360. * 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.
  20361. * 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.
  20362. * 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
  20363. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20364. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20365. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20366. */
  20367. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20368. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20369. pathArray: pathArray,
  20370. closeArray: closeArray,
  20371. closePath: closePath,
  20372. offset: offset,
  20373. updatable: updatable,
  20374. sideOrientation: sideOrientation,
  20375. instance: instance
  20376. }, scene);
  20377. };
  20378. /**
  20379. * Creates a plane polygonal mesh. By default, this is a disc.
  20380. * Please consider using the same method from the MeshBuilder class instead.
  20381. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20382. * 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.
  20383. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20384. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20385. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20386. */
  20387. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20388. var options = {
  20389. radius: radius,
  20390. tessellation: tessellation,
  20391. sideOrientation: sideOrientation,
  20392. updatable: updatable
  20393. };
  20394. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20395. };
  20396. /**
  20397. * Creates a box mesh.
  20398. * Please consider using the same method from the MeshBuilder class instead.
  20399. * The parameter `size` sets the size (float) of each box side (default 1).
  20400. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20401. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20402. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20403. */
  20404. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20405. var options = {
  20406. size: size,
  20407. sideOrientation: sideOrientation,
  20408. updatable: updatable
  20409. };
  20410. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20411. };
  20412. /**
  20413. * Creates a sphere mesh.
  20414. * Please consider using the same method from the MeshBuilder class instead.
  20415. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20416. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20417. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20418. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20420. */
  20421. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20422. var options = {
  20423. segments: segments,
  20424. diameterX: diameter,
  20425. diameterY: diameter,
  20426. diameterZ: diameter,
  20427. sideOrientation: sideOrientation,
  20428. updatable: updatable
  20429. };
  20430. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20431. };
  20432. /**
  20433. * Creates a cylinder or a cone mesh.
  20434. * Please consider using the same method from the MeshBuilder class instead.
  20435. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20436. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20437. * 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.
  20438. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20439. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20440. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20441. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20443. */
  20444. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20445. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20446. if (scene !== undefined) {
  20447. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20448. updatable = scene;
  20449. }
  20450. scene = subdivisions;
  20451. subdivisions = 1;
  20452. }
  20453. var options = {
  20454. height: height,
  20455. diameterTop: diameterTop,
  20456. diameterBottom: diameterBottom,
  20457. tessellation: tessellation,
  20458. subdivisions: subdivisions,
  20459. sideOrientation: sideOrientation,
  20460. updatable: updatable
  20461. };
  20462. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20463. };
  20464. // Torus (Code from SharpDX.org)
  20465. /**
  20466. * Creates a torus mesh.
  20467. * Please consider using the same method from the MeshBuilder class instead.
  20468. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20469. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20470. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20472. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20474. */
  20475. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20476. var options = {
  20477. diameter: diameter,
  20478. thickness: thickness,
  20479. tessellation: tessellation,
  20480. sideOrientation: sideOrientation,
  20481. updatable: updatable
  20482. };
  20483. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20484. };
  20485. /**
  20486. * Creates a torus knot mesh.
  20487. * Please consider using the same method from the MeshBuilder class instead.
  20488. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20489. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20490. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20491. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20492. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20493. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20494. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20495. */
  20496. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20497. var options = {
  20498. radius: radius,
  20499. tube: tube,
  20500. radialSegments: radialSegments,
  20501. tubularSegments: tubularSegments,
  20502. p: p,
  20503. q: q,
  20504. sideOrientation: sideOrientation,
  20505. updatable: updatable
  20506. };
  20507. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20508. };
  20509. /**
  20510. * Creates a line mesh.
  20511. * Please consider using the same method from the MeshBuilder class instead.
  20512. * 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.
  20513. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20514. * The parameter `points` is an array successive Vector3.
  20515. * 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
  20516. * When updating an instance, remember that only point positions can change, not the number of points.
  20517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20518. */
  20519. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20520. var options = {
  20521. points: points,
  20522. updatable: updatable,
  20523. instance: instance
  20524. };
  20525. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20526. };
  20527. /**
  20528. * Creates a dashed line mesh.
  20529. * Please consider using the same method from the MeshBuilder class instead.
  20530. * 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.
  20531. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20532. * The parameter `points` is an array successive Vector3.
  20533. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20534. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20535. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20536. * 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
  20537. * When updating an instance, remember that only point positions can change, not the number of points.
  20538. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20539. */
  20540. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20541. var options = {
  20542. points: points,
  20543. dashSize: dashSize,
  20544. gapSize: gapSize,
  20545. dashNb: dashNb,
  20546. updatable: updatable,
  20547. instance: instance
  20548. };
  20549. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20550. };
  20551. /**
  20552. * Creates an extruded shape mesh.
  20553. * 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.
  20554. * Please consider using the same method from the MeshBuilder class instead.
  20555. *
  20556. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20557. * 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
  20558. * extruded along the Z axis.
  20559. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20560. * 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.
  20561. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20562. * 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
  20563. * 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
  20564. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20565. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20566. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20567. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20568. */
  20569. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20570. var options = {
  20571. shape: shape,
  20572. path: path,
  20573. scale: scale,
  20574. rotation: rotation,
  20575. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20576. sideOrientation: sideOrientation,
  20577. instance: instance,
  20578. updatable: updatable
  20579. };
  20580. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20581. };
  20582. /**
  20583. * Creates an custom extruded shape mesh.
  20584. * 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.
  20585. * Please consider using the same method from the MeshBuilder class instead.
  20586. *
  20587. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20588. * 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
  20589. * extruded along the Z axis.
  20590. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20591. * 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
  20592. * and the distance of this point from the begining of the path :
  20593. * ```javascript
  20594. * var rotationFunction = function(i, distance) {
  20595. * // do things
  20596. * return rotationValue; }
  20597. * ```
  20598. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20599. * 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
  20600. * and the distance of this point from the begining of the path :
  20601. * ```javascript
  20602. * var scaleFunction = function(i, distance) {
  20603. * // do things
  20604. * return scaleValue;}
  20605. * ```
  20606. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20607. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20608. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20609. * 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
  20610. * 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
  20611. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20612. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20613. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20615. */
  20616. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20617. var options = {
  20618. shape: shape,
  20619. path: path,
  20620. scaleFunction: scaleFunction,
  20621. rotationFunction: rotationFunction,
  20622. ribbonCloseArray: ribbonCloseArray,
  20623. ribbonClosePath: ribbonClosePath,
  20624. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20625. sideOrientation: sideOrientation,
  20626. instance: instance,
  20627. updatable: updatable
  20628. };
  20629. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20630. };
  20631. /**
  20632. * Creates lathe mesh.
  20633. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20634. * Please consider using the same method from the MeshBuilder class instead.
  20635. * 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
  20636. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20637. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20638. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20639. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20640. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20641. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20642. */
  20643. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20644. var options = {
  20645. shape: shape,
  20646. radius: radius,
  20647. tessellation: tessellation,
  20648. sideOrientation: sideOrientation,
  20649. updatable: updatable
  20650. };
  20651. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20652. };
  20653. /**
  20654. * Creates a plane mesh.
  20655. * Please consider using the same method from the MeshBuilder class instead.
  20656. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20657. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20658. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20660. */
  20661. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20662. var options = {
  20663. size: size,
  20664. width: size,
  20665. height: size,
  20666. sideOrientation: sideOrientation,
  20667. updatable: updatable
  20668. };
  20669. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20670. };
  20671. /**
  20672. * Creates a ground mesh.
  20673. * Please consider using the same method from the MeshBuilder class instead.
  20674. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20675. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20676. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20677. */
  20678. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20679. var options = {
  20680. width: width,
  20681. height: height,
  20682. subdivisions: subdivisions,
  20683. updatable: updatable
  20684. };
  20685. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20686. };
  20687. /**
  20688. * Creates a tiled ground mesh.
  20689. * Please consider using the same method from the MeshBuilder class instead.
  20690. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20691. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20692. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20693. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20694. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20695. * numbers of subdivisions on the ground width and height of each tile.
  20696. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20697. */
  20698. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20699. var options = {
  20700. xmin: xmin,
  20701. zmin: zmin,
  20702. xmax: xmax,
  20703. zmax: zmax,
  20704. subdivisions: subdivisions,
  20705. precision: precision,
  20706. updatable: updatable
  20707. };
  20708. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20709. };
  20710. /**
  20711. * Creates a ground mesh from a height map.
  20712. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20713. * Please consider using the same method from the MeshBuilder class instead.
  20714. * The parameter `url` sets the URL of the height map image resource.
  20715. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20716. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20717. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20718. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20719. * 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).
  20720. * This function is passed the newly built mesh :
  20721. * ```javascript
  20722. * function(mesh) { // do things
  20723. * return; }
  20724. * ```
  20725. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20726. */
  20727. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20728. var options = {
  20729. width: width,
  20730. height: height,
  20731. subdivisions: subdivisions,
  20732. minHeight: minHeight,
  20733. maxHeight: maxHeight,
  20734. updatable: updatable,
  20735. onReady: onReady
  20736. };
  20737. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20738. };
  20739. /**
  20740. * Creates a tube mesh.
  20741. * 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.
  20742. * Please consider using the same method from the MeshBuilder class instead.
  20743. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20744. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20745. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20746. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20747. * 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.
  20748. * It must return a radius value (positive float) :
  20749. * ```javascript
  20750. * var radiusFunction = function(i, distance) {
  20751. * // do things
  20752. * return radius; }
  20753. * ```
  20754. * 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
  20755. * 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
  20756. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20757. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20758. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20759. */
  20760. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20761. var options = {
  20762. path: path,
  20763. radius: radius,
  20764. tessellation: tessellation,
  20765. radiusFunction: radiusFunction,
  20766. arc: 1,
  20767. cap: cap,
  20768. updatable: updatable,
  20769. sideOrientation: sideOrientation,
  20770. instance: instance
  20771. };
  20772. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20773. };
  20774. /**
  20775. * Creates a polyhedron mesh.
  20776. * Please consider using the same method from the MeshBuilder class instead.
  20777. * 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
  20778. * to choose the wanted type.
  20779. * The parameter `size` (positive float, default 1) sets the polygon size.
  20780. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20781. * 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`.
  20782. * 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
  20783. * 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)`).
  20784. * 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
  20785. * 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.
  20786. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20787. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20789. */
  20790. Mesh.CreatePolyhedron = function (name, options, scene) {
  20791. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20792. };
  20793. /**
  20794. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20795. * Please consider using the same method from the MeshBuilder class instead.
  20796. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20797. * 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`).
  20798. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20799. * 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.
  20800. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20801. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20802. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20803. */
  20804. Mesh.CreateIcoSphere = function (name, options, scene) {
  20805. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20806. };
  20807. /**
  20808. * Creates a decal mesh.
  20809. * Please consider using the same method from the MeshBuilder class instead.
  20810. * 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.
  20811. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20812. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20813. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20814. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20815. */
  20816. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20817. var options = {
  20818. position: position,
  20819. normal: normal,
  20820. size: size,
  20821. angle: angle
  20822. };
  20823. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20824. };
  20825. // Skeletons
  20826. /**
  20827. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20828. */
  20829. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20830. var source;
  20831. if (!this._sourcePositions) {
  20832. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20833. this._sourcePositions = new Float32Array(source);
  20834. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20835. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20836. }
  20837. }
  20838. return this._sourcePositions;
  20839. };
  20840. /**
  20841. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20842. */
  20843. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20844. var source;
  20845. if (!this._sourceNormals) {
  20846. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20847. this._sourceNormals = new Float32Array(source);
  20848. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20849. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20850. }
  20851. }
  20852. return this._sourceNormals;
  20853. };
  20854. /**
  20855. * Update the vertex buffers by applying transformation from the bones
  20856. * @param {skeleton} skeleton to apply
  20857. */
  20858. Mesh.prototype.applySkeleton = function (skeleton) {
  20859. if (!this.geometry) {
  20860. return;
  20861. }
  20862. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20863. return;
  20864. }
  20865. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20866. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20867. return this;
  20868. }
  20869. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20870. return this;
  20871. }
  20872. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20873. return this;
  20874. }
  20875. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20876. return this;
  20877. }
  20878. if (!this._sourcePositions) {
  20879. this.setPositionsForCPUSkinning();
  20880. }
  20881. if (!this._sourceNormals) {
  20882. this.setNormalsForCPUSkinning();
  20883. }
  20884. // positionsData checks for not being Float32Array will only pass at most once
  20885. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20886. if (!(positionsData instanceof Float32Array)) {
  20887. positionsData = new Float32Array(positionsData);
  20888. }
  20889. // normalsData checks for not being Float32Array will only pass at most once
  20890. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20891. if (!(normalsData instanceof Float32Array)) {
  20892. normalsData = new Float32Array(normalsData);
  20893. }
  20894. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20895. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20896. var needExtras = this.numBoneInfluencers > 4;
  20897. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20898. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20899. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20900. var tempVector3 = BABYLON.Vector3.Zero();
  20901. var finalMatrix = new BABYLON.Matrix();
  20902. var tempMatrix = new BABYLON.Matrix();
  20903. var matWeightIdx = 0;
  20904. var inf;
  20905. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20906. var weight;
  20907. for (inf = 0; inf < 4; inf++) {
  20908. weight = matricesWeightsData[matWeightIdx + inf];
  20909. if (weight > 0) {
  20910. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20911. finalMatrix.addToSelf(tempMatrix);
  20912. }
  20913. else
  20914. break;
  20915. }
  20916. if (needExtras) {
  20917. for (inf = 0; inf < 4; inf++) {
  20918. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20919. if (weight > 0) {
  20920. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20921. finalMatrix.addToSelf(tempMatrix);
  20922. }
  20923. else
  20924. break;
  20925. }
  20926. }
  20927. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20928. tempVector3.toArray(positionsData, index);
  20929. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20930. tempVector3.toArray(normalsData, index);
  20931. finalMatrix.reset();
  20932. }
  20933. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20934. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20935. return this;
  20936. };
  20937. // Tools
  20938. /**
  20939. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20940. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20941. */
  20942. Mesh.MinMax = function (meshes) {
  20943. var minVector = null;
  20944. var maxVector = null;
  20945. for (var i in meshes) {
  20946. var mesh = meshes[i];
  20947. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20948. if (!minVector) {
  20949. minVector = boundingBox.minimumWorld;
  20950. maxVector = boundingBox.maximumWorld;
  20951. continue;
  20952. }
  20953. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20954. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20955. }
  20956. return {
  20957. min: minVector,
  20958. max: maxVector
  20959. };
  20960. };
  20961. /**
  20962. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20963. */
  20964. Mesh.Center = function (meshesOrMinMaxVector) {
  20965. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  20966. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20967. };
  20968. /**
  20969. * Merge the array of meshes into a single mesh for performance reasons.
  20970. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20971. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20972. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20973. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20974. */
  20975. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  20976. if (disposeSource === void 0) { disposeSource = true; }
  20977. var index;
  20978. if (!allow32BitsIndices) {
  20979. var totalVertices = 0;
  20980. // Counting vertices
  20981. for (index = 0; index < meshes.length; index++) {
  20982. if (meshes[index]) {
  20983. totalVertices += meshes[index].getTotalVertices();
  20984. if (totalVertices > 65536) {
  20985. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20986. return null;
  20987. }
  20988. }
  20989. }
  20990. }
  20991. // Merge
  20992. var vertexData;
  20993. var otherVertexData;
  20994. var source;
  20995. for (index = 0; index < meshes.length; index++) {
  20996. if (meshes[index]) {
  20997. meshes[index].computeWorldMatrix(true);
  20998. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20999. otherVertexData.transform(meshes[index].getWorldMatrix());
  21000. if (vertexData) {
  21001. vertexData.merge(otherVertexData);
  21002. }
  21003. else {
  21004. vertexData = otherVertexData;
  21005. source = meshes[index];
  21006. }
  21007. }
  21008. }
  21009. if (!meshSubclass) {
  21010. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21011. }
  21012. vertexData.applyToMesh(meshSubclass);
  21013. // Setting properties
  21014. meshSubclass.material = source.material;
  21015. meshSubclass.checkCollisions = source.checkCollisions;
  21016. // Cleaning
  21017. if (disposeSource) {
  21018. for (index = 0; index < meshes.length; index++) {
  21019. if (meshes[index]) {
  21020. meshes[index].dispose();
  21021. }
  21022. }
  21023. }
  21024. return meshSubclass;
  21025. };
  21026. // Consts
  21027. Mesh._FRONTSIDE = 0;
  21028. Mesh._BACKSIDE = 1;
  21029. Mesh._DOUBLESIDE = 2;
  21030. Mesh._DEFAULTSIDE = 0;
  21031. Mesh._NO_CAP = 0;
  21032. Mesh._CAP_START = 1;
  21033. Mesh._CAP_END = 2;
  21034. Mesh._CAP_ALL = 3;
  21035. return Mesh;
  21036. })(BABYLON.AbstractMesh);
  21037. BABYLON.Mesh = Mesh;
  21038. })(BABYLON || (BABYLON = {}));
  21039. var BABYLON;
  21040. (function (BABYLON) {
  21041. var SubMesh = (function () {
  21042. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21043. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21044. this.materialIndex = materialIndex;
  21045. this.verticesStart = verticesStart;
  21046. this.verticesCount = verticesCount;
  21047. this.indexStart = indexStart;
  21048. this.indexCount = indexCount;
  21049. this._renderId = 0;
  21050. this._mesh = mesh;
  21051. this._renderingMesh = renderingMesh || mesh;
  21052. mesh.subMeshes.push(this);
  21053. this._trianglePlanes = [];
  21054. this._id = mesh.subMeshes.length - 1;
  21055. if (createBoundingBox) {
  21056. this.refreshBoundingInfo();
  21057. mesh.computeWorldMatrix(true);
  21058. }
  21059. }
  21060. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21061. get: function () {
  21062. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21063. },
  21064. enumerable: true,
  21065. configurable: true
  21066. });
  21067. SubMesh.prototype.getBoundingInfo = function () {
  21068. if (this.IsGlobal) {
  21069. return this._mesh.getBoundingInfo();
  21070. }
  21071. return this._boundingInfo;
  21072. };
  21073. SubMesh.prototype.getMesh = function () {
  21074. return this._mesh;
  21075. };
  21076. SubMesh.prototype.getRenderingMesh = function () {
  21077. return this._renderingMesh;
  21078. };
  21079. SubMesh.prototype.getMaterial = function () {
  21080. var rootMaterial = this._renderingMesh.material;
  21081. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  21082. var multiMaterial = rootMaterial;
  21083. return multiMaterial.getSubMaterial(this.materialIndex);
  21084. }
  21085. if (!rootMaterial) {
  21086. return this._mesh.getScene().defaultMaterial;
  21087. }
  21088. return rootMaterial;
  21089. };
  21090. // Methods
  21091. SubMesh.prototype.refreshBoundingInfo = function () {
  21092. this._lastColliderWorldVertices = null;
  21093. if (this.IsGlobal) {
  21094. return;
  21095. }
  21096. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21097. if (!data) {
  21098. this._boundingInfo = this._mesh._boundingInfo;
  21099. return;
  21100. }
  21101. var indices = this._renderingMesh.getIndices();
  21102. var extend;
  21103. //is this the only submesh?
  21104. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21105. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21106. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21107. }
  21108. else {
  21109. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21110. }
  21111. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21112. };
  21113. SubMesh.prototype._checkCollision = function (collider) {
  21114. return this.getBoundingInfo()._checkCollision(collider);
  21115. };
  21116. SubMesh.prototype.updateBoundingInfo = function (world) {
  21117. if (!this.getBoundingInfo()) {
  21118. this.refreshBoundingInfo();
  21119. }
  21120. this.getBoundingInfo().update(world);
  21121. };
  21122. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21123. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21124. };
  21125. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21126. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21127. };
  21128. SubMesh.prototype.render = function (enableAlphaMode) {
  21129. this._renderingMesh.render(this, enableAlphaMode);
  21130. };
  21131. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21132. if (!this._linesIndexBuffer) {
  21133. var linesIndices = [];
  21134. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21135. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21136. }
  21137. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21138. this.linesIndexCount = linesIndices.length;
  21139. }
  21140. return this._linesIndexBuffer;
  21141. };
  21142. SubMesh.prototype.canIntersects = function (ray) {
  21143. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21144. };
  21145. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21146. var intersectInfo = null;
  21147. // LineMesh first as it's also a Mesh...
  21148. if (this._mesh instanceof BABYLON.LinesMesh) {
  21149. var lineMesh = this._mesh;
  21150. // Line test
  21151. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21152. var p0 = positions[indices[index]];
  21153. var p1 = positions[indices[index + 1]];
  21154. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21155. if (length < 0) {
  21156. continue;
  21157. }
  21158. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21159. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21160. if (fastCheck) {
  21161. break;
  21162. }
  21163. }
  21164. }
  21165. }
  21166. else {
  21167. // Triangles test
  21168. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21169. var p0 = positions[indices[index]];
  21170. var p1 = positions[indices[index + 1]];
  21171. var p2 = positions[indices[index + 2]];
  21172. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21173. if (currentIntersectInfo) {
  21174. if (currentIntersectInfo.distance < 0) {
  21175. continue;
  21176. }
  21177. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21178. intersectInfo = currentIntersectInfo;
  21179. intersectInfo.faceId = index / 3;
  21180. if (fastCheck) {
  21181. break;
  21182. }
  21183. }
  21184. }
  21185. }
  21186. }
  21187. return intersectInfo;
  21188. };
  21189. // Clone
  21190. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21191. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21192. if (!this.IsGlobal) {
  21193. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21194. }
  21195. return result;
  21196. };
  21197. // Dispose
  21198. SubMesh.prototype.dispose = function () {
  21199. if (this._linesIndexBuffer) {
  21200. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21201. this._linesIndexBuffer = null;
  21202. }
  21203. // Remove from mesh
  21204. var index = this._mesh.subMeshes.indexOf(this);
  21205. this._mesh.subMeshes.splice(index, 1);
  21206. };
  21207. // Statics
  21208. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21209. var minVertexIndex = Number.MAX_VALUE;
  21210. var maxVertexIndex = -Number.MAX_VALUE;
  21211. renderingMesh = renderingMesh || mesh;
  21212. var indices = renderingMesh.getIndices();
  21213. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21214. var vertexIndex = indices[index];
  21215. if (vertexIndex < minVertexIndex)
  21216. minVertexIndex = vertexIndex;
  21217. if (vertexIndex > maxVertexIndex)
  21218. maxVertexIndex = vertexIndex;
  21219. }
  21220. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21221. };
  21222. return SubMesh;
  21223. })();
  21224. BABYLON.SubMesh = SubMesh;
  21225. })(BABYLON || (BABYLON = {}));
  21226. var BABYLON;
  21227. (function (BABYLON) {
  21228. var MeshBuilder = (function () {
  21229. function MeshBuilder() {
  21230. }
  21231. MeshBuilder.updateSideOrientationForRightHandedSystem = function (orientation, scene) {
  21232. if (!scene.useRightHandedSystem) {
  21233. if (orientation === undefined || orientation === null) {
  21234. return BABYLON.Mesh.FRONTSIDE;
  21235. }
  21236. switch (orientation) {
  21237. case BABYLON.Mesh.FRONTSIDE:
  21238. case BABYLON.Mesh.DEFAULTSIDE:
  21239. return BABYLON.Mesh.FRONTSIDE;
  21240. default:
  21241. return BABYLON.Mesh.BACKSIDE;
  21242. }
  21243. }
  21244. if (orientation === undefined || orientation === null) {
  21245. return BABYLON.Mesh.BACKSIDE;
  21246. }
  21247. switch (orientation) {
  21248. case BABYLON.Mesh.FRONTSIDE:
  21249. case BABYLON.Mesh.DEFAULTSIDE:
  21250. return BABYLON.Mesh.BACKSIDE;
  21251. default:
  21252. return BABYLON.Mesh.FRONTSIDE;
  21253. }
  21254. };
  21255. /**
  21256. * Creates a box mesh.
  21257. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  21258. * The parameter `size` sets the size (float) of each box side (default 1).
  21259. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  21260. * 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).
  21261. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21262. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21263. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21264. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21265. */
  21266. MeshBuilder.CreateBox = function (name, options, scene) {
  21267. var box = new BABYLON.Mesh(name, scene);
  21268. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21269. var vertexData = BABYLON.VertexData.CreateBox(options);
  21270. vertexData.applyToMesh(box, options.updatable);
  21271. return box;
  21272. };
  21273. /**
  21274. * Creates a sphere mesh.
  21275. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  21276. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21277. * 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`).
  21278. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21279. * 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
  21280. * 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).
  21281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21282. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21284. */
  21285. MeshBuilder.CreateSphere = function (name, options, scene) {
  21286. var sphere = new BABYLON.Mesh(name, scene);
  21287. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21288. var vertexData = BABYLON.VertexData.CreateSphere(options);
  21289. vertexData.applyToMesh(sphere, options.updatable);
  21290. return sphere;
  21291. };
  21292. /**
  21293. * Creates a plane polygonal mesh. By default, this is a disc.
  21294. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  21295. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21296. * 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.
  21297. * 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
  21298. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21299. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21301. */
  21302. MeshBuilder.CreateDisc = function (name, options, scene) {
  21303. var disc = new BABYLON.Mesh(name, scene);
  21304. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21305. var vertexData = BABYLON.VertexData.CreateDisc(options);
  21306. vertexData.applyToMesh(disc, options.updatable);
  21307. return disc;
  21308. };
  21309. /**
  21310. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21311. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  21312. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21313. * 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`).
  21314. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21315. * 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.
  21316. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21317. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21318. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21319. */
  21320. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  21321. var sphere = new BABYLON.Mesh(name, scene);
  21322. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21323. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  21324. vertexData.applyToMesh(sphere, options.updatable);
  21325. return sphere;
  21326. };
  21327. ;
  21328. /**
  21329. * Creates a ribbon mesh.
  21330. * 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.
  21331. *
  21332. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21333. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21334. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21335. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21336. * 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.
  21337. * 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.
  21338. * 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
  21339. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21340. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21341. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21342. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21343. */
  21344. MeshBuilder.CreateRibbon = function (name, options, scene) {
  21345. var pathArray = options.pathArray;
  21346. var closeArray = options.closeArray;
  21347. var closePath = options.closePath;
  21348. var offset = options.offset;
  21349. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21350. var instance = options.instance;
  21351. var updatable = options.updatable;
  21352. if (instance) {
  21353. // positionFunction : ribbon case
  21354. // only pathArray and sideOrientation parameters are taken into account for positions update
  21355. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  21356. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  21357. var positionFunction = function (positions) {
  21358. var minlg = pathArray[0].length;
  21359. var i = 0;
  21360. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  21361. for (var si = 1; si <= ns; si++) {
  21362. for (var p = 0; p < pathArray.length; p++) {
  21363. var path = pathArray[p];
  21364. var l = path.length;
  21365. minlg = (minlg < l) ? minlg : l;
  21366. var j = 0;
  21367. while (j < minlg) {
  21368. positions[i] = path[j].x;
  21369. positions[i + 1] = path[j].y;
  21370. positions[i + 2] = path[j].z;
  21371. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21372. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21373. }
  21374. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21375. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21376. }
  21377. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21378. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21379. }
  21380. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21381. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21382. }
  21383. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21384. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21385. }
  21386. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21387. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21388. }
  21389. j++;
  21390. i += 3;
  21391. }
  21392. if (instance._closePath) {
  21393. positions[i] = path[0].x;
  21394. positions[i + 1] = path[0].y;
  21395. positions[i + 2] = path[0].z;
  21396. i += 3;
  21397. }
  21398. }
  21399. }
  21400. };
  21401. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21402. positionFunction(positions);
  21403. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21404. instance._boundingInfo.update(instance._worldMatrix);
  21405. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21406. if (!(instance.areNormalsFrozen)) {
  21407. var indices = instance.getIndices();
  21408. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21409. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21410. if (instance._closePath) {
  21411. var indexFirst = 0;
  21412. var indexLast = 0;
  21413. for (var p = 0; p < pathArray.length; p++) {
  21414. indexFirst = instance._idx[p] * 3;
  21415. if (p + 1 < pathArray.length) {
  21416. indexLast = (instance._idx[p + 1] - 1) * 3;
  21417. }
  21418. else {
  21419. indexLast = normals.length - 3;
  21420. }
  21421. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21422. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21423. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21424. normals[indexLast] = normals[indexFirst];
  21425. normals[indexLast + 1] = normals[indexFirst + 1];
  21426. normals[indexLast + 2] = normals[indexFirst + 2];
  21427. }
  21428. }
  21429. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21430. }
  21431. return instance;
  21432. }
  21433. else {
  21434. var ribbon = new BABYLON.Mesh(name, scene);
  21435. ribbon.sideOrientation = sideOrientation;
  21436. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21437. if (closePath) {
  21438. ribbon._idx = vertexData._idx;
  21439. }
  21440. ribbon._closePath = closePath;
  21441. ribbon._closeArray = closeArray;
  21442. vertexData.applyToMesh(ribbon, updatable);
  21443. return ribbon;
  21444. }
  21445. };
  21446. /**
  21447. * Creates a cylinder or a cone mesh.
  21448. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21449. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21450. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21451. * 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.
  21452. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21453. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21454. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21455. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21456. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21457. * 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).
  21458. * 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
  21459. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21460. * 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
  21461. * 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.
  21462. * If `enclose` is false, a ring surface is one element.
  21463. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21464. * 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
  21465. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21466. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21468. */
  21469. MeshBuilder.CreateCylinder = function (name, options, scene) {
  21470. var cylinder = new BABYLON.Mesh(name, scene);
  21471. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21472. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  21473. vertexData.applyToMesh(cylinder, options.updatable);
  21474. return cylinder;
  21475. };
  21476. /**
  21477. * Creates a torus mesh.
  21478. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  21479. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21480. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21481. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21482. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21483. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21484. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21485. */
  21486. MeshBuilder.CreateTorus = function (name, options, scene) {
  21487. var torus = new BABYLON.Mesh(name, scene);
  21488. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21489. var vertexData = BABYLON.VertexData.CreateTorus(options);
  21490. vertexData.applyToMesh(torus, options.updatable);
  21491. return torus;
  21492. };
  21493. /**
  21494. * Creates a torus knot mesh.
  21495. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  21496. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21497. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21498. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21499. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21500. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21501. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21502. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21503. */
  21504. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  21505. var torusKnot = new BABYLON.Mesh(name, scene);
  21506. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21507. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  21508. vertexData.applyToMesh(torusKnot, options.updatable);
  21509. return torusKnot;
  21510. };
  21511. /**
  21512. * Creates a line system mesh.
  21513. * A line system is a pool of many lines gathered in a single mesh.
  21514. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  21515. * 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.
  21516. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  21517. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  21518. * 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
  21519. * 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
  21520. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  21521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21522. */
  21523. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  21524. var instance = options.instance;
  21525. var lines = options.lines;
  21526. if (instance) {
  21527. var positionFunction = function (positions) {
  21528. var i = 0;
  21529. for (var l = 0; l < lines.length; l++) {
  21530. var points = lines[l];
  21531. for (var p = 0; p < points.length; p++) {
  21532. positions[i] = points[p].x;
  21533. positions[i + 1] = points[p].y;
  21534. positions[i + 2] = points[p].z;
  21535. i += 3;
  21536. }
  21537. }
  21538. };
  21539. instance.updateMeshPositions(positionFunction, false);
  21540. return instance;
  21541. }
  21542. // line system creation
  21543. var lineSystem = new BABYLON.LinesMesh(name, scene);
  21544. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  21545. vertexData.applyToMesh(lineSystem, options.updatable);
  21546. return lineSystem;
  21547. };
  21548. /**
  21549. * Creates a line mesh.
  21550. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  21551. * 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.
  21552. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21553. * The parameter `points` is an array successive Vector3.
  21554. * 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
  21555. * When updating an instance, remember that only point positions can change, not the number of points.
  21556. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21557. */
  21558. MeshBuilder.CreateLines = function (name, options, scene) {
  21559. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  21560. return lines;
  21561. };
  21562. /**
  21563. * Creates a dashed line mesh.
  21564. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  21565. * 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.
  21566. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21567. * The parameter `points` is an array successive Vector3.
  21568. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21569. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21570. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21571. * 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
  21572. * When updating an instance, remember that only point positions can change, not the number of points.
  21573. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21574. */
  21575. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  21576. var points = options.points;
  21577. var instance = options.instance;
  21578. var gapSize = options.gapSize;
  21579. var dashNb = options.dashNb;
  21580. var dashSize = options.dashSize;
  21581. if (instance) {
  21582. var positionFunction = function (positions) {
  21583. var curvect = BABYLON.Vector3.Zero();
  21584. var nbSeg = positions.length / 6;
  21585. var lg = 0;
  21586. var nb = 0;
  21587. var shft = 0;
  21588. var dashshft = 0;
  21589. var curshft = 0;
  21590. var p = 0;
  21591. var i = 0;
  21592. var j = 0;
  21593. for (i = 0; i < points.length - 1; i++) {
  21594. points[i + 1].subtractToRef(points[i], curvect);
  21595. lg += curvect.length();
  21596. }
  21597. shft = lg / nbSeg;
  21598. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  21599. for (i = 0; i < points.length - 1; i++) {
  21600. points[i + 1].subtractToRef(points[i], curvect);
  21601. nb = Math.floor(curvect.length() / shft);
  21602. curvect.normalize();
  21603. j = 0;
  21604. while (j < nb && p < positions.length) {
  21605. curshft = shft * j;
  21606. positions[p] = points[i].x + curshft * curvect.x;
  21607. positions[p + 1] = points[i].y + curshft * curvect.y;
  21608. positions[p + 2] = points[i].z + curshft * curvect.z;
  21609. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  21610. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  21611. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  21612. p += 6;
  21613. j++;
  21614. }
  21615. }
  21616. while (p < positions.length) {
  21617. positions[p] = points[i].x;
  21618. positions[p + 1] = points[i].y;
  21619. positions[p + 2] = points[i].z;
  21620. p += 3;
  21621. }
  21622. };
  21623. instance.updateMeshPositions(positionFunction, false);
  21624. return instance;
  21625. }
  21626. // dashed lines creation
  21627. var dashedLines = new BABYLON.LinesMesh(name, scene);
  21628. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  21629. vertexData.applyToMesh(dashedLines, options.updatable);
  21630. dashedLines.dashSize = dashSize;
  21631. dashedLines.gapSize = gapSize;
  21632. return dashedLines;
  21633. };
  21634. /**
  21635. * Creates an extruded shape mesh.
  21636. * 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.
  21637. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  21638. *
  21639. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21640. * 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
  21641. * extruded along the Z axis.
  21642. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21643. * 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.
  21644. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21645. * 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
  21646. * 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
  21647. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21648. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21649. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21650. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21651. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21652. */
  21653. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  21654. var path = options.path;
  21655. var shape = options.shape;
  21656. var scale = options.scale || 1;
  21657. var rotation = options.rotation || 0;
  21658. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21659. var updatable = options.updatable;
  21660. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21661. var instance = options.instance;
  21662. var invertUV = options.invertUV || false;
  21663. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  21664. };
  21665. /**
  21666. * Creates an custom extruded shape mesh.
  21667. * 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.
  21668. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  21669. *
  21670. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21671. * 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
  21672. * extruded along the Z axis.
  21673. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21674. * 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
  21675. * and the distance of this point from the begining of the path :
  21676. * ```javascript
  21677. * var rotationFunction = function(i, distance) {
  21678. * // do things
  21679. * return rotationValue; }
  21680. * ```
  21681. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21682. * 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
  21683. * and the distance of this point from the begining of the path :
  21684. * ```javascript
  21685. * var scaleFunction = function(i, distance) {
  21686. * // do things
  21687. * return scaleValue;}
  21688. * ```
  21689. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21690. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21691. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21692. * 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
  21693. * 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
  21694. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21695. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21696. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21697. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21698. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21699. */
  21700. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  21701. var path = options.path;
  21702. var shape = options.shape;
  21703. var scaleFunction = options.scaleFunction || (function () { return 1; });
  21704. var rotationFunction = options.rotationFunction || (function () { return 0; });
  21705. var ribbonCloseArray = options.ribbonCloseArray || false;
  21706. var ribbonClosePath = options.ribbonClosePath || false;
  21707. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21708. var updatable = options.updatable;
  21709. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21710. var instance = options.instance;
  21711. var invertUV = options.invertUV || false;
  21712. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  21713. };
  21714. /**
  21715. * Creates lathe mesh.
  21716. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21717. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  21718. *
  21719. * 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
  21720. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21721. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21722. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21723. * 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.
  21724. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  21725. * 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
  21726. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21727. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21728. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21730. */
  21731. MeshBuilder.CreateLathe = function (name, options, scene) {
  21732. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  21733. var closed = (options.closed === undefined) ? true : options.closed;
  21734. var shape = options.shape;
  21735. var radius = options.radius || 1;
  21736. var tessellation = options.tessellation || 64;
  21737. var updatable = options.updatable;
  21738. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21739. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21740. var pi2 = Math.PI * 2;
  21741. var paths = new Array();
  21742. var invertUV = options.invertUV || false;
  21743. var i = 0;
  21744. var p = 0;
  21745. var step = pi2 / tessellation * arc;
  21746. var rotated;
  21747. var path = new Array();
  21748. ;
  21749. for (i = 0; i <= tessellation; i++) {
  21750. var path = [];
  21751. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  21752. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  21753. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  21754. }
  21755. for (p = 0; p < shape.length; p++) {
  21756. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  21757. path.push(rotated);
  21758. }
  21759. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  21760. 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));
  21761. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  21762. }
  21763. paths.push(path);
  21764. }
  21765. // lathe ribbon
  21766. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  21767. return lathe;
  21768. };
  21769. /**
  21770. * Creates a plane mesh.
  21771. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21772. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21773. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  21774. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  21775. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21776. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21777. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21778. */
  21779. MeshBuilder.CreatePlane = function (name, options, scene) {
  21780. var plane = new BABYLON.Mesh(name, scene);
  21781. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21782. var vertexData = BABYLON.VertexData.CreatePlane(options);
  21783. vertexData.applyToMesh(plane, options.updatable);
  21784. if (options.sourcePlane) {
  21785. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  21786. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  21787. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  21788. plane.rotate(vectorProduct, product);
  21789. }
  21790. return plane;
  21791. };
  21792. /**
  21793. * Creates a ground mesh.
  21794. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21795. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21796. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21797. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21798. */
  21799. MeshBuilder.CreateGround = function (name, options, scene) {
  21800. var ground = new BABYLON.GroundMesh(name, scene);
  21801. ground._setReady(false);
  21802. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  21803. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  21804. ground._width = options.width || 1;
  21805. ground._height = options.height || 1;
  21806. ground._maxX = ground._width / 2;
  21807. ground._maxZ = ground._height / 2;
  21808. ground._minX = -ground._maxX;
  21809. ground._minZ = -ground._maxZ;
  21810. var vertexData = BABYLON.VertexData.CreateGround(options);
  21811. vertexData.applyToMesh(ground, options.updatable);
  21812. ground._setReady(true);
  21813. return ground;
  21814. };
  21815. /**
  21816. * Creates a tiled ground mesh.
  21817. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  21818. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21819. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21820. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21821. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21822. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21823. * numbers of subdivisions on the ground width and height of each tile.
  21824. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21825. */
  21826. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  21827. var tiledGround = new BABYLON.Mesh(name, scene);
  21828. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  21829. vertexData.applyToMesh(tiledGround, options.updatable);
  21830. return tiledGround;
  21831. };
  21832. /**
  21833. * Creates a ground mesh from a height map.
  21834. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21835. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  21836. * The parameter `url` sets the URL of the height map image resource.
  21837. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21838. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21839. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21840. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21841. * 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).
  21842. * This function is passed the newly built mesh :
  21843. * ```javascript
  21844. * function(mesh) { // do things
  21845. * return; }
  21846. * ```
  21847. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21848. */
  21849. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  21850. var width = options.width || 10.0;
  21851. var height = options.height || 10.0;
  21852. var subdivisions = options.subdivisions || 1 | 0;
  21853. var minHeight = options.minHeight || 0.0;
  21854. var maxHeight = options.maxHeight || 10.0;
  21855. var updatable = options.updatable;
  21856. var onReady = options.onReady;
  21857. var ground = new BABYLON.GroundMesh(name, scene);
  21858. ground._subdivisionsX = subdivisions;
  21859. ground._subdivisionsY = subdivisions;
  21860. ground._width = width;
  21861. ground._height = height;
  21862. ground._maxX = ground._width / 2.0;
  21863. ground._maxZ = ground._height / 2.0;
  21864. ground._minX = -ground._maxX;
  21865. ground._minZ = -ground._maxZ;
  21866. ground._setReady(false);
  21867. var onload = function (img) {
  21868. // Getting height map data
  21869. var canvas = document.createElement("canvas");
  21870. var context = canvas.getContext("2d");
  21871. var bufferWidth = img.width;
  21872. var bufferHeight = img.height;
  21873. canvas.width = bufferWidth;
  21874. canvas.height = bufferHeight;
  21875. context.drawImage(img, 0, 0);
  21876. // Create VertexData from map data
  21877. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21878. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  21879. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  21880. width: width, height: height,
  21881. subdivisions: subdivisions,
  21882. minHeight: minHeight, maxHeight: maxHeight,
  21883. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  21884. });
  21885. vertexData.applyToMesh(ground, updatable);
  21886. ground._setReady(true);
  21887. //execute ready callback, if set
  21888. if (onReady) {
  21889. onReady(ground);
  21890. }
  21891. };
  21892. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21893. return ground;
  21894. };
  21895. /**
  21896. * Creates a tube mesh.
  21897. * 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.
  21898. *
  21899. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  21900. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21901. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21902. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21903. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21904. * 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.
  21905. * It must return a radius value (positive float) :
  21906. * ```javascript
  21907. * var radiusFunction = function(i, distance) {
  21908. * // do things
  21909. * return radius; }
  21910. * ```
  21911. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  21912. * 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
  21913. * 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
  21914. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21915. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21916. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21917. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21918. */
  21919. MeshBuilder.CreateTube = function (name, options, scene) {
  21920. var path = options.path;
  21921. var radius = options.radius || 1.0;
  21922. var tessellation = options.tessellation || 64 | 0;
  21923. var radiusFunction = options.radiusFunction;
  21924. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21925. var invertUV = options.invertUV || false;
  21926. var updatable = options.updatable;
  21927. var sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  21928. var instance = options.instance;
  21929. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  21930. // tube geometry
  21931. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  21932. var tangents = path3D.getTangents();
  21933. var normals = path3D.getNormals();
  21934. var distances = path3D.getDistances();
  21935. var pi2 = Math.PI * 2;
  21936. var step = pi2 / tessellation * arc;
  21937. var returnRadius = function () { return radius; };
  21938. var radiusFunctionFinal = radiusFunction || returnRadius;
  21939. var circlePath;
  21940. var rad;
  21941. var normal;
  21942. var rotated;
  21943. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21944. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21945. for (var i = 0; i < path.length; i++) {
  21946. rad = radiusFunctionFinal(i, distances[i]); // current radius
  21947. circlePath = Array(); // current circle array
  21948. normal = normals[i]; // current normal
  21949. for (var t = 0; t < tessellation; t++) {
  21950. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  21951. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  21952. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  21953. rotated.scaleInPlace(rad).addInPlace(path[i]);
  21954. circlePath[t] = rotated;
  21955. }
  21956. circlePaths[index] = circlePath;
  21957. index++;
  21958. }
  21959. // cap
  21960. var capPath = function (nbPoints, pathIndex) {
  21961. var pointCap = Array();
  21962. for (var i = 0; i < nbPoints; i++) {
  21963. pointCap.push(path[pathIndex]);
  21964. }
  21965. return pointCap;
  21966. };
  21967. switch (cap) {
  21968. case BABYLON.Mesh.NO_CAP:
  21969. break;
  21970. case BABYLON.Mesh.CAP_START:
  21971. circlePaths[0] = capPath(tessellation, 0);
  21972. circlePaths[1] = circlePaths[2].slice(0);
  21973. break;
  21974. case BABYLON.Mesh.CAP_END:
  21975. circlePaths[index] = circlePaths[index - 1].slice(0);
  21976. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21977. break;
  21978. case BABYLON.Mesh.CAP_ALL:
  21979. circlePaths[0] = capPath(tessellation, 0);
  21980. circlePaths[1] = circlePaths[2].slice(0);
  21981. circlePaths[index] = circlePaths[index - 1].slice(0);
  21982. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21983. break;
  21984. default:
  21985. break;
  21986. }
  21987. return circlePaths;
  21988. };
  21989. var path3D;
  21990. var pathArray;
  21991. if (instance) {
  21992. var arc = options.arc || instance.arc;
  21993. path3D = (instance.path3D).update(path);
  21994. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  21995. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  21996. instance.path3D = path3D;
  21997. instance.pathArray = pathArray;
  21998. instance.arc = arc;
  21999. return instance;
  22000. }
  22001. // tube creation
  22002. path3D = new BABYLON.Path3D(path);
  22003. var newPathArray = new Array();
  22004. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22005. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22006. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22007. tube.pathArray = pathArray;
  22008. tube.path3D = path3D;
  22009. tube.tessellation = tessellation;
  22010. tube.cap = cap;
  22011. tube.arc = options.arc;
  22012. return tube;
  22013. };
  22014. /**
  22015. * Creates a polyhedron mesh.
  22016. *
  22017. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22018. * 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
  22019. * to choose the wanted type.
  22020. * The parameter `size` (positive float, default 1) sets the polygon size.
  22021. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22022. * 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`.
  22023. * 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
  22024. * 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)`).
  22025. * 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
  22026. * 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.
  22027. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22028. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22030. */
  22031. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22032. var polyhedron = new BABYLON.Mesh(name, scene);
  22033. options.sideOrientation = this.updateSideOrientationForRightHandedSystem(options.sideOrientation, scene);
  22034. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22035. vertexData.applyToMesh(polyhedron, options.updatable);
  22036. return polyhedron;
  22037. };
  22038. /**
  22039. * Creates a decal mesh.
  22040. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  22041. * 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.
  22042. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22043. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22044. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22045. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22046. */
  22047. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  22048. var indices = sourceMesh.getIndices();
  22049. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22050. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22051. var position = options.position || BABYLON.Vector3.Zero();
  22052. var normal = options.normal || BABYLON.Vector3.Up();
  22053. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  22054. var angle = options.angle || 0;
  22055. // Getting correct rotation
  22056. if (!normal) {
  22057. var target = new BABYLON.Vector3(0, 0, 1);
  22058. var camera = sourceMesh.getScene().activeCamera;
  22059. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  22060. normal = camera.globalPosition.subtract(cameraWorldTarget);
  22061. }
  22062. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  22063. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  22064. var pitch = Math.atan2(normal.y, len);
  22065. // Matrix
  22066. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  22067. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  22068. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  22069. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  22070. var vertexData = new BABYLON.VertexData();
  22071. vertexData.indices = [];
  22072. vertexData.positions = [];
  22073. vertexData.normals = [];
  22074. vertexData.uvs = [];
  22075. var currentVertexDataIndex = 0;
  22076. var extractDecalVector3 = function (indexId) {
  22077. var vertexId = indices[indexId];
  22078. var result = new BABYLON.PositionNormalVertex();
  22079. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  22080. // Send vector to decal local world
  22081. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  22082. // Get normal
  22083. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  22084. return result;
  22085. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  22086. var clip = function (vertices, axis) {
  22087. if (vertices.length === 0) {
  22088. return vertices;
  22089. }
  22090. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  22091. var clipVertices = function (v0, v1) {
  22092. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  22093. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  22094. };
  22095. var result = new Array();
  22096. for (var index = 0; index < vertices.length; index += 3) {
  22097. var v1Out;
  22098. var v2Out;
  22099. var v3Out;
  22100. var total = 0;
  22101. var nV1, nV2, nV3, nV4;
  22102. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  22103. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  22104. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  22105. v1Out = d1 > 0;
  22106. v2Out = d2 > 0;
  22107. v3Out = d3 > 0;
  22108. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  22109. switch (total) {
  22110. case 0:
  22111. result.push(vertices[index]);
  22112. result.push(vertices[index + 1]);
  22113. result.push(vertices[index + 2]);
  22114. break;
  22115. case 1:
  22116. if (v1Out) {
  22117. nV1 = vertices[index + 1];
  22118. nV2 = vertices[index + 2];
  22119. nV3 = clipVertices(vertices[index], nV1);
  22120. nV4 = clipVertices(vertices[index], nV2);
  22121. }
  22122. if (v2Out) {
  22123. nV1 = vertices[index];
  22124. nV2 = vertices[index + 2];
  22125. nV3 = clipVertices(vertices[index + 1], nV1);
  22126. nV4 = clipVertices(vertices[index + 1], nV2);
  22127. result.push(nV3);
  22128. result.push(nV2.clone());
  22129. result.push(nV1.clone());
  22130. result.push(nV2.clone());
  22131. result.push(nV3.clone());
  22132. result.push(nV4);
  22133. break;
  22134. }
  22135. if (v3Out) {
  22136. nV1 = vertices[index];
  22137. nV2 = vertices[index + 1];
  22138. nV3 = clipVertices(vertices[index + 2], nV1);
  22139. nV4 = clipVertices(vertices[index + 2], nV2);
  22140. }
  22141. result.push(nV1.clone());
  22142. result.push(nV2.clone());
  22143. result.push(nV3);
  22144. result.push(nV4);
  22145. result.push(nV3.clone());
  22146. result.push(nV2.clone());
  22147. break;
  22148. case 2:
  22149. if (!v1Out) {
  22150. nV1 = vertices[index].clone();
  22151. nV2 = clipVertices(nV1, vertices[index + 1]);
  22152. nV3 = clipVertices(nV1, vertices[index + 2]);
  22153. result.push(nV1);
  22154. result.push(nV2);
  22155. result.push(nV3);
  22156. }
  22157. if (!v2Out) {
  22158. nV1 = vertices[index + 1].clone();
  22159. nV2 = clipVertices(nV1, vertices[index + 2]);
  22160. nV3 = clipVertices(nV1, vertices[index]);
  22161. result.push(nV1);
  22162. result.push(nV2);
  22163. result.push(nV3);
  22164. }
  22165. if (!v3Out) {
  22166. nV1 = vertices[index + 2].clone();
  22167. nV2 = clipVertices(nV1, vertices[index]);
  22168. nV3 = clipVertices(nV1, vertices[index + 1]);
  22169. result.push(nV1);
  22170. result.push(nV2);
  22171. result.push(nV3);
  22172. }
  22173. break;
  22174. case 3:
  22175. break;
  22176. }
  22177. }
  22178. return result;
  22179. };
  22180. for (var index = 0; index < indices.length; index += 3) {
  22181. var faceVertices = new Array();
  22182. faceVertices.push(extractDecalVector3(index));
  22183. faceVertices.push(extractDecalVector3(index + 1));
  22184. faceVertices.push(extractDecalVector3(index + 2));
  22185. // Clip
  22186. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  22187. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  22188. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  22189. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  22190. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  22191. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  22192. if (faceVertices.length === 0) {
  22193. continue;
  22194. }
  22195. // Add UVs and get back to world
  22196. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  22197. var vertex = faceVertices[vIndex];
  22198. //TODO check for Int32Array
  22199. vertexData.indices.push(currentVertexDataIndex);
  22200. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  22201. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  22202. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  22203. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  22204. currentVertexDataIndex++;
  22205. }
  22206. }
  22207. // Return mesh
  22208. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  22209. vertexData.applyToMesh(decal);
  22210. decal.position = position.clone();
  22211. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  22212. return decal;
  22213. };
  22214. // Privates
  22215. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  22216. // extrusion geometry
  22217. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  22218. var tangents = path3D.getTangents();
  22219. var normals = path3D.getNormals();
  22220. var binormals = path3D.getBinormals();
  22221. var distances = path3D.getDistances();
  22222. var angle = 0;
  22223. var returnScale = function () { return scale; };
  22224. var returnRotation = function () { return rotation; };
  22225. var rotate = custom ? rotateFunction : returnRotation;
  22226. var scl = custom ? scaleFunction : returnScale;
  22227. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22228. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22229. for (var i = 0; i < curve.length; i++) {
  22230. var shapePath = new Array();
  22231. var angleStep = rotate(i, distances[i]);
  22232. var scaleRatio = scl(i, distances[i]);
  22233. for (var p = 0; p < shape.length; p++) {
  22234. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  22235. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  22236. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  22237. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  22238. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  22239. shapePath[p] = rotated;
  22240. }
  22241. shapePaths[index] = shapePath;
  22242. angle += angleStep;
  22243. index++;
  22244. }
  22245. // cap
  22246. var capPath = function (shapePath) {
  22247. var pointCap = Array();
  22248. var barycenter = BABYLON.Vector3.Zero();
  22249. var i;
  22250. for (i = 0; i < shapePath.length; i++) {
  22251. barycenter.addInPlace(shapePath[i]);
  22252. }
  22253. barycenter.scaleInPlace(1 / shapePath.length);
  22254. for (i = 0; i < shapePath.length; i++) {
  22255. pointCap.push(barycenter);
  22256. }
  22257. return pointCap;
  22258. };
  22259. switch (cap) {
  22260. case BABYLON.Mesh.NO_CAP:
  22261. break;
  22262. case BABYLON.Mesh.CAP_START:
  22263. shapePaths[0] = capPath(shapePaths[2]);
  22264. shapePaths[1] = shapePaths[2].slice(0);
  22265. break;
  22266. case BABYLON.Mesh.CAP_END:
  22267. shapePaths[index] = shapePaths[index - 1];
  22268. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22269. break;
  22270. case BABYLON.Mesh.CAP_ALL:
  22271. shapePaths[0] = capPath(shapePaths[2]);
  22272. shapePaths[1] = shapePaths[2].slice(0);
  22273. shapePaths[index] = shapePaths[index - 1];
  22274. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22275. break;
  22276. default:
  22277. break;
  22278. }
  22279. return shapePaths;
  22280. };
  22281. var path3D;
  22282. var pathArray;
  22283. if (instance) {
  22284. path3D = (instance.path3D).update(curve);
  22285. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  22286. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  22287. return instance;
  22288. }
  22289. // extruded shape creation
  22290. path3D = new BABYLON.Path3D(curve);
  22291. var newShapePaths = new Array();
  22292. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22293. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  22294. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  22295. extrudedGeneric.pathArray = pathArray;
  22296. extrudedGeneric.path3D = path3D;
  22297. extrudedGeneric.cap = cap;
  22298. return extrudedGeneric;
  22299. };
  22300. return MeshBuilder;
  22301. })();
  22302. BABYLON.MeshBuilder = MeshBuilder;
  22303. })(BABYLON || (BABYLON = {}));
  22304. var BABYLON;
  22305. (function (BABYLON) {
  22306. var BaseTexture = (function () {
  22307. function BaseTexture(scene) {
  22308. this.hasAlpha = false;
  22309. this.getAlphaFromRGB = false;
  22310. this.level = 1;
  22311. this.coordinatesIndex = 0;
  22312. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22313. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22314. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22315. this.anisotropicFilteringLevel = 4;
  22316. this.isCube = false;
  22317. this.isRenderTarget = false;
  22318. this.animations = new Array();
  22319. /**
  22320. * An event triggered when the texture is disposed.
  22321. * @type {BABYLON.Observable}
  22322. */
  22323. this.onDisposeObservable = new BABYLON.Observable();
  22324. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22325. this._scene = scene;
  22326. this._scene.textures.push(this);
  22327. }
  22328. BaseTexture.prototype.toString = function () {
  22329. return this.name;
  22330. };
  22331. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22332. set: function (callback) {
  22333. if (this._onDisposeObserver) {
  22334. this.onDisposeObservable.remove(this._onDisposeObserver);
  22335. }
  22336. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22337. },
  22338. enumerable: true,
  22339. configurable: true
  22340. });
  22341. BaseTexture.prototype.getScene = function () {
  22342. return this._scene;
  22343. };
  22344. BaseTexture.prototype.getTextureMatrix = function () {
  22345. return null;
  22346. };
  22347. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22348. return null;
  22349. };
  22350. BaseTexture.prototype.getInternalTexture = function () {
  22351. return this._texture;
  22352. };
  22353. BaseTexture.prototype.isReady = function () {
  22354. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22355. return true;
  22356. }
  22357. if (this._texture) {
  22358. return this._texture.isReady;
  22359. }
  22360. return false;
  22361. };
  22362. BaseTexture.prototype.getSize = function () {
  22363. if (this._texture._width) {
  22364. return new BABYLON.Size(this._texture._width, this._texture._height);
  22365. }
  22366. if (this._texture._size) {
  22367. return new BABYLON.Size(this._texture._size, this._texture._size);
  22368. }
  22369. return BABYLON.Size.Zero();
  22370. };
  22371. BaseTexture.prototype.getBaseSize = function () {
  22372. if (!this.isReady() || !this._texture)
  22373. return BABYLON.Size.Zero();
  22374. if (this._texture._size) {
  22375. return new BABYLON.Size(this._texture._size, this._texture._size);
  22376. }
  22377. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22378. };
  22379. BaseTexture.prototype.scale = function (ratio) {
  22380. };
  22381. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22382. get: function () {
  22383. return false;
  22384. },
  22385. enumerable: true,
  22386. configurable: true
  22387. });
  22388. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22389. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22390. for (var index = 0; index < texturesCache.length; index++) {
  22391. var texturesCacheEntry = texturesCache[index];
  22392. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22393. texturesCache.splice(index, 1);
  22394. return;
  22395. }
  22396. }
  22397. };
  22398. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22399. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22400. for (var index = 0; index < texturesCache.length; index++) {
  22401. var texturesCacheEntry = texturesCache[index];
  22402. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22403. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22404. texturesCacheEntry.references++;
  22405. return texturesCacheEntry;
  22406. }
  22407. }
  22408. }
  22409. return null;
  22410. };
  22411. BaseTexture.prototype.delayLoad = function () {
  22412. };
  22413. BaseTexture.prototype.clone = function () {
  22414. return null;
  22415. };
  22416. BaseTexture.prototype.releaseInternalTexture = function () {
  22417. if (this._texture) {
  22418. this._scene.getEngine().releaseInternalTexture(this._texture);
  22419. delete this._texture;
  22420. }
  22421. };
  22422. BaseTexture.prototype.dispose = function () {
  22423. // Animations
  22424. this.getScene().stopAnimation(this);
  22425. // Remove from scene
  22426. var index = this._scene.textures.indexOf(this);
  22427. if (index >= 0) {
  22428. this._scene.textures.splice(index, 1);
  22429. }
  22430. if (this._texture === undefined) {
  22431. return;
  22432. }
  22433. // Release
  22434. this.releaseInternalTexture();
  22435. // Callback
  22436. this.onDisposeObservable.notifyObservers(this);
  22437. this.onDisposeObservable.clear();
  22438. };
  22439. BaseTexture.prototype.serialize = function () {
  22440. if (!this.name) {
  22441. return null;
  22442. }
  22443. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22444. // Animations
  22445. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22446. return serializationObject;
  22447. };
  22448. __decorate([
  22449. BABYLON.serialize()
  22450. ], BaseTexture.prototype, "name", void 0);
  22451. __decorate([
  22452. BABYLON.serialize()
  22453. ], BaseTexture.prototype, "hasAlpha", void 0);
  22454. __decorate([
  22455. BABYLON.serialize()
  22456. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22457. __decorate([
  22458. BABYLON.serialize()
  22459. ], BaseTexture.prototype, "level", void 0);
  22460. __decorate([
  22461. BABYLON.serialize()
  22462. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22463. __decorate([
  22464. BABYLON.serialize()
  22465. ], BaseTexture.prototype, "coordinatesMode", void 0);
  22466. __decorate([
  22467. BABYLON.serialize()
  22468. ], BaseTexture.prototype, "wrapU", void 0);
  22469. __decorate([
  22470. BABYLON.serialize()
  22471. ], BaseTexture.prototype, "wrapV", void 0);
  22472. __decorate([
  22473. BABYLON.serialize()
  22474. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22475. __decorate([
  22476. BABYLON.serialize()
  22477. ], BaseTexture.prototype, "isCube", void 0);
  22478. __decorate([
  22479. BABYLON.serialize()
  22480. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22481. return BaseTexture;
  22482. })();
  22483. BABYLON.BaseTexture = BaseTexture;
  22484. })(BABYLON || (BABYLON = {}));
  22485. var BABYLON;
  22486. (function (BABYLON) {
  22487. var Texture = (function (_super) {
  22488. __extends(Texture, _super);
  22489. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  22490. var _this = this;
  22491. if (noMipmap === void 0) { noMipmap = false; }
  22492. if (invertY === void 0) { invertY = true; }
  22493. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22494. if (onLoad === void 0) { onLoad = null; }
  22495. if (onError === void 0) { onError = null; }
  22496. if (buffer === void 0) { buffer = null; }
  22497. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22498. _super.call(this, scene);
  22499. this.uOffset = 0;
  22500. this.vOffset = 0;
  22501. this.uScale = 1.0;
  22502. this.vScale = 1.0;
  22503. this.uAng = 0;
  22504. this.vAng = 0;
  22505. this.wAng = 0;
  22506. this.name = url;
  22507. this.url = url;
  22508. this._noMipmap = noMipmap;
  22509. this._invertY = invertY;
  22510. this._samplingMode = samplingMode;
  22511. this._buffer = buffer;
  22512. this._deleteBuffer = deleteBuffer;
  22513. if (!url) {
  22514. return;
  22515. }
  22516. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  22517. var load = function () {
  22518. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  22519. _this.onLoadObservable.notifyObservers(true);
  22520. }
  22521. if (onLoad) {
  22522. onLoad();
  22523. }
  22524. };
  22525. if (!this._texture) {
  22526. if (!scene.useDelayedTextureLoading) {
  22527. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  22528. if (deleteBuffer) {
  22529. delete this._buffer;
  22530. }
  22531. }
  22532. else {
  22533. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22534. this._delayedOnLoad = load;
  22535. this._delayedOnError = onError;
  22536. }
  22537. }
  22538. else {
  22539. if (this._texture.isReady) {
  22540. BABYLON.Tools.SetImmediate(function () { return load(); });
  22541. }
  22542. else {
  22543. this._texture.onLoadedCallbacks.push(load);
  22544. }
  22545. }
  22546. }
  22547. Object.defineProperty(Texture.prototype, "noMipmap", {
  22548. get: function () {
  22549. return this._noMipmap;
  22550. },
  22551. enumerable: true,
  22552. configurable: true
  22553. });
  22554. Texture.prototype.delayLoad = function () {
  22555. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22556. return;
  22557. }
  22558. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22559. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22560. if (!this._texture) {
  22561. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  22562. if (this._deleteBuffer) {
  22563. delete this._buffer;
  22564. }
  22565. }
  22566. };
  22567. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22568. if (!this._texture) {
  22569. return;
  22570. }
  22571. this._samplingMode = samplingMode;
  22572. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22573. };
  22574. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22575. x *= this.uScale;
  22576. y *= this.vScale;
  22577. x -= 0.5 * this.uScale;
  22578. y -= 0.5 * this.vScale;
  22579. z -= 0.5;
  22580. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22581. t.x += 0.5 * this.uScale + this.uOffset;
  22582. t.y += 0.5 * this.vScale + this.vOffset;
  22583. t.z += 0.5;
  22584. };
  22585. Texture.prototype.getTextureMatrix = function () {
  22586. if (this.uOffset === this._cachedUOffset &&
  22587. this.vOffset === this._cachedVOffset &&
  22588. this.uScale === this._cachedUScale &&
  22589. this.vScale === this._cachedVScale &&
  22590. this.uAng === this._cachedUAng &&
  22591. this.vAng === this._cachedVAng &&
  22592. this.wAng === this._cachedWAng) {
  22593. return this._cachedTextureMatrix;
  22594. }
  22595. this._cachedUOffset = this.uOffset;
  22596. this._cachedVOffset = this.vOffset;
  22597. this._cachedUScale = this.uScale;
  22598. this._cachedVScale = this.vScale;
  22599. this._cachedUAng = this.uAng;
  22600. this._cachedVAng = this.vAng;
  22601. this._cachedWAng = this.wAng;
  22602. if (!this._cachedTextureMatrix) {
  22603. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22604. this._rowGenerationMatrix = new BABYLON.Matrix();
  22605. this._t0 = BABYLON.Vector3.Zero();
  22606. this._t1 = BABYLON.Vector3.Zero();
  22607. this._t2 = BABYLON.Vector3.Zero();
  22608. }
  22609. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22610. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22611. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22612. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22613. this._t1.subtractInPlace(this._t0);
  22614. this._t2.subtractInPlace(this._t0);
  22615. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22616. this._cachedTextureMatrix.m[0] = this._t1.x;
  22617. this._cachedTextureMatrix.m[1] = this._t1.y;
  22618. this._cachedTextureMatrix.m[2] = this._t1.z;
  22619. this._cachedTextureMatrix.m[4] = this._t2.x;
  22620. this._cachedTextureMatrix.m[5] = this._t2.y;
  22621. this._cachedTextureMatrix.m[6] = this._t2.z;
  22622. this._cachedTextureMatrix.m[8] = this._t0.x;
  22623. this._cachedTextureMatrix.m[9] = this._t0.y;
  22624. this._cachedTextureMatrix.m[10] = this._t0.z;
  22625. return this._cachedTextureMatrix;
  22626. };
  22627. Texture.prototype.getReflectionTextureMatrix = function () {
  22628. if (this.uOffset === this._cachedUOffset &&
  22629. this.vOffset === this._cachedVOffset &&
  22630. this.uScale === this._cachedUScale &&
  22631. this.vScale === this._cachedVScale &&
  22632. this.coordinatesMode === this._cachedCoordinatesMode) {
  22633. return this._cachedTextureMatrix;
  22634. }
  22635. if (!this._cachedTextureMatrix) {
  22636. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22637. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22638. }
  22639. this._cachedCoordinatesMode = this.coordinatesMode;
  22640. switch (this.coordinatesMode) {
  22641. case Texture.PLANAR_MODE:
  22642. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22643. this._cachedTextureMatrix[0] = this.uScale;
  22644. this._cachedTextureMatrix[5] = this.vScale;
  22645. this._cachedTextureMatrix[12] = this.uOffset;
  22646. this._cachedTextureMatrix[13] = this.vOffset;
  22647. break;
  22648. case Texture.PROJECTION_MODE:
  22649. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22650. this._projectionModeMatrix.m[0] = 0.5;
  22651. this._projectionModeMatrix.m[5] = -0.5;
  22652. this._projectionModeMatrix.m[10] = 0.0;
  22653. this._projectionModeMatrix.m[12] = 0.5;
  22654. this._projectionModeMatrix.m[13] = 0.5;
  22655. this._projectionModeMatrix.m[14] = 1.0;
  22656. this._projectionModeMatrix.m[15] = 1.0;
  22657. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22658. break;
  22659. default:
  22660. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22661. break;
  22662. }
  22663. return this._cachedTextureMatrix;
  22664. };
  22665. Texture.prototype.clone = function () {
  22666. var _this = this;
  22667. return BABYLON.SerializationHelper.Clone(function () {
  22668. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22669. }, this);
  22670. };
  22671. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22672. get: function () {
  22673. if (!this._onLoadObservarble) {
  22674. this._onLoadObservarble = new BABYLON.Observable();
  22675. }
  22676. return this._onLoadObservarble;
  22677. },
  22678. enumerable: true,
  22679. configurable: true
  22680. });
  22681. // Statics
  22682. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  22683. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22684. if (onLoad === void 0) { onLoad = null; }
  22685. if (onError === void 0) { onError = null; }
  22686. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  22687. };
  22688. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22689. if (parsedTexture.isCube) {
  22690. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22691. }
  22692. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22693. return null;
  22694. }
  22695. var texture = BABYLON.SerializationHelper.Parse(function () {
  22696. if (parsedTexture.customType) {
  22697. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22698. return customTexture.Parse(parsedTexture, scene, rootUrl);
  22699. }
  22700. else if (parsedTexture.mirrorPlane) {
  22701. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22702. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22703. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22704. return mirrorTexture;
  22705. }
  22706. else if (parsedTexture.isRenderTarget) {
  22707. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22708. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22709. return renderTargetTexture;
  22710. }
  22711. else {
  22712. var texture;
  22713. if (parsedTexture.base64String) {
  22714. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22715. }
  22716. else {
  22717. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22718. }
  22719. return texture;
  22720. }
  22721. }, parsedTexture, scene);
  22722. // Animations
  22723. if (parsedTexture.animations) {
  22724. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22725. var parsedAnimation = parsedTexture.animations[animationIndex];
  22726. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22727. }
  22728. }
  22729. return texture;
  22730. };
  22731. // Constants
  22732. Texture.NEAREST_SAMPLINGMODE = 1;
  22733. Texture.BILINEAR_SAMPLINGMODE = 2;
  22734. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22735. Texture.EXPLICIT_MODE = 0;
  22736. Texture.SPHERICAL_MODE = 1;
  22737. Texture.PLANAR_MODE = 2;
  22738. Texture.CUBIC_MODE = 3;
  22739. Texture.PROJECTION_MODE = 4;
  22740. Texture.SKYBOX_MODE = 5;
  22741. Texture.INVCUBIC_MODE = 6;
  22742. Texture.EQUIRECTANGULAR_MODE = 7;
  22743. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22744. Texture.CLAMP_ADDRESSMODE = 0;
  22745. Texture.WRAP_ADDRESSMODE = 1;
  22746. Texture.MIRROR_ADDRESSMODE = 2;
  22747. __decorate([
  22748. BABYLON.serialize()
  22749. ], Texture.prototype, "url", void 0);
  22750. __decorate([
  22751. BABYLON.serialize()
  22752. ], Texture.prototype, "uOffset", void 0);
  22753. __decorate([
  22754. BABYLON.serialize()
  22755. ], Texture.prototype, "vOffset", void 0);
  22756. __decorate([
  22757. BABYLON.serialize()
  22758. ], Texture.prototype, "uScale", void 0);
  22759. __decorate([
  22760. BABYLON.serialize()
  22761. ], Texture.prototype, "vScale", void 0);
  22762. __decorate([
  22763. BABYLON.serialize()
  22764. ], Texture.prototype, "uAng", void 0);
  22765. __decorate([
  22766. BABYLON.serialize()
  22767. ], Texture.prototype, "vAng", void 0);
  22768. __decorate([
  22769. BABYLON.serialize()
  22770. ], Texture.prototype, "wAng", void 0);
  22771. return Texture;
  22772. })(BABYLON.BaseTexture);
  22773. BABYLON.Texture = Texture;
  22774. })(BABYLON || (BABYLON = {}));
  22775. var BABYLON;
  22776. (function (BABYLON) {
  22777. var CubeTexture = (function (_super) {
  22778. __extends(CubeTexture, _super);
  22779. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  22780. _super.call(this, scene);
  22781. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  22782. this.name = rootUrl;
  22783. this.url = rootUrl;
  22784. this._noMipmap = noMipmap;
  22785. this.hasAlpha = false;
  22786. if (!rootUrl && !files) {
  22787. return;
  22788. }
  22789. this._texture = this._getFromCache(rootUrl, noMipmap);
  22790. if (!files) {
  22791. if (!extensions) {
  22792. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  22793. }
  22794. files = [];
  22795. for (var index = 0; index < extensions.length; index++) {
  22796. files.push(rootUrl + extensions[index]);
  22797. }
  22798. this._extensions = extensions;
  22799. }
  22800. this._files = files;
  22801. if (!this._texture) {
  22802. if (!scene.useDelayedTextureLoading) {
  22803. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  22804. }
  22805. else {
  22806. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22807. }
  22808. }
  22809. this.isCube = true;
  22810. this._textureMatrix = BABYLON.Matrix.Identity();
  22811. }
  22812. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  22813. return new CubeTexture("", scene, null, noMipmap, files);
  22814. };
  22815. // Methods
  22816. CubeTexture.prototype.delayLoad = function () {
  22817. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22818. return;
  22819. }
  22820. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22821. this._texture = this._getFromCache(this.url, this._noMipmap);
  22822. if (!this._texture) {
  22823. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  22824. }
  22825. };
  22826. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  22827. return this._textureMatrix;
  22828. };
  22829. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  22830. var texture = BABYLON.SerializationHelper.Parse(function () {
  22831. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  22832. }, parsedTexture, scene);
  22833. // Animations
  22834. if (parsedTexture.animations) {
  22835. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22836. var parsedAnimation = parsedTexture.animations[animationIndex];
  22837. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22838. }
  22839. }
  22840. return texture;
  22841. };
  22842. CubeTexture.prototype.clone = function () {
  22843. var _this = this;
  22844. return BABYLON.SerializationHelper.Clone(function () {
  22845. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  22846. }, this);
  22847. };
  22848. return CubeTexture;
  22849. })(BABYLON.BaseTexture);
  22850. BABYLON.CubeTexture = CubeTexture;
  22851. })(BABYLON || (BABYLON = {}));
  22852. var BABYLON;
  22853. (function (BABYLON) {
  22854. var RenderTargetTexture = (function (_super) {
  22855. __extends(RenderTargetTexture, _super);
  22856. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  22857. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  22858. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22859. if (isCube === void 0) { isCube = false; }
  22860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22861. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  22862. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  22863. _super.call(this, null, scene, !generateMipMaps);
  22864. this.isCube = isCube;
  22865. /**
  22866. * Use this list to define the list of mesh you want to render.
  22867. */
  22868. this.renderList = new Array();
  22869. this.renderParticles = true;
  22870. this.renderSprites = false;
  22871. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  22872. // Events
  22873. /**
  22874. * An event triggered when the texture is unbind.
  22875. * @type {BABYLON.Observable}
  22876. */
  22877. this.onAfterUnbindObservable = new BABYLON.Observable();
  22878. /**
  22879. * An event triggered before rendering the texture
  22880. * @type {BABYLON.Observable}
  22881. */
  22882. this.onBeforeRenderObservable = new BABYLON.Observable();
  22883. /**
  22884. * An event triggered after rendering the texture
  22885. * @type {BABYLON.Observable}
  22886. */
  22887. this.onAfterRenderObservable = new BABYLON.Observable();
  22888. /**
  22889. * An event triggered after the texture clear
  22890. * @type {BABYLON.Observable}
  22891. */
  22892. this.onClearObservable = new BABYLON.Observable();
  22893. this._currentRefreshId = -1;
  22894. this._refreshRate = 1;
  22895. this.name = name;
  22896. this.isRenderTarget = true;
  22897. this._size = size;
  22898. this._generateMipMaps = generateMipMaps;
  22899. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  22900. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  22901. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22902. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22903. }
  22904. if (isCube) {
  22905. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  22906. generateMipMaps: generateMipMaps,
  22907. samplingMode: samplingMode,
  22908. generateDepthBuffer: generateDepthBuffer,
  22909. generateStencilBuffer: generateStencilBuffer
  22910. });
  22911. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  22912. this._textureMatrix = BABYLON.Matrix.Identity();
  22913. }
  22914. else {
  22915. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  22916. generateMipMaps: generateMipMaps,
  22917. type: type,
  22918. samplingMode: samplingMode,
  22919. generateDepthBuffer: generateDepthBuffer,
  22920. generateStencilBuffer: generateStencilBuffer
  22921. });
  22922. }
  22923. // Rendering groups
  22924. this._renderingManager = new BABYLON.RenderingManager(scene);
  22925. }
  22926. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  22927. get: function () {
  22928. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  22929. },
  22930. enumerable: true,
  22931. configurable: true
  22932. });
  22933. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  22934. get: function () {
  22935. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  22936. },
  22937. enumerable: true,
  22938. configurable: true
  22939. });
  22940. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  22941. get: function () {
  22942. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  22943. },
  22944. enumerable: true,
  22945. configurable: true
  22946. });
  22947. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  22948. set: function (callback) {
  22949. if (this._onAfterUnbindObserver) {
  22950. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  22951. }
  22952. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  22953. },
  22954. enumerable: true,
  22955. configurable: true
  22956. });
  22957. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  22958. set: function (callback) {
  22959. if (this._onBeforeRenderObserver) {
  22960. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22961. }
  22962. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22963. },
  22964. enumerable: true,
  22965. configurable: true
  22966. });
  22967. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  22968. set: function (callback) {
  22969. if (this._onAfterRenderObserver) {
  22970. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22971. }
  22972. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22973. },
  22974. enumerable: true,
  22975. configurable: true
  22976. });
  22977. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  22978. set: function (callback) {
  22979. if (this._onClearObserver) {
  22980. this.onClearObservable.remove(this._onClearObserver);
  22981. }
  22982. this._onClearObserver = this.onClearObservable.add(callback);
  22983. },
  22984. enumerable: true,
  22985. configurable: true
  22986. });
  22987. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  22988. this._currentRefreshId = -1;
  22989. };
  22990. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  22991. get: function () {
  22992. return this._refreshRate;
  22993. },
  22994. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22995. set: function (value) {
  22996. this._refreshRate = value;
  22997. this.resetRefreshCounter();
  22998. },
  22999. enumerable: true,
  23000. configurable: true
  23001. });
  23002. RenderTargetTexture.prototype._shouldRender = function () {
  23003. if (this._currentRefreshId === -1) {
  23004. this._currentRefreshId = 1;
  23005. return true;
  23006. }
  23007. if (this.refreshRate === this._currentRefreshId) {
  23008. this._currentRefreshId = 1;
  23009. return true;
  23010. }
  23011. this._currentRefreshId++;
  23012. return false;
  23013. };
  23014. RenderTargetTexture.prototype.isReady = function () {
  23015. if (!this.getScene().renderTargetsEnabled) {
  23016. return false;
  23017. }
  23018. return _super.prototype.isReady.call(this);
  23019. };
  23020. RenderTargetTexture.prototype.getRenderSize = function () {
  23021. return this._size;
  23022. };
  23023. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  23024. get: function () {
  23025. return true;
  23026. },
  23027. enumerable: true,
  23028. configurable: true
  23029. });
  23030. RenderTargetTexture.prototype.scale = function (ratio) {
  23031. var newSize = this._size * ratio;
  23032. this.resize(newSize, this._generateMipMaps);
  23033. };
  23034. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  23035. if (this.isCube) {
  23036. return this._textureMatrix;
  23037. }
  23038. return _super.prototype.getReflectionTextureMatrix.call(this);
  23039. };
  23040. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  23041. this.releaseInternalTexture();
  23042. if (this.isCube) {
  23043. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  23044. }
  23045. else {
  23046. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23047. }
  23048. };
  23049. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  23050. var scene = this.getScene();
  23051. if (this.useCameraPostProcesses !== undefined) {
  23052. useCameraPostProcess = this.useCameraPostProcesses;
  23053. }
  23054. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23055. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  23056. }
  23057. if (this._waitingRenderList) {
  23058. this.renderList = [];
  23059. for (var index = 0; index < this._waitingRenderList.length; index++) {
  23060. var id = this._waitingRenderList[index];
  23061. this.renderList.push(scene.getMeshByID(id));
  23062. }
  23063. delete this._waitingRenderList;
  23064. }
  23065. // Is predicate defined?
  23066. if (this.renderListPredicate) {
  23067. this.renderList.splice(0); // Clear previous renderList
  23068. var sceneMeshes = this.getScene().meshes;
  23069. for (var index = 0; index < sceneMeshes.length; index++) {
  23070. var mesh = sceneMeshes[index];
  23071. if (this.renderListPredicate(mesh)) {
  23072. this.renderList.push(mesh);
  23073. }
  23074. }
  23075. }
  23076. if (this.renderList && this.renderList.length === 0) {
  23077. return;
  23078. }
  23079. // Prepare renderingManager
  23080. this._renderingManager.reset();
  23081. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  23082. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  23083. var sceneRenderId = scene.getRenderId();
  23084. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  23085. var mesh = currentRenderList[meshIndex];
  23086. if (mesh) {
  23087. if (!mesh.isReady()) {
  23088. // Reset _currentRefreshId
  23089. this.resetRefreshCounter();
  23090. continue;
  23091. }
  23092. mesh._preActivateForIntermediateRendering(sceneRenderId);
  23093. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  23094. mesh._activate(sceneRenderId);
  23095. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23096. var subMesh = mesh.subMeshes[subIndex];
  23097. scene._activeIndices.addCount(subMesh.indexCount, false);
  23098. this._renderingManager.dispatch(subMesh);
  23099. }
  23100. }
  23101. }
  23102. }
  23103. if (this.isCube) {
  23104. for (var face = 0; face < 6; face++) {
  23105. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23106. scene.incrementRenderId();
  23107. scene.resetCachedMaterial();
  23108. }
  23109. }
  23110. else {
  23111. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23112. }
  23113. this.onAfterUnbindObservable.notifyObservers(this);
  23114. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23115. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  23116. }
  23117. scene.resetCachedMaterial();
  23118. };
  23119. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  23120. var scene = this.getScene();
  23121. var engine = scene.getEngine();
  23122. // Bind
  23123. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  23124. if (this.isCube) {
  23125. engine.bindFramebuffer(this._texture, faceIndex);
  23126. }
  23127. else {
  23128. engine.bindFramebuffer(this._texture);
  23129. }
  23130. }
  23131. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  23132. // Clear
  23133. if (this.onClearObservable.hasObservers()) {
  23134. this.onClearObservable.notifyObservers(engine);
  23135. }
  23136. else {
  23137. engine.clear(scene.clearColor, true, true, true);
  23138. }
  23139. if (!this._doNotChangeAspectRatio) {
  23140. scene.updateTransformMatrix(true);
  23141. }
  23142. // Render
  23143. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  23144. if (useCameraPostProcess) {
  23145. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  23146. }
  23147. if (!this._doNotChangeAspectRatio) {
  23148. scene.updateTransformMatrix(true);
  23149. }
  23150. this.onAfterRenderObservable.notifyObservers(faceIndex);
  23151. // Dump ?
  23152. if (dumpForDebug) {
  23153. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  23154. }
  23155. // Unbind
  23156. if (!this.isCube || faceIndex === 5) {
  23157. if (this.isCube) {
  23158. if (faceIndex === 5) {
  23159. engine.generateMipMapsForCubemap(this._texture);
  23160. }
  23161. }
  23162. engine.unBindFramebuffer(this._texture, this.isCube);
  23163. }
  23164. };
  23165. /**
  23166. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23167. * This allowed control for front to back rendering or reversly depending of the special needs.
  23168. *
  23169. * @param renderingGroupId The rendering group id corresponding to its index
  23170. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23171. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23172. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23173. */
  23174. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23175. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23176. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23177. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23178. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23179. };
  23180. /**
  23181. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23182. *
  23183. * @param renderingGroupId The rendering group id corresponding to its index
  23184. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23185. */
  23186. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  23187. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  23188. };
  23189. RenderTargetTexture.prototype.clone = function () {
  23190. var textureSize = this.getSize();
  23191. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23192. // Base texture
  23193. newTexture.hasAlpha = this.hasAlpha;
  23194. newTexture.level = this.level;
  23195. // RenderTarget Texture
  23196. newTexture.coordinatesMode = this.coordinatesMode;
  23197. newTexture.renderList = this.renderList.slice(0);
  23198. return newTexture;
  23199. };
  23200. RenderTargetTexture.prototype.serialize = function () {
  23201. if (!this.name) {
  23202. return null;
  23203. }
  23204. var serializationObject = _super.prototype.serialize.call(this);
  23205. serializationObject.renderTargetSize = this.getRenderSize();
  23206. serializationObject.renderList = [];
  23207. for (var index = 0; index < this.renderList.length; index++) {
  23208. serializationObject.renderList.push(this.renderList[index].id);
  23209. }
  23210. return serializationObject;
  23211. };
  23212. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  23213. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  23214. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  23215. return RenderTargetTexture;
  23216. })(BABYLON.Texture);
  23217. BABYLON.RenderTargetTexture = RenderTargetTexture;
  23218. })(BABYLON || (BABYLON = {}));
  23219. var BABYLON;
  23220. (function (BABYLON) {
  23221. var ProceduralTexture = (function (_super) {
  23222. __extends(ProceduralTexture, _super);
  23223. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  23224. if (generateMipMaps === void 0) { generateMipMaps = true; }
  23225. if (isCube === void 0) { isCube = false; }
  23226. _super.call(this, null, scene, !generateMipMaps);
  23227. this.isCube = isCube;
  23228. this.isEnabled = true;
  23229. this._currentRefreshId = -1;
  23230. this._refreshRate = 1;
  23231. this._vertexBuffers = {};
  23232. this._uniforms = new Array();
  23233. this._samplers = new Array();
  23234. this._textures = new Array();
  23235. this._floats = new Array();
  23236. this._floatsArrays = {};
  23237. this._colors3 = new Array();
  23238. this._colors4 = new Array();
  23239. this._vectors2 = new Array();
  23240. this._vectors3 = new Array();
  23241. this._matrices = new Array();
  23242. this._fallbackTextureUsed = false;
  23243. scene._proceduralTextures.push(this);
  23244. this.name = name;
  23245. this.isRenderTarget = true;
  23246. this._size = size;
  23247. this._generateMipMaps = generateMipMaps;
  23248. this.setFragment(fragment);
  23249. this._fallbackTexture = fallbackTexture;
  23250. var engine = scene.getEngine();
  23251. if (isCube) {
  23252. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  23253. this.setFloat("face", 0);
  23254. }
  23255. else {
  23256. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  23257. }
  23258. // VBO
  23259. var vertices = [];
  23260. vertices.push(1, 1);
  23261. vertices.push(-1, 1);
  23262. vertices.push(-1, -1);
  23263. vertices.push(1, -1);
  23264. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  23265. // Indices
  23266. var indices = [];
  23267. indices.push(0);
  23268. indices.push(1);
  23269. indices.push(2);
  23270. indices.push(0);
  23271. indices.push(2);
  23272. indices.push(3);
  23273. this._indexBuffer = engine.createIndexBuffer(indices);
  23274. }
  23275. ProceduralTexture.prototype.reset = function () {
  23276. if (this._effect === undefined) {
  23277. return;
  23278. }
  23279. var engine = this.getScene().getEngine();
  23280. engine._releaseEffect(this._effect);
  23281. };
  23282. ProceduralTexture.prototype.isReady = function () {
  23283. var _this = this;
  23284. var engine = this.getScene().getEngine();
  23285. var shaders;
  23286. if (!this._fragment) {
  23287. return false;
  23288. }
  23289. if (this._fallbackTextureUsed) {
  23290. return true;
  23291. }
  23292. if (this._fragment.fragmentElement !== undefined) {
  23293. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  23294. }
  23295. else {
  23296. shaders = { vertex: "procedural", fragment: this._fragment };
  23297. }
  23298. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  23299. _this.releaseInternalTexture();
  23300. if (_this._fallbackTexture) {
  23301. _this._texture = _this._fallbackTexture._texture;
  23302. _this._texture.references++;
  23303. }
  23304. _this._fallbackTextureUsed = true;
  23305. });
  23306. return this._effect.isReady();
  23307. };
  23308. ProceduralTexture.prototype.resetRefreshCounter = function () {
  23309. this._currentRefreshId = -1;
  23310. };
  23311. ProceduralTexture.prototype.setFragment = function (fragment) {
  23312. this._fragment = fragment;
  23313. };
  23314. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  23315. get: function () {
  23316. return this._refreshRate;
  23317. },
  23318. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23319. set: function (value) {
  23320. this._refreshRate = value;
  23321. this.resetRefreshCounter();
  23322. },
  23323. enumerable: true,
  23324. configurable: true
  23325. });
  23326. ProceduralTexture.prototype._shouldRender = function () {
  23327. if (!this.isEnabled || !this.isReady() || !this._texture) {
  23328. return false;
  23329. }
  23330. if (this._fallbackTextureUsed) {
  23331. return false;
  23332. }
  23333. if (this._currentRefreshId === -1) {
  23334. this._currentRefreshId = 1;
  23335. return true;
  23336. }
  23337. if (this.refreshRate === this._currentRefreshId) {
  23338. this._currentRefreshId = 1;
  23339. return true;
  23340. }
  23341. this._currentRefreshId++;
  23342. return false;
  23343. };
  23344. ProceduralTexture.prototype.getRenderSize = function () {
  23345. return this._size;
  23346. };
  23347. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  23348. if (this._fallbackTextureUsed) {
  23349. return;
  23350. }
  23351. this.releaseInternalTexture();
  23352. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23353. };
  23354. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  23355. if (this._uniforms.indexOf(uniformName) === -1) {
  23356. this._uniforms.push(uniformName);
  23357. }
  23358. };
  23359. ProceduralTexture.prototype.setTexture = function (name, texture) {
  23360. if (this._samplers.indexOf(name) === -1) {
  23361. this._samplers.push(name);
  23362. }
  23363. this._textures[name] = texture;
  23364. return this;
  23365. };
  23366. ProceduralTexture.prototype.setFloat = function (name, value) {
  23367. this._checkUniform(name);
  23368. this._floats[name] = value;
  23369. return this;
  23370. };
  23371. ProceduralTexture.prototype.setFloats = function (name, value) {
  23372. this._checkUniform(name);
  23373. this._floatsArrays[name] = value;
  23374. return this;
  23375. };
  23376. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23377. this._checkUniform(name);
  23378. this._colors3[name] = value;
  23379. return this;
  23380. };
  23381. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23382. this._checkUniform(name);
  23383. this._colors4[name] = value;
  23384. return this;
  23385. };
  23386. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23387. this._checkUniform(name);
  23388. this._vectors2[name] = value;
  23389. return this;
  23390. };
  23391. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23392. this._checkUniform(name);
  23393. this._vectors3[name] = value;
  23394. return this;
  23395. };
  23396. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23397. this._checkUniform(name);
  23398. this._matrices[name] = value;
  23399. return this;
  23400. };
  23401. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23402. var scene = this.getScene();
  23403. var engine = scene.getEngine();
  23404. // Render
  23405. engine.enableEffect(this._effect);
  23406. engine.setState(false);
  23407. // Texture
  23408. for (var name in this._textures) {
  23409. this._effect.setTexture(name, this._textures[name]);
  23410. }
  23411. // Float
  23412. for (name in this._floats) {
  23413. this._effect.setFloat(name, this._floats[name]);
  23414. }
  23415. // Floats
  23416. for (name in this._floatsArrays) {
  23417. this._effect.setArray(name, this._floatsArrays[name]);
  23418. }
  23419. // Color3
  23420. for (name in this._colors3) {
  23421. this._effect.setColor3(name, this._colors3[name]);
  23422. }
  23423. // Color4
  23424. for (name in this._colors4) {
  23425. var color = this._colors4[name];
  23426. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23427. }
  23428. // Vector2
  23429. for (name in this._vectors2) {
  23430. this._effect.setVector2(name, this._vectors2[name]);
  23431. }
  23432. // Vector3
  23433. for (name in this._vectors3) {
  23434. this._effect.setVector3(name, this._vectors3[name]);
  23435. }
  23436. // Matrix
  23437. for (name in this._matrices) {
  23438. this._effect.setMatrix(name, this._matrices[name]);
  23439. }
  23440. // VBOs
  23441. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23442. if (this.isCube) {
  23443. for (var face = 0; face < 6; face++) {
  23444. engine.bindFramebuffer(this._texture, face);
  23445. this._effect.setFloat("face", face);
  23446. // Clear
  23447. engine.clear(scene.clearColor, true, true, true);
  23448. // Draw order
  23449. engine.draw(true, 0, 6);
  23450. // Mipmaps
  23451. if (face === 5) {
  23452. engine.generateMipMapsForCubemap(this._texture);
  23453. }
  23454. }
  23455. }
  23456. else {
  23457. engine.bindFramebuffer(this._texture);
  23458. // Clear
  23459. engine.clear(scene.clearColor, true, true, true);
  23460. // Draw order
  23461. engine.draw(true, 0, 6);
  23462. }
  23463. // Unbind
  23464. engine.unBindFramebuffer(this._texture, this.isCube);
  23465. if (this.onGenerated) {
  23466. this.onGenerated();
  23467. }
  23468. };
  23469. ProceduralTexture.prototype.clone = function () {
  23470. var textureSize = this.getSize();
  23471. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  23472. // Base texture
  23473. newTexture.hasAlpha = this.hasAlpha;
  23474. newTexture.level = this.level;
  23475. // RenderTarget Texture
  23476. newTexture.coordinatesMode = this.coordinatesMode;
  23477. return newTexture;
  23478. };
  23479. ProceduralTexture.prototype.dispose = function () {
  23480. var index = this.getScene()._proceduralTextures.indexOf(this);
  23481. if (index >= 0) {
  23482. this.getScene()._proceduralTextures.splice(index, 1);
  23483. }
  23484. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  23485. if (vertexBuffer) {
  23486. vertexBuffer.dispose();
  23487. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  23488. }
  23489. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  23490. this._indexBuffer = null;
  23491. }
  23492. _super.prototype.dispose.call(this);
  23493. };
  23494. return ProceduralTexture;
  23495. })(BABYLON.Texture);
  23496. BABYLON.ProceduralTexture = ProceduralTexture;
  23497. })(BABYLON || (BABYLON = {}));
  23498. var BABYLON;
  23499. (function (BABYLON) {
  23500. var MirrorTexture = (function (_super) {
  23501. __extends(MirrorTexture, _super);
  23502. function MirrorTexture(name, size, scene, generateMipMaps) {
  23503. var _this = this;
  23504. _super.call(this, name, size, scene, generateMipMaps, true);
  23505. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  23506. this._transformMatrix = BABYLON.Matrix.Zero();
  23507. this._mirrorMatrix = BABYLON.Matrix.Zero();
  23508. this.onBeforeRenderObservable.add(function () {
  23509. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  23510. _this._savedViewMatrix = scene.getViewMatrix();
  23511. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  23512. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  23513. scene.clipPlane = _this.mirrorPlane;
  23514. scene.getEngine().cullBackFaces = false;
  23515. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  23516. });
  23517. this.onAfterRenderObservable.add(function () {
  23518. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  23519. scene.getEngine().cullBackFaces = true;
  23520. scene._mirroredCameraPosition = null;
  23521. delete scene.clipPlane;
  23522. });
  23523. }
  23524. MirrorTexture.prototype.clone = function () {
  23525. var textureSize = this.getSize();
  23526. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23527. // Base texture
  23528. newTexture.hasAlpha = this.hasAlpha;
  23529. newTexture.level = this.level;
  23530. // Mirror Texture
  23531. newTexture.mirrorPlane = this.mirrorPlane.clone();
  23532. newTexture.renderList = this.renderList.slice(0);
  23533. return newTexture;
  23534. };
  23535. MirrorTexture.prototype.serialize = function () {
  23536. if (!this.name) {
  23537. return null;
  23538. }
  23539. var serializationObject = _super.prototype.serialize.call(this);
  23540. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  23541. return serializationObject;
  23542. };
  23543. return MirrorTexture;
  23544. })(BABYLON.RenderTargetTexture);
  23545. BABYLON.MirrorTexture = MirrorTexture;
  23546. })(BABYLON || (BABYLON = {}));
  23547. var BABYLON;
  23548. (function (BABYLON) {
  23549. /**
  23550. * Creates a refraction texture used by refraction channel of the standard material.
  23551. * @param name the texture name
  23552. * @param size size of the underlying texture
  23553. * @param scene root scene
  23554. */
  23555. var RefractionTexture = (function (_super) {
  23556. __extends(RefractionTexture, _super);
  23557. function RefractionTexture(name, size, scene, generateMipMaps) {
  23558. var _this = this;
  23559. _super.call(this, name, size, scene, generateMipMaps, true);
  23560. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  23561. this.depth = 2.0;
  23562. this.onBeforeRenderObservable.add(function () {
  23563. scene.clipPlane = _this.refractionPlane;
  23564. });
  23565. this.onAfterRenderObservable.add(function () {
  23566. delete scene.clipPlane;
  23567. });
  23568. }
  23569. RefractionTexture.prototype.clone = function () {
  23570. var textureSize = this.getSize();
  23571. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23572. // Base texture
  23573. newTexture.hasAlpha = this.hasAlpha;
  23574. newTexture.level = this.level;
  23575. // Refraction Texture
  23576. newTexture.refractionPlane = this.refractionPlane.clone();
  23577. newTexture.renderList = this.renderList.slice(0);
  23578. newTexture.depth = this.depth;
  23579. return newTexture;
  23580. };
  23581. RefractionTexture.prototype.serialize = function () {
  23582. if (!this.name) {
  23583. return null;
  23584. }
  23585. var serializationObject = _super.prototype.serialize.call(this);
  23586. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  23587. serializationObject.depth = this.depth;
  23588. return serializationObject;
  23589. };
  23590. return RefractionTexture;
  23591. })(BABYLON.RenderTargetTexture);
  23592. BABYLON.RefractionTexture = RefractionTexture;
  23593. })(BABYLON || (BABYLON = {}));
  23594. var BABYLON;
  23595. (function (BABYLON) {
  23596. var DynamicTexture = (function (_super) {
  23597. __extends(DynamicTexture, _super);
  23598. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  23599. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23600. _super.call(this, null, scene, !generateMipMaps);
  23601. this.name = name;
  23602. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23603. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23604. this._generateMipMaps = generateMipMaps;
  23605. if (options.getContext) {
  23606. this._canvas = options;
  23607. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23608. }
  23609. else {
  23610. this._canvas = document.createElement("canvas");
  23611. if (options.width) {
  23612. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23613. }
  23614. else {
  23615. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  23616. }
  23617. }
  23618. var textureSize = this.getSize();
  23619. this._canvas.width = textureSize.width;
  23620. this._canvas.height = textureSize.height;
  23621. this._context = this._canvas.getContext("2d");
  23622. }
  23623. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  23624. get: function () {
  23625. return true;
  23626. },
  23627. enumerable: true,
  23628. configurable: true
  23629. });
  23630. DynamicTexture.prototype.scale = function (ratio) {
  23631. var textureSize = this.getSize();
  23632. textureSize.width *= ratio;
  23633. textureSize.height *= ratio;
  23634. this._canvas.width = textureSize.width;
  23635. this._canvas.height = textureSize.height;
  23636. this.releaseInternalTexture();
  23637. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  23638. };
  23639. DynamicTexture.prototype.getContext = function () {
  23640. return this._context;
  23641. };
  23642. DynamicTexture.prototype.clear = function () {
  23643. var size = this.getSize();
  23644. this._context.fillRect(0, 0, size.width, size.height);
  23645. };
  23646. DynamicTexture.prototype.update = function (invertY) {
  23647. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  23648. };
  23649. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  23650. if (update === void 0) { update = true; }
  23651. var size = this.getSize();
  23652. if (clearColor) {
  23653. this._context.fillStyle = clearColor;
  23654. this._context.fillRect(0, 0, size.width, size.height);
  23655. }
  23656. this._context.font = font;
  23657. if (x === null) {
  23658. var textSize = this._context.measureText(text);
  23659. x = (size.width - textSize.width) / 2;
  23660. }
  23661. this._context.fillStyle = color;
  23662. this._context.fillText(text, x, y);
  23663. if (update) {
  23664. this.update(invertY);
  23665. }
  23666. };
  23667. DynamicTexture.prototype.clone = function () {
  23668. var textureSize = this.getSize();
  23669. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  23670. // Base texture
  23671. newTexture.hasAlpha = this.hasAlpha;
  23672. newTexture.level = this.level;
  23673. // Dynamic Texture
  23674. newTexture.wrapU = this.wrapU;
  23675. newTexture.wrapV = this.wrapV;
  23676. return newTexture;
  23677. };
  23678. return DynamicTexture;
  23679. })(BABYLON.Texture);
  23680. BABYLON.DynamicTexture = DynamicTexture;
  23681. })(BABYLON || (BABYLON = {}));
  23682. var BABYLON;
  23683. (function (BABYLON) {
  23684. var VideoTexture = (function (_super) {
  23685. __extends(VideoTexture, _super);
  23686. /**
  23687. * Creates a video texture.
  23688. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  23689. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  23690. * @param {BABYLON.Scene} scene is obviously the current scene.
  23691. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  23692. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  23693. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  23694. */
  23695. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  23696. var _this = this;
  23697. if (generateMipMaps === void 0) { generateMipMaps = false; }
  23698. if (invertY === void 0) { invertY = false; }
  23699. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23700. _super.call(this, null, scene, !generateMipMaps, invertY);
  23701. this._autoLaunch = true;
  23702. var urls;
  23703. this.name = name;
  23704. if (urlsOrVideo instanceof HTMLVideoElement) {
  23705. this.video = urlsOrVideo;
  23706. }
  23707. else {
  23708. urls = urlsOrVideo;
  23709. this.video = document.createElement("video");
  23710. this.video.autoplay = false;
  23711. this.video.loop = true;
  23712. }
  23713. this._generateMipMaps = generateMipMaps;
  23714. this._samplingMode = samplingMode;
  23715. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  23716. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23717. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23718. }
  23719. else {
  23720. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23721. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23722. this._generateMipMaps = false;
  23723. }
  23724. if (urls) {
  23725. this.video.addEventListener("canplaythrough", function () {
  23726. _this._createTexture();
  23727. });
  23728. urls.forEach(function (url) {
  23729. var source = document.createElement("source");
  23730. source.src = url;
  23731. _this.video.appendChild(source);
  23732. });
  23733. }
  23734. else {
  23735. this._createTexture();
  23736. }
  23737. this._lastUpdate = BABYLON.Tools.Now;
  23738. }
  23739. VideoTexture.prototype._createTexture = function () {
  23740. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  23741. this._texture.isReady = true;
  23742. };
  23743. VideoTexture.prototype.update = function () {
  23744. if (this._autoLaunch) {
  23745. this._autoLaunch = false;
  23746. this.video.play();
  23747. }
  23748. var now = BABYLON.Tools.Now;
  23749. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  23750. return false;
  23751. }
  23752. this._lastUpdate = now;
  23753. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  23754. return true;
  23755. };
  23756. return VideoTexture;
  23757. })(BABYLON.Texture);
  23758. BABYLON.VideoTexture = VideoTexture;
  23759. })(BABYLON || (BABYLON = {}));
  23760. var BABYLON;
  23761. (function (BABYLON) {
  23762. var CustomProceduralTexture = (function (_super) {
  23763. __extends(CustomProceduralTexture, _super);
  23764. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  23765. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  23766. this._animate = true;
  23767. this._time = 0;
  23768. this._texturePath = texturePath;
  23769. //Try to load json
  23770. this.loadJson(texturePath);
  23771. this.refreshRate = 1;
  23772. }
  23773. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  23774. var _this = this;
  23775. var that = this;
  23776. function noConfigFile() {
  23777. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  23778. try {
  23779. that.setFragment(that._texturePath);
  23780. }
  23781. catch (ex) {
  23782. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  23783. }
  23784. }
  23785. var configFileUrl = jsonUrl + "/config.json";
  23786. var xhr = new XMLHttpRequest();
  23787. xhr.open("GET", configFileUrl, true);
  23788. xhr.addEventListener("load", function () {
  23789. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  23790. try {
  23791. _this._config = JSON.parse(xhr.response);
  23792. _this.updateShaderUniforms();
  23793. _this.updateTextures();
  23794. _this.setFragment(_this._texturePath + "/custom");
  23795. _this._animate = _this._config.animate;
  23796. _this.refreshRate = _this._config.refreshrate;
  23797. }
  23798. catch (ex) {
  23799. noConfigFile();
  23800. }
  23801. }
  23802. else {
  23803. noConfigFile();
  23804. }
  23805. }, false);
  23806. xhr.addEventListener("error", function () {
  23807. noConfigFile();
  23808. }, false);
  23809. try {
  23810. xhr.send();
  23811. }
  23812. catch (ex) {
  23813. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  23814. }
  23815. };
  23816. CustomProceduralTexture.prototype.isReady = function () {
  23817. if (!_super.prototype.isReady.call(this)) {
  23818. return false;
  23819. }
  23820. for (var name in this._textures) {
  23821. var texture = this._textures[name];
  23822. if (!texture.isReady()) {
  23823. return false;
  23824. }
  23825. }
  23826. return true;
  23827. };
  23828. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23829. if (this._animate) {
  23830. this._time += this.getScene().getAnimationRatio() * 0.03;
  23831. this.updateShaderUniforms();
  23832. }
  23833. _super.prototype.render.call(this, useCameraPostProcess);
  23834. };
  23835. CustomProceduralTexture.prototype.updateTextures = function () {
  23836. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  23837. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  23838. }
  23839. };
  23840. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  23841. if (this._config) {
  23842. for (var j = 0; j < this._config.uniforms.length; j++) {
  23843. var uniform = this._config.uniforms[j];
  23844. switch (uniform.type) {
  23845. case "float":
  23846. this.setFloat(uniform.name, uniform.value);
  23847. break;
  23848. case "color3":
  23849. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  23850. break;
  23851. case "color4":
  23852. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  23853. break;
  23854. case "vector2":
  23855. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  23856. break;
  23857. case "vector3":
  23858. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  23859. break;
  23860. }
  23861. }
  23862. }
  23863. this.setFloat("time", this._time);
  23864. };
  23865. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  23866. get: function () {
  23867. return this._animate;
  23868. },
  23869. set: function (value) {
  23870. this._animate = value;
  23871. },
  23872. enumerable: true,
  23873. configurable: true
  23874. });
  23875. return CustomProceduralTexture;
  23876. })(BABYLON.ProceduralTexture);
  23877. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  23878. })(BABYLON || (BABYLON = {}));
  23879. var BABYLON;
  23880. (function (BABYLON) {
  23881. var EffectFallbacks = (function () {
  23882. function EffectFallbacks() {
  23883. this._defines = {};
  23884. this._currentRank = 32;
  23885. this._maxRank = -1;
  23886. }
  23887. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23888. if (!this._defines[rank]) {
  23889. if (rank < this._currentRank) {
  23890. this._currentRank = rank;
  23891. }
  23892. if (rank > this._maxRank) {
  23893. this._maxRank = rank;
  23894. }
  23895. this._defines[rank] = new Array();
  23896. }
  23897. this._defines[rank].push(define);
  23898. };
  23899. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23900. this._meshRank = rank;
  23901. this._mesh = mesh;
  23902. if (rank > this._maxRank) {
  23903. this._maxRank = rank;
  23904. }
  23905. };
  23906. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23907. get: function () {
  23908. return this._currentRank <= this._maxRank;
  23909. },
  23910. enumerable: true,
  23911. configurable: true
  23912. });
  23913. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23914. var currentFallbacks = this._defines[this._currentRank];
  23915. for (var index = 0; index < currentFallbacks.length; index++) {
  23916. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23917. }
  23918. if (this._mesh && this._currentRank === this._meshRank) {
  23919. this._mesh.computeBonesUsingShaders = false;
  23920. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23921. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23922. }
  23923. this._currentRank++;
  23924. return currentDefines;
  23925. };
  23926. return EffectFallbacks;
  23927. })();
  23928. BABYLON.EffectFallbacks = EffectFallbacks;
  23929. var Effect = (function () {
  23930. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23931. var _this = this;
  23932. this._isReady = false;
  23933. this._compilationError = "";
  23934. this._valueCache = {};
  23935. this._engine = engine;
  23936. this.name = baseName;
  23937. this.defines = defines;
  23938. this._uniformsNames = uniformsNames.concat(samplers);
  23939. this._samplers = samplers;
  23940. this._attributesNames = attributesNames;
  23941. this.onError = onError;
  23942. this.onCompiled = onCompiled;
  23943. this._indexParameters = indexParameters;
  23944. var vertexSource;
  23945. var fragmentSource;
  23946. if (baseName.vertexElement) {
  23947. vertexSource = document.getElementById(baseName.vertexElement);
  23948. if (!vertexSource) {
  23949. vertexSource = baseName.vertexElement;
  23950. }
  23951. }
  23952. else {
  23953. vertexSource = baseName.vertex || baseName;
  23954. }
  23955. if (baseName.fragmentElement) {
  23956. fragmentSource = document.getElementById(baseName.fragmentElement);
  23957. if (!fragmentSource) {
  23958. fragmentSource = baseName.fragmentElement;
  23959. }
  23960. }
  23961. else {
  23962. fragmentSource = baseName.fragment || baseName;
  23963. }
  23964. this._loadVertexShader(vertexSource, function (vertexCode) {
  23965. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23966. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23967. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23968. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  23969. });
  23970. });
  23971. });
  23972. });
  23973. }
  23974. // Properties
  23975. Effect.prototype.isReady = function () {
  23976. return this._isReady;
  23977. };
  23978. Effect.prototype.getProgram = function () {
  23979. return this._program;
  23980. };
  23981. Effect.prototype.getAttributesNames = function () {
  23982. return this._attributesNames;
  23983. };
  23984. Effect.prototype.getAttributeLocation = function (index) {
  23985. return this._attributes[index];
  23986. };
  23987. Effect.prototype.getAttributeLocationByName = function (name) {
  23988. var index = this._attributesNames.indexOf(name);
  23989. return this._attributes[index];
  23990. };
  23991. Effect.prototype.getAttributesCount = function () {
  23992. return this._attributes.length;
  23993. };
  23994. Effect.prototype.getUniformIndex = function (uniformName) {
  23995. return this._uniformsNames.indexOf(uniformName);
  23996. };
  23997. Effect.prototype.getUniform = function (uniformName) {
  23998. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23999. };
  24000. Effect.prototype.getSamplers = function () {
  24001. return this._samplers;
  24002. };
  24003. Effect.prototype.getCompilationError = function () {
  24004. return this._compilationError;
  24005. };
  24006. // Methods
  24007. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24008. // DOM element ?
  24009. if (vertex instanceof HTMLElement) {
  24010. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24011. callback(vertexCode);
  24012. return;
  24013. }
  24014. // Is in local store ?
  24015. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24016. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24017. return;
  24018. }
  24019. var vertexShaderUrl;
  24020. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24021. vertexShaderUrl = vertex;
  24022. }
  24023. else {
  24024. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24025. }
  24026. // Vertex shader
  24027. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24028. };
  24029. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24030. // DOM element ?
  24031. if (fragment instanceof HTMLElement) {
  24032. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24033. callback(fragmentCode);
  24034. return;
  24035. }
  24036. // Is in local store ?
  24037. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24038. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24039. return;
  24040. }
  24041. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24042. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24043. return;
  24044. }
  24045. var fragmentShaderUrl;
  24046. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24047. fragmentShaderUrl = fragment;
  24048. }
  24049. else {
  24050. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24051. }
  24052. // Fragment shader
  24053. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24054. };
  24055. Effect.prototype._dumpShadersName = function () {
  24056. if (this.name.vertexElement) {
  24057. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  24058. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  24059. }
  24060. else if (this.name.vertex) {
  24061. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  24062. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  24063. }
  24064. else {
  24065. BABYLON.Tools.Error("Vertex shader:" + this.name);
  24066. BABYLON.Tools.Error("Fragment shader:" + this.name);
  24067. }
  24068. };
  24069. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24070. var _this = this;
  24071. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24072. var match = regex.exec(sourceCode);
  24073. var returnValue = new String(sourceCode);
  24074. while (match != null) {
  24075. var includeFile = match[1];
  24076. if (Effect.IncludesShadersStore[includeFile]) {
  24077. // Substitution
  24078. var includeContent = Effect.IncludesShadersStore[includeFile];
  24079. if (match[2]) {
  24080. var splits = match[3].split(",");
  24081. for (var index = 0; index < splits.length; index += 2) {
  24082. var source = new RegExp(splits[index], "g");
  24083. var dest = splits[index + 1];
  24084. includeContent = includeContent.replace(source, dest);
  24085. }
  24086. }
  24087. if (match[4]) {
  24088. var indexString = match[5];
  24089. if (indexString.indexOf("..") !== -1) {
  24090. var indexSplits = indexString.split("..");
  24091. var minIndex = parseInt(indexSplits[0]);
  24092. var maxIndex = parseInt(indexSplits[1]);
  24093. var sourceIncludeContent = includeContent.slice(0);
  24094. includeContent = "";
  24095. if (isNaN(maxIndex)) {
  24096. maxIndex = this._indexParameters[indexSplits[1]];
  24097. }
  24098. for (var i = minIndex; i <= maxIndex; i++) {
  24099. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24100. }
  24101. }
  24102. else {
  24103. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24104. }
  24105. }
  24106. // Replace
  24107. returnValue = returnValue.replace(match[0], includeContent);
  24108. }
  24109. else {
  24110. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24111. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24112. Effect.IncludesShadersStore[includeFile] = fileContent;
  24113. _this._processIncludes(returnValue, callback);
  24114. });
  24115. return;
  24116. }
  24117. match = regex.exec(sourceCode);
  24118. }
  24119. callback(returnValue);
  24120. };
  24121. Effect.prototype._processPrecision = function (source) {
  24122. if (source.indexOf("precision highp float") === -1) {
  24123. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24124. source = "precision mediump float;\n" + source;
  24125. }
  24126. else {
  24127. source = "precision highp float;\n" + source;
  24128. }
  24129. }
  24130. else {
  24131. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24132. source = source.replace("precision highp float", "precision mediump float");
  24133. }
  24134. }
  24135. return source;
  24136. };
  24137. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  24138. try {
  24139. var engine = this._engine;
  24140. // Precision
  24141. vertexSourceCode = this._processPrecision(vertexSourceCode);
  24142. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  24143. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  24144. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24145. this._attributes = engine.getAttributes(this._program, attributesNames);
  24146. var index;
  24147. for (index = 0; index < this._samplers.length; index++) {
  24148. var sampler = this.getUniform(this._samplers[index]);
  24149. if (sampler == null) {
  24150. this._samplers.splice(index, 1);
  24151. index--;
  24152. }
  24153. }
  24154. engine.bindSamplers(this);
  24155. this._isReady = true;
  24156. if (this.onCompiled) {
  24157. this.onCompiled(this);
  24158. }
  24159. }
  24160. catch (e) {
  24161. // Let's go through fallbacks then
  24162. if (fallbacks && fallbacks.isMoreFallbacks) {
  24163. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  24164. this._dumpShadersName();
  24165. defines = fallbacks.reduce(defines);
  24166. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  24167. }
  24168. else {
  24169. BABYLON.Tools.Error("Unable to compile effect: ");
  24170. this._dumpShadersName();
  24171. BABYLON.Tools.Error("Defines: " + defines);
  24172. BABYLON.Tools.Error("Error: " + e.message);
  24173. this._compilationError = e.message;
  24174. if (this.onError) {
  24175. this.onError(this, this._compilationError);
  24176. }
  24177. }
  24178. }
  24179. };
  24180. Object.defineProperty(Effect.prototype, "isSupported", {
  24181. get: function () {
  24182. return this._compilationError === "";
  24183. },
  24184. enumerable: true,
  24185. configurable: true
  24186. });
  24187. Effect.prototype._bindTexture = function (channel, texture) {
  24188. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24189. };
  24190. Effect.prototype.setTexture = function (channel, texture) {
  24191. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24192. };
  24193. Effect.prototype.setTextureArray = function (channel, textures) {
  24194. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24195. var initialPos = this._samplers.indexOf(channel);
  24196. for (var index = 1; index < textures.length; index++) {
  24197. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24198. }
  24199. }
  24200. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24201. };
  24202. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24203. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24204. };
  24205. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24206. var changed = false;
  24207. var cache = this._valueCache[uniformName];
  24208. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  24209. changed = true;
  24210. cache = new BABYLON.Matrix();
  24211. }
  24212. var tm = cache.m;
  24213. var om = matrix.m;
  24214. for (var index = 0; index < 16; index++) {
  24215. if (tm[index] !== om[index]) {
  24216. tm[index] = om[index];
  24217. changed = true;
  24218. }
  24219. }
  24220. this._valueCache[uniformName] = cache;
  24221. return changed;
  24222. };
  24223. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24224. var cache = this._valueCache[uniformName];
  24225. if (!cache) {
  24226. cache = [x, y];
  24227. this._valueCache[uniformName] = cache;
  24228. return true;
  24229. }
  24230. var changed = false;
  24231. if (cache[0] !== x) {
  24232. cache[0] = x;
  24233. changed = true;
  24234. }
  24235. if (cache[1] !== y) {
  24236. cache[1] = y;
  24237. changed = true;
  24238. }
  24239. return changed;
  24240. };
  24241. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24242. var cache = this._valueCache[uniformName];
  24243. if (!cache) {
  24244. cache = [x, y, z];
  24245. this._valueCache[uniformName] = cache;
  24246. return true;
  24247. }
  24248. var changed = false;
  24249. if (cache[0] !== x) {
  24250. cache[0] = x;
  24251. changed = true;
  24252. }
  24253. if (cache[1] !== y) {
  24254. cache[1] = y;
  24255. changed = true;
  24256. }
  24257. if (cache[2] !== z) {
  24258. cache[2] = z;
  24259. changed = true;
  24260. }
  24261. return changed;
  24262. };
  24263. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24264. var cache = this._valueCache[uniformName];
  24265. if (!cache) {
  24266. cache = [x, y, z, w];
  24267. this._valueCache[uniformName] = cache;
  24268. return true;
  24269. }
  24270. var changed = false;
  24271. if (cache[0] !== x) {
  24272. cache[0] = x;
  24273. changed = true;
  24274. }
  24275. if (cache[1] !== y) {
  24276. cache[1] = y;
  24277. changed = true;
  24278. }
  24279. if (cache[2] !== z) {
  24280. cache[2] = z;
  24281. changed = true;
  24282. }
  24283. if (cache[3] !== w) {
  24284. cache[3] = w;
  24285. changed = true;
  24286. }
  24287. return changed;
  24288. };
  24289. Effect.prototype.setIntArray = function (uniformName, array) {
  24290. this._valueCache[uniformName] = null;
  24291. this._engine.setIntArray(this.getUniform(uniformName), array);
  24292. return this;
  24293. };
  24294. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24295. this._valueCache[uniformName] = null;
  24296. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24297. return this;
  24298. };
  24299. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24300. this._valueCache[uniformName] = null;
  24301. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24302. return this;
  24303. };
  24304. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24305. this._valueCache[uniformName] = null;
  24306. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24307. return this;
  24308. };
  24309. Effect.prototype.setFloatArray = function (uniformName, array) {
  24310. this._valueCache[uniformName] = null;
  24311. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24312. return this;
  24313. };
  24314. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24315. this._valueCache[uniformName] = null;
  24316. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24317. return this;
  24318. };
  24319. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24320. this._valueCache[uniformName] = null;
  24321. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24322. return this;
  24323. };
  24324. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24325. this._valueCache[uniformName] = null;
  24326. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24327. return this;
  24328. };
  24329. Effect.prototype.setArray = function (uniformName, array) {
  24330. this._valueCache[uniformName] = null;
  24331. this._engine.setArray(this.getUniform(uniformName), array);
  24332. return this;
  24333. };
  24334. Effect.prototype.setArray2 = function (uniformName, array) {
  24335. this._valueCache[uniformName] = null;
  24336. this._engine.setArray2(this.getUniform(uniformName), array);
  24337. return this;
  24338. };
  24339. Effect.prototype.setArray3 = function (uniformName, array) {
  24340. this._valueCache[uniformName] = null;
  24341. this._engine.setArray3(this.getUniform(uniformName), array);
  24342. return this;
  24343. };
  24344. Effect.prototype.setArray4 = function (uniformName, array) {
  24345. this._valueCache[uniformName] = null;
  24346. this._engine.setArray4(this.getUniform(uniformName), array);
  24347. return this;
  24348. };
  24349. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24350. this._valueCache[uniformName] = null;
  24351. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24352. return this;
  24353. };
  24354. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24355. if (this._cacheMatrix(uniformName, matrix)) {
  24356. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24357. }
  24358. return this;
  24359. };
  24360. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24361. this._valueCache[uniformName] = null;
  24362. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24363. return this;
  24364. };
  24365. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24366. this._valueCache[uniformName] = null;
  24367. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24368. return this;
  24369. };
  24370. Effect.prototype.setFloat = function (uniformName, value) {
  24371. var cache = this._valueCache[uniformName];
  24372. if (cache !== undefined && cache === value)
  24373. return this;
  24374. this._valueCache[uniformName] = value;
  24375. this._engine.setFloat(this.getUniform(uniformName), value);
  24376. return this;
  24377. };
  24378. Effect.prototype.setBool = function (uniformName, bool) {
  24379. var cache = this._valueCache[uniformName];
  24380. if (cache !== undefined && cache === bool)
  24381. return this;
  24382. this._valueCache[uniformName] = bool;
  24383. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24384. return this;
  24385. };
  24386. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24387. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24388. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24389. }
  24390. return this;
  24391. };
  24392. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24393. if (this._cacheFloat2(uniformName, x, y)) {
  24394. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24395. }
  24396. return this;
  24397. };
  24398. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24399. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24400. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24401. }
  24402. return this;
  24403. };
  24404. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24405. if (this._cacheFloat3(uniformName, x, y, z)) {
  24406. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24407. }
  24408. return this;
  24409. };
  24410. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24411. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24412. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24413. }
  24414. return this;
  24415. };
  24416. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24417. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24418. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24419. }
  24420. return this;
  24421. };
  24422. Effect.prototype.setColor3 = function (uniformName, color3) {
  24423. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24424. this._engine.setColor3(this.getUniform(uniformName), color3);
  24425. }
  24426. return this;
  24427. };
  24428. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24429. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24430. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24431. }
  24432. return this;
  24433. };
  24434. // Statics
  24435. Effect.ShadersStore = {};
  24436. Effect.IncludesShadersStore = {};
  24437. return Effect;
  24438. })();
  24439. BABYLON.Effect = Effect;
  24440. })(BABYLON || (BABYLON = {}));
  24441. var BABYLON;
  24442. (function (BABYLON) {
  24443. var MaterialHelper = (function () {
  24444. function MaterialHelper() {
  24445. }
  24446. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  24447. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24448. var lightIndex = 0;
  24449. var needNormals = false;
  24450. var needRebuild = false;
  24451. var needShadows = false;
  24452. var lightmapMode = false;
  24453. for (var index = 0; index < scene.lights.length; index++) {
  24454. var light = scene.lights[index];
  24455. if (!light.isEnabled()) {
  24456. continue;
  24457. }
  24458. // Excluded check
  24459. if (light._excludedMeshesIds.length > 0) {
  24460. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  24461. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  24462. if (excludedMesh) {
  24463. light.excludedMeshes.push(excludedMesh);
  24464. }
  24465. }
  24466. light._excludedMeshesIds = [];
  24467. }
  24468. // Included check
  24469. if (light._includedOnlyMeshesIds.length > 0) {
  24470. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  24471. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  24472. if (includedOnlyMesh) {
  24473. light.includedOnlyMeshes.push(includedOnlyMesh);
  24474. }
  24475. }
  24476. light._includedOnlyMeshesIds = [];
  24477. }
  24478. if (!light.canAffectMesh(mesh)) {
  24479. continue;
  24480. }
  24481. needNormals = true;
  24482. if (defines["LIGHT" + lightIndex] === undefined) {
  24483. needRebuild = true;
  24484. }
  24485. defines["LIGHT" + lightIndex] = true;
  24486. var type;
  24487. if (light instanceof BABYLON.SpotLight) {
  24488. type = "SPOTLIGHT" + lightIndex;
  24489. }
  24490. else if (light instanceof BABYLON.HemisphericLight) {
  24491. type = "HEMILIGHT" + lightIndex;
  24492. }
  24493. else if (light instanceof BABYLON.PointLight) {
  24494. type = "POINTLIGHT" + lightIndex;
  24495. }
  24496. else {
  24497. type = "DIRLIGHT" + lightIndex;
  24498. }
  24499. if (defines[type] === undefined) {
  24500. needRebuild = true;
  24501. }
  24502. defines[type] = true;
  24503. // Specular
  24504. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  24505. defines["SPECULARTERM"] = true;
  24506. }
  24507. // Shadows
  24508. if (scene.shadowsEnabled) {
  24509. var shadowGenerator = light.getShadowGenerator();
  24510. if (mesh && mesh.receiveShadows && shadowGenerator) {
  24511. if (defines["SHADOW" + lightIndex] === undefined) {
  24512. needRebuild = true;
  24513. }
  24514. defines["SHADOW" + lightIndex] = true;
  24515. defines["SHADOWS"] = true;
  24516. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  24517. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  24518. needRebuild = true;
  24519. }
  24520. defines["SHADOWVSM" + lightIndex] = true;
  24521. }
  24522. if (shadowGenerator.usePoissonSampling) {
  24523. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  24524. needRebuild = true;
  24525. }
  24526. defines["SHADOWPCF" + lightIndex] = true;
  24527. }
  24528. needShadows = true;
  24529. }
  24530. }
  24531. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24532. lightmapMode = true;
  24533. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  24534. needRebuild = true;
  24535. }
  24536. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  24537. needRebuild = true;
  24538. }
  24539. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24540. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  24541. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  24542. }
  24543. }
  24544. lightIndex++;
  24545. if (lightIndex === maxSimultaneousLights)
  24546. break;
  24547. }
  24548. var caps = scene.getEngine().getCaps();
  24549. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  24550. if (defines["SHADOWFULLFLOAT"] === undefined) {
  24551. needRebuild = true;
  24552. }
  24553. defines["SHADOWFULLFLOAT"] = true;
  24554. }
  24555. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  24556. needRebuild = true;
  24557. }
  24558. if (lightmapMode) {
  24559. defines["LIGHTMAPEXCLUDED"] = true;
  24560. }
  24561. if (needRebuild) {
  24562. defines.rebuild();
  24563. }
  24564. return needNormals;
  24565. };
  24566. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  24567. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24568. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24569. if (!defines["LIGHT" + lightIndex]) {
  24570. break;
  24571. }
  24572. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  24573. samplersList.push("shadowSampler" + lightIndex);
  24574. }
  24575. };
  24576. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24577. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24578. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24579. if (!defines["LIGHT" + lightIndex]) {
  24580. break;
  24581. }
  24582. if (lightIndex > 0) {
  24583. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24584. }
  24585. if (defines["SHADOW" + lightIndex]) {
  24586. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24587. }
  24588. if (defines["SHADOWPCF" + lightIndex]) {
  24589. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24590. }
  24591. if (defines["SHADOWVSM" + lightIndex]) {
  24592. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  24593. }
  24594. }
  24595. };
  24596. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24597. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24598. fallbacks.addCPUSkinningFallback(0, mesh);
  24599. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24600. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24601. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24602. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24603. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24604. }
  24605. }
  24606. };
  24607. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24608. if (defines["INSTANCES"]) {
  24609. attribs.push("world0");
  24610. attribs.push("world1");
  24611. attribs.push("world2");
  24612. attribs.push("world3");
  24613. }
  24614. };
  24615. // Bindings
  24616. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  24617. var shadowGenerator = light.getShadowGenerator();
  24618. if (mesh.receiveShadows && shadowGenerator) {
  24619. if (!light.needCube()) {
  24620. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  24621. }
  24622. else {
  24623. if (!depthValuesAlreadySet) {
  24624. depthValuesAlreadySet = true;
  24625. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  24626. }
  24627. }
  24628. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  24629. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  24630. }
  24631. return depthValuesAlreadySet;
  24632. };
  24633. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24634. if (light instanceof BABYLON.PointLight) {
  24635. // Point Light
  24636. light.transferToEffect(effect, "vLightData" + lightIndex);
  24637. }
  24638. else if (light instanceof BABYLON.DirectionalLight) {
  24639. // Directional Light
  24640. light.transferToEffect(effect, "vLightData" + lightIndex);
  24641. }
  24642. else if (light instanceof BABYLON.SpotLight) {
  24643. // Spot Light
  24644. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  24645. }
  24646. else if (light instanceof BABYLON.HemisphericLight) {
  24647. // Hemispheric Light
  24648. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  24649. }
  24650. };
  24651. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  24652. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24653. var lightIndex = 0;
  24654. var depthValuesAlreadySet = false;
  24655. for (var index = 0; index < scene.lights.length; index++) {
  24656. var light = scene.lights[index];
  24657. if (!light.isEnabled()) {
  24658. continue;
  24659. }
  24660. if (!light.canAffectMesh(mesh)) {
  24661. continue;
  24662. }
  24663. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24664. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  24665. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  24666. if (defines["SPECULARTERM"]) {
  24667. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  24668. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  24669. }
  24670. // Shadows
  24671. if (scene.shadowsEnabled) {
  24672. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  24673. }
  24674. lightIndex++;
  24675. if (lightIndex === maxSimultaneousLights)
  24676. break;
  24677. }
  24678. };
  24679. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24680. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24681. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24682. effect.setColor3("vFogColor", scene.fogColor);
  24683. }
  24684. };
  24685. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24686. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24687. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  24688. }
  24689. };
  24690. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24691. if (defines["LOGARITHMICDEPTH"]) {
  24692. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24693. }
  24694. };
  24695. MaterialHelper.BindClipPlane = function (effect, scene) {
  24696. if (scene.clipPlane) {
  24697. var clipPlane = scene.clipPlane;
  24698. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24699. }
  24700. };
  24701. return MaterialHelper;
  24702. })();
  24703. BABYLON.MaterialHelper = MaterialHelper;
  24704. })(BABYLON || (BABYLON = {}));
  24705. var BABYLON;
  24706. (function (BABYLON) {
  24707. var FresnelParameters = (function () {
  24708. function FresnelParameters() {
  24709. this.isEnabled = true;
  24710. this.leftColor = BABYLON.Color3.White();
  24711. this.rightColor = BABYLON.Color3.Black();
  24712. this.bias = 0;
  24713. this.power = 1;
  24714. }
  24715. FresnelParameters.prototype.clone = function () {
  24716. var newFresnelParameters = new FresnelParameters();
  24717. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  24718. return new FresnelParameters;
  24719. };
  24720. FresnelParameters.prototype.serialize = function () {
  24721. var serializationObject = {};
  24722. serializationObject.isEnabled = this.isEnabled;
  24723. serializationObject.leftColor = this.leftColor;
  24724. serializationObject.rightColor = this.rightColor;
  24725. serializationObject.bias = this.bias;
  24726. serializationObject.power = this.power;
  24727. return serializationObject;
  24728. };
  24729. FresnelParameters.Parse = function (parsedFresnelParameters) {
  24730. var fresnelParameters = new FresnelParameters();
  24731. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  24732. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  24733. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  24734. fresnelParameters.bias = parsedFresnelParameters.bias;
  24735. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  24736. return fresnelParameters;
  24737. };
  24738. return FresnelParameters;
  24739. })();
  24740. BABYLON.FresnelParameters = FresnelParameters;
  24741. })(BABYLON || (BABYLON = {}));
  24742. var BABYLON;
  24743. (function (BABYLON) {
  24744. var MaterialDefines = (function () {
  24745. function MaterialDefines() {
  24746. }
  24747. MaterialDefines.prototype.rebuild = function () {
  24748. if (this._keys) {
  24749. delete this._keys;
  24750. }
  24751. this._keys = Object.keys(this);
  24752. };
  24753. MaterialDefines.prototype.isEqual = function (other) {
  24754. if (this._keys.length !== other._keys.length) {
  24755. return false;
  24756. }
  24757. for (var index = 0; index < this._keys.length; index++) {
  24758. var prop = this._keys[index];
  24759. if (this[prop] !== other[prop]) {
  24760. return false;
  24761. }
  24762. }
  24763. return true;
  24764. };
  24765. MaterialDefines.prototype.cloneTo = function (other) {
  24766. if (this._keys.length !== other._keys.length) {
  24767. other._keys = this._keys.slice(0);
  24768. }
  24769. for (var index = 0; index < this._keys.length; index++) {
  24770. var prop = this._keys[index];
  24771. other[prop] = this[prop];
  24772. }
  24773. };
  24774. MaterialDefines.prototype.reset = function () {
  24775. for (var index = 0; index < this._keys.length; index++) {
  24776. var prop = this._keys[index];
  24777. if (typeof (this[prop]) === "number") {
  24778. this[prop] = 0;
  24779. }
  24780. else {
  24781. this[prop] = false;
  24782. }
  24783. }
  24784. };
  24785. MaterialDefines.prototype.toString = function () {
  24786. var result = "";
  24787. for (var index = 0; index < this._keys.length; index++) {
  24788. var prop = this._keys[index];
  24789. if (typeof (this[prop]) === "number") {
  24790. result += "#define " + prop + " " + this[prop] + "\n";
  24791. }
  24792. else if (this[prop]) {
  24793. result += "#define " + prop + "\n";
  24794. }
  24795. }
  24796. return result;
  24797. };
  24798. return MaterialDefines;
  24799. })();
  24800. BABYLON.MaterialDefines = MaterialDefines;
  24801. var Material = (function () {
  24802. function Material(name, scene, doNotAdd) {
  24803. this.name = name;
  24804. this.checkReadyOnEveryCall = false;
  24805. this.checkReadyOnlyOnce = false;
  24806. this.state = "";
  24807. this.alpha = 1.0;
  24808. this.backFaceCulling = true;
  24809. /**
  24810. * An event triggered when the material is disposed.
  24811. * @type {BABYLON.Observable}
  24812. */
  24813. this.onDisposeObservable = new BABYLON.Observable();
  24814. /**
  24815. * An event triggered when the material is bound.
  24816. * @type {BABYLON.Observable}
  24817. */
  24818. this.onBindObservable = new BABYLON.Observable();
  24819. /**
  24820. * An event triggered when the material is unbound.
  24821. * @type {BABYLON.Observable}
  24822. */
  24823. this.onUnBindObservable = new BABYLON.Observable();
  24824. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  24825. this.disableDepthWrite = false;
  24826. this.fogEnabled = true;
  24827. this.pointSize = 1.0;
  24828. this.zOffset = 0;
  24829. this._wasPreviouslyReady = false;
  24830. this._fillMode = Material.TriangleFillMode;
  24831. this.id = name;
  24832. this._scene = scene;
  24833. if (scene.useRightHandedSystem) {
  24834. this.sideOrientation = Material.ClockWiseSideOrientation;
  24835. }
  24836. else {
  24837. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  24838. }
  24839. if (!doNotAdd) {
  24840. scene.materials.push(this);
  24841. }
  24842. }
  24843. Object.defineProperty(Material, "TriangleFillMode", {
  24844. get: function () {
  24845. return Material._TriangleFillMode;
  24846. },
  24847. enumerable: true,
  24848. configurable: true
  24849. });
  24850. Object.defineProperty(Material, "WireFrameFillMode", {
  24851. get: function () {
  24852. return Material._WireFrameFillMode;
  24853. },
  24854. enumerable: true,
  24855. configurable: true
  24856. });
  24857. Object.defineProperty(Material, "PointFillMode", {
  24858. get: function () {
  24859. return Material._PointFillMode;
  24860. },
  24861. enumerable: true,
  24862. configurable: true
  24863. });
  24864. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24865. get: function () {
  24866. return Material._ClockWiseSideOrientation;
  24867. },
  24868. enumerable: true,
  24869. configurable: true
  24870. });
  24871. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24872. get: function () {
  24873. return Material._CounterClockWiseSideOrientation;
  24874. },
  24875. enumerable: true,
  24876. configurable: true
  24877. });
  24878. Object.defineProperty(Material.prototype, "onDispose", {
  24879. set: function (callback) {
  24880. if (this._onDisposeObserver) {
  24881. this.onDisposeObservable.remove(this._onDisposeObserver);
  24882. }
  24883. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24884. },
  24885. enumerable: true,
  24886. configurable: true
  24887. });
  24888. Object.defineProperty(Material.prototype, "onBind", {
  24889. set: function (callback) {
  24890. if (this._onBindObserver) {
  24891. this.onBindObservable.remove(this._onBindObserver);
  24892. }
  24893. this._onBindObserver = this.onBindObservable.add(callback);
  24894. },
  24895. enumerable: true,
  24896. configurable: true
  24897. });
  24898. Object.defineProperty(Material.prototype, "wireframe", {
  24899. get: function () {
  24900. return this._fillMode === Material.WireFrameFillMode;
  24901. },
  24902. set: function (value) {
  24903. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24904. },
  24905. enumerable: true,
  24906. configurable: true
  24907. });
  24908. Object.defineProperty(Material.prototype, "pointsCloud", {
  24909. get: function () {
  24910. return this._fillMode === Material.PointFillMode;
  24911. },
  24912. set: function (value) {
  24913. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24914. },
  24915. enumerable: true,
  24916. configurable: true
  24917. });
  24918. Object.defineProperty(Material.prototype, "fillMode", {
  24919. get: function () {
  24920. return this._fillMode;
  24921. },
  24922. set: function (value) {
  24923. this._fillMode = value;
  24924. },
  24925. enumerable: true,
  24926. configurable: true
  24927. });
  24928. /**
  24929. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24930. * subclasses should override adding information pertainent to themselves
  24931. */
  24932. Material.prototype.toString = function (fullDetails) {
  24933. var ret = "Name: " + this.name;
  24934. if (fullDetails) {
  24935. }
  24936. return ret;
  24937. };
  24938. Object.defineProperty(Material.prototype, "isFrozen", {
  24939. get: function () {
  24940. return this.checkReadyOnlyOnce;
  24941. },
  24942. enumerable: true,
  24943. configurable: true
  24944. });
  24945. Material.prototype.freeze = function () {
  24946. this.checkReadyOnlyOnce = true;
  24947. };
  24948. Material.prototype.unfreeze = function () {
  24949. this.checkReadyOnlyOnce = false;
  24950. };
  24951. Material.prototype.isReady = function (mesh, useInstances) {
  24952. return true;
  24953. };
  24954. Material.prototype.getEffect = function () {
  24955. return this._effect;
  24956. };
  24957. Material.prototype.getScene = function () {
  24958. return this._scene;
  24959. };
  24960. Material.prototype.needAlphaBlending = function () {
  24961. return (this.alpha < 1.0);
  24962. };
  24963. Material.prototype.needAlphaTesting = function () {
  24964. return false;
  24965. };
  24966. Material.prototype.getAlphaTestTexture = function () {
  24967. return null;
  24968. };
  24969. Material.prototype.markDirty = function () {
  24970. this._wasPreviouslyReady = false;
  24971. };
  24972. Material.prototype._preBind = function () {
  24973. var engine = this._scene.getEngine();
  24974. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  24975. engine.enableEffect(this._effect);
  24976. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  24977. };
  24978. Material.prototype.bind = function (world, mesh) {
  24979. this._scene._cachedMaterial = this;
  24980. this.onBindObservable.notifyObservers(mesh);
  24981. if (this.disableDepthWrite) {
  24982. var engine = this._scene.getEngine();
  24983. this._cachedDepthWriteState = engine.getDepthWrite();
  24984. engine.setDepthWrite(false);
  24985. }
  24986. };
  24987. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24988. };
  24989. Material.prototype.unbind = function () {
  24990. this.onUnBindObservable.notifyObservers(this);
  24991. if (this.disableDepthWrite) {
  24992. var engine = this._scene.getEngine();
  24993. engine.setDepthWrite(this._cachedDepthWriteState);
  24994. }
  24995. };
  24996. Material.prototype.clone = function (name) {
  24997. return null;
  24998. };
  24999. Material.prototype.getBindedMeshes = function () {
  25000. var result = new Array();
  25001. for (var index = 0; index < this._scene.meshes.length; index++) {
  25002. var mesh = this._scene.meshes[index];
  25003. if (mesh.material === this) {
  25004. result.push(mesh);
  25005. }
  25006. }
  25007. return result;
  25008. };
  25009. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25010. // Animations
  25011. this.getScene().stopAnimation(this);
  25012. // Remove from scene
  25013. var index = this._scene.materials.indexOf(this);
  25014. if (index >= 0) {
  25015. this._scene.materials.splice(index, 1);
  25016. }
  25017. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25018. if (forceDisposeEffect && this._effect) {
  25019. this._scene.getEngine()._releaseEffect(this._effect);
  25020. this._effect = null;
  25021. }
  25022. // Remove from meshes
  25023. for (index = 0; index < this._scene.meshes.length; index++) {
  25024. var mesh = this._scene.meshes[index];
  25025. if (mesh.material === this) {
  25026. mesh.material = null;
  25027. }
  25028. }
  25029. // Callback
  25030. this.onDisposeObservable.notifyObservers(this);
  25031. this.onDisposeObservable.clear();
  25032. this.onBindObservable.clear();
  25033. };
  25034. Material.prototype.serialize = function () {
  25035. return BABYLON.SerializationHelper.Serialize(this);
  25036. };
  25037. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25038. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25039. multiMaterial.id = parsedMultiMaterial.id;
  25040. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25041. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25042. var subMatId = parsedMultiMaterial.materials[matIndex];
  25043. if (subMatId) {
  25044. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25045. }
  25046. else {
  25047. multiMaterial.subMaterials.push(null);
  25048. }
  25049. }
  25050. return multiMaterial;
  25051. };
  25052. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25053. if (!parsedMaterial.customType) {
  25054. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25055. }
  25056. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25057. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25058. ;
  25059. };
  25060. Material._TriangleFillMode = 0;
  25061. Material._WireFrameFillMode = 1;
  25062. Material._PointFillMode = 2;
  25063. Material._ClockWiseSideOrientation = 0;
  25064. Material._CounterClockWiseSideOrientation = 1;
  25065. __decorate([
  25066. BABYLON.serialize()
  25067. ], Material.prototype, "id", void 0);
  25068. __decorate([
  25069. BABYLON.serialize()
  25070. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25071. __decorate([
  25072. BABYLON.serialize()
  25073. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25074. __decorate([
  25075. BABYLON.serialize()
  25076. ], Material.prototype, "state", void 0);
  25077. __decorate([
  25078. BABYLON.serialize()
  25079. ], Material.prototype, "alpha", void 0);
  25080. __decorate([
  25081. BABYLON.serialize()
  25082. ], Material.prototype, "backFaceCulling", void 0);
  25083. __decorate([
  25084. BABYLON.serialize()
  25085. ], Material.prototype, "sideOrientation", void 0);
  25086. __decorate([
  25087. BABYLON.serialize()
  25088. ], Material.prototype, "alphaMode", void 0);
  25089. __decorate([
  25090. BABYLON.serialize()
  25091. ], Material.prototype, "disableDepthWrite", void 0);
  25092. __decorate([
  25093. BABYLON.serialize()
  25094. ], Material.prototype, "fogEnabled", void 0);
  25095. __decorate([
  25096. BABYLON.serialize()
  25097. ], Material.prototype, "pointSize", void 0);
  25098. __decorate([
  25099. BABYLON.serialize()
  25100. ], Material.prototype, "zOffset", void 0);
  25101. __decorate([
  25102. BABYLON.serialize()
  25103. ], Material.prototype, "wireframe", null);
  25104. __decorate([
  25105. BABYLON.serialize()
  25106. ], Material.prototype, "pointsCloud", null);
  25107. __decorate([
  25108. BABYLON.serialize()
  25109. ], Material.prototype, "fillMode", null);
  25110. return Material;
  25111. })();
  25112. BABYLON.Material = Material;
  25113. })(BABYLON || (BABYLON = {}));
  25114. var BABYLON;
  25115. (function (BABYLON) {
  25116. var StandardMaterialDefines = (function (_super) {
  25117. __extends(StandardMaterialDefines, _super);
  25118. function StandardMaterialDefines() {
  25119. _super.call(this);
  25120. this.DIFFUSE = false;
  25121. this.AMBIENT = false;
  25122. this.OPACITY = false;
  25123. this.OPACITYRGB = false;
  25124. this.REFLECTION = false;
  25125. this.EMISSIVE = false;
  25126. this.SPECULAR = false;
  25127. this.BUMP = false;
  25128. this.PARALLAX = false;
  25129. this.PARALLAXOCCLUSION = false;
  25130. this.SPECULAROVERALPHA = false;
  25131. this.CLIPPLANE = false;
  25132. this.ALPHATEST = false;
  25133. this.ALPHAFROMDIFFUSE = false;
  25134. this.POINTSIZE = false;
  25135. this.FOG = false;
  25136. this.SPECULARTERM = false;
  25137. this.DIFFUSEFRESNEL = false;
  25138. this.OPACITYFRESNEL = false;
  25139. this.REFLECTIONFRESNEL = false;
  25140. this.REFRACTIONFRESNEL = false;
  25141. this.EMISSIVEFRESNEL = false;
  25142. this.FRESNEL = false;
  25143. this.NORMAL = false;
  25144. this.UV1 = false;
  25145. this.UV2 = false;
  25146. this.VERTEXCOLOR = false;
  25147. this.VERTEXALPHA = false;
  25148. this.NUM_BONE_INFLUENCERS = 0;
  25149. this.BonesPerMesh = 0;
  25150. this.INSTANCES = false;
  25151. this.GLOSSINESS = false;
  25152. this.ROUGHNESS = false;
  25153. this.EMISSIVEASILLUMINATION = false;
  25154. this.LINKEMISSIVEWITHDIFFUSE = false;
  25155. this.REFLECTIONFRESNELFROMSPECULAR = false;
  25156. this.LIGHTMAP = false;
  25157. this.USELIGHTMAPASSHADOWMAP = false;
  25158. this.REFLECTIONMAP_3D = false;
  25159. this.REFLECTIONMAP_SPHERICAL = false;
  25160. this.REFLECTIONMAP_PLANAR = false;
  25161. this.REFLECTIONMAP_CUBIC = false;
  25162. this.REFLECTIONMAP_PROJECTION = false;
  25163. this.REFLECTIONMAP_SKYBOX = false;
  25164. this.REFLECTIONMAP_EXPLICIT = false;
  25165. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  25166. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  25167. this.INVERTCUBICMAP = false;
  25168. this.LOGARITHMICDEPTH = false;
  25169. this.REFRACTION = false;
  25170. this.REFRACTIONMAP_3D = false;
  25171. this.REFLECTIONOVERALPHA = false;
  25172. this.INVERTNORMALMAPX = false;
  25173. this.INVERTNORMALMAPY = false;
  25174. this.SHADOWFULLFLOAT = false;
  25175. this.CAMERACOLORGRADING = false;
  25176. this.CAMERACOLORCURVES = false;
  25177. this.rebuild();
  25178. }
  25179. return StandardMaterialDefines;
  25180. })(BABYLON.MaterialDefines);
  25181. var StandardMaterial = (function (_super) {
  25182. __extends(StandardMaterial, _super);
  25183. function StandardMaterial(name, scene) {
  25184. var _this = this;
  25185. _super.call(this, name, scene);
  25186. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25187. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  25188. this.specularColor = new BABYLON.Color3(1, 1, 1);
  25189. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  25190. this.specularPower = 64;
  25191. this.useAlphaFromDiffuseTexture = false;
  25192. this.useEmissiveAsIllumination = false;
  25193. this.linkEmissiveWithDiffuse = false;
  25194. this.useReflectionFresnelFromSpecular = false;
  25195. this.useSpecularOverAlpha = false;
  25196. this.useReflectionOverAlpha = false;
  25197. this.disableLighting = false;
  25198. this.useParallax = false;
  25199. this.useParallaxOcclusion = false;
  25200. this.parallaxScaleBias = 0.05;
  25201. this.roughness = 0;
  25202. this.indexOfRefraction = 0.98;
  25203. this.invertRefractionY = true;
  25204. this.useLightmapAsShadowmap = false;
  25205. this.useGlossinessFromSpecularMapAlpha = false;
  25206. this.maxSimultaneousLights = 4;
  25207. /**
  25208. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  25209. */
  25210. this.invertNormalMapX = false;
  25211. /**
  25212. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  25213. */
  25214. this.invertNormalMapY = false;
  25215. /**
  25216. * Color Grading 2D Lookup Texture.
  25217. * This allows special effects like sepia, black and white to sixties rendering style.
  25218. */
  25219. this.cameraColorGradingTexture = null;
  25220. /**
  25221. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  25222. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  25223. * 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;
  25224. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  25225. */
  25226. this.cameraColorCurves = null;
  25227. this._renderTargets = new BABYLON.SmartArray(16);
  25228. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  25229. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  25230. this._defines = new StandardMaterialDefines();
  25231. this._cachedDefines = new StandardMaterialDefines();
  25232. this._cachedDefines.BonesPerMesh = -1;
  25233. this.getRenderTargetTextures = function () {
  25234. _this._renderTargets.reset();
  25235. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  25236. _this._renderTargets.push(_this.reflectionTexture);
  25237. }
  25238. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  25239. _this._renderTargets.push(_this.refractionTexture);
  25240. }
  25241. return _this._renderTargets;
  25242. };
  25243. }
  25244. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  25245. get: function () {
  25246. return this._useLogarithmicDepth;
  25247. },
  25248. set: function (value) {
  25249. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  25250. },
  25251. enumerable: true,
  25252. configurable: true
  25253. });
  25254. StandardMaterial.prototype.needAlphaBlending = function () {
  25255. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  25256. };
  25257. StandardMaterial.prototype.needAlphaTesting = function () {
  25258. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  25259. };
  25260. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  25261. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  25262. };
  25263. StandardMaterial.prototype.getAlphaTestTexture = function () {
  25264. return this.diffuseTexture;
  25265. };
  25266. // Methods
  25267. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  25268. if (!mesh) {
  25269. return true;
  25270. }
  25271. if (this._defines.INSTANCES !== useInstances) {
  25272. return false;
  25273. }
  25274. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  25275. return true;
  25276. }
  25277. return false;
  25278. };
  25279. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  25280. if (this.isFrozen) {
  25281. if (this._wasPreviouslyReady) {
  25282. return true;
  25283. }
  25284. }
  25285. var scene = this.getScene();
  25286. if (!this.checkReadyOnEveryCall) {
  25287. if (this._renderId === scene.getRenderId()) {
  25288. if (this._checkCache(scene, mesh, useInstances)) {
  25289. return true;
  25290. }
  25291. }
  25292. }
  25293. var engine = scene.getEngine();
  25294. var needNormals = false;
  25295. var needUVs = false;
  25296. this._defines.reset();
  25297. // Textures
  25298. if (scene.texturesEnabled) {
  25299. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25300. if (!this.diffuseTexture.isReady()) {
  25301. return false;
  25302. }
  25303. else {
  25304. needUVs = true;
  25305. this._defines.DIFFUSE = true;
  25306. }
  25307. }
  25308. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25309. if (!this.ambientTexture.isReady()) {
  25310. return false;
  25311. }
  25312. else {
  25313. needUVs = true;
  25314. this._defines.AMBIENT = true;
  25315. }
  25316. }
  25317. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25318. if (!this.opacityTexture.isReady()) {
  25319. return false;
  25320. }
  25321. else {
  25322. needUVs = true;
  25323. this._defines.OPACITY = true;
  25324. if (this.opacityTexture.getAlphaFromRGB) {
  25325. this._defines.OPACITYRGB = true;
  25326. }
  25327. }
  25328. }
  25329. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25330. if (!this.reflectionTexture.isReady()) {
  25331. return false;
  25332. }
  25333. else {
  25334. needNormals = true;
  25335. this._defines.REFLECTION = true;
  25336. if (this.roughness > 0) {
  25337. this._defines.ROUGHNESS = true;
  25338. }
  25339. if (this.useReflectionOverAlpha) {
  25340. this._defines.REFLECTIONOVERALPHA = true;
  25341. }
  25342. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  25343. this._defines.INVERTCUBICMAP = true;
  25344. }
  25345. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  25346. switch (this.reflectionTexture.coordinatesMode) {
  25347. case BABYLON.Texture.CUBIC_MODE:
  25348. case BABYLON.Texture.INVCUBIC_MODE:
  25349. this._defines.REFLECTIONMAP_CUBIC = true;
  25350. break;
  25351. case BABYLON.Texture.EXPLICIT_MODE:
  25352. this._defines.REFLECTIONMAP_EXPLICIT = true;
  25353. break;
  25354. case BABYLON.Texture.PLANAR_MODE:
  25355. this._defines.REFLECTIONMAP_PLANAR = true;
  25356. break;
  25357. case BABYLON.Texture.PROJECTION_MODE:
  25358. this._defines.REFLECTIONMAP_PROJECTION = true;
  25359. break;
  25360. case BABYLON.Texture.SKYBOX_MODE:
  25361. this._defines.REFLECTIONMAP_SKYBOX = true;
  25362. break;
  25363. case BABYLON.Texture.SPHERICAL_MODE:
  25364. this._defines.REFLECTIONMAP_SPHERICAL = true;
  25365. break;
  25366. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  25367. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  25368. break;
  25369. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  25370. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  25371. break;
  25372. }
  25373. }
  25374. }
  25375. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25376. if (!this.emissiveTexture.isReady()) {
  25377. return false;
  25378. }
  25379. else {
  25380. needUVs = true;
  25381. this._defines.EMISSIVE = true;
  25382. }
  25383. }
  25384. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25385. if (!this.lightmapTexture.isReady()) {
  25386. return false;
  25387. }
  25388. else {
  25389. needUVs = true;
  25390. this._defines.LIGHTMAP = true;
  25391. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  25392. }
  25393. }
  25394. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25395. if (!this.specularTexture.isReady()) {
  25396. return false;
  25397. }
  25398. else {
  25399. needUVs = true;
  25400. this._defines.SPECULAR = true;
  25401. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25402. }
  25403. }
  25404. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25405. if (!this.bumpTexture.isReady()) {
  25406. return false;
  25407. }
  25408. else {
  25409. needUVs = true;
  25410. this._defines.BUMP = true;
  25411. if (this.useParallax) {
  25412. this._defines.PARALLAX = true;
  25413. if (this.useParallaxOcclusion) {
  25414. this._defines.PARALLAXOCCLUSION = true;
  25415. }
  25416. }
  25417. if (this.invertNormalMapX) {
  25418. this._defines.INVERTNORMALMAPX = true;
  25419. }
  25420. if (this.invertNormalMapY) {
  25421. this._defines.INVERTNORMALMAPY = true;
  25422. }
  25423. }
  25424. }
  25425. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25426. if (!this.refractionTexture.isReady()) {
  25427. return false;
  25428. }
  25429. else {
  25430. needUVs = true;
  25431. this._defines.REFRACTION = true;
  25432. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  25433. }
  25434. }
  25435. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25436. if (!this.cameraColorGradingTexture.isReady()) {
  25437. return false;
  25438. }
  25439. else {
  25440. this._defines.CAMERACOLORGRADING = true;
  25441. }
  25442. }
  25443. }
  25444. // Effect
  25445. if (scene.clipPlane) {
  25446. this._defines.CLIPPLANE = true;
  25447. }
  25448. if (engine.getAlphaTesting()) {
  25449. this._defines.ALPHATEST = true;
  25450. }
  25451. if (this._shouldUseAlphaFromDiffuseTexture()) {
  25452. this._defines.ALPHAFROMDIFFUSE = true;
  25453. }
  25454. if (this.useEmissiveAsIllumination) {
  25455. this._defines.EMISSIVEASILLUMINATION = true;
  25456. }
  25457. if (this.linkEmissiveWithDiffuse) {
  25458. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  25459. }
  25460. if (this.useLogarithmicDepth) {
  25461. this._defines.LOGARITHMICDEPTH = true;
  25462. }
  25463. if (this.cameraColorCurves) {
  25464. this._defines.CAMERACOLORCURVES = true;
  25465. }
  25466. // Point size
  25467. if (this.pointsCloud || scene.forcePointsCloud) {
  25468. this._defines.POINTSIZE = true;
  25469. }
  25470. // Fog
  25471. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25472. this._defines.FOG = true;
  25473. }
  25474. if (scene.lightsEnabled && !this.disableLighting) {
  25475. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  25476. }
  25477. if (StandardMaterial.FresnelEnabled) {
  25478. // Fresnel
  25479. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  25480. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  25481. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  25482. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  25483. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25484. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25485. this._defines.DIFFUSEFRESNEL = true;
  25486. }
  25487. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25488. this._defines.OPACITYFRESNEL = true;
  25489. }
  25490. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25491. this._defines.REFLECTIONFRESNEL = true;
  25492. if (this.useReflectionFresnelFromSpecular) {
  25493. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  25494. }
  25495. }
  25496. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25497. this._defines.REFRACTIONFRESNEL = true;
  25498. }
  25499. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25500. this._defines.EMISSIVEFRESNEL = true;
  25501. }
  25502. needNormals = true;
  25503. this._defines.FRESNEL = true;
  25504. }
  25505. }
  25506. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  25507. this._defines.SPECULAROVERALPHA = true;
  25508. }
  25509. // Attribs
  25510. if (mesh) {
  25511. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25512. this._defines.NORMAL = true;
  25513. }
  25514. if (needUVs) {
  25515. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25516. this._defines.UV1 = true;
  25517. }
  25518. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25519. this._defines.UV2 = true;
  25520. }
  25521. }
  25522. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25523. this._defines.VERTEXCOLOR = true;
  25524. if (mesh.hasVertexAlpha) {
  25525. this._defines.VERTEXALPHA = true;
  25526. }
  25527. }
  25528. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25529. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  25530. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  25531. }
  25532. // Instances
  25533. if (useInstances) {
  25534. this._defines.INSTANCES = true;
  25535. }
  25536. }
  25537. // Get correct effect
  25538. if (!this._defines.isEqual(this._cachedDefines)) {
  25539. this._defines.cloneTo(this._cachedDefines);
  25540. scene.resetCachedMaterial();
  25541. // Fallbacks
  25542. var fallbacks = new BABYLON.EffectFallbacks();
  25543. if (this._defines.REFLECTION) {
  25544. fallbacks.addFallback(0, "REFLECTION");
  25545. }
  25546. if (this._defines.SPECULAR) {
  25547. fallbacks.addFallback(0, "SPECULAR");
  25548. }
  25549. if (this._defines.BUMP) {
  25550. fallbacks.addFallback(0, "BUMP");
  25551. }
  25552. if (this._defines.PARALLAX) {
  25553. fallbacks.addFallback(1, "PARALLAX");
  25554. }
  25555. if (this._defines.PARALLAXOCCLUSION) {
  25556. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  25557. }
  25558. if (this._defines.SPECULAROVERALPHA) {
  25559. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  25560. }
  25561. if (this._defines.FOG) {
  25562. fallbacks.addFallback(1, "FOG");
  25563. }
  25564. if (this._defines.POINTSIZE) {
  25565. fallbacks.addFallback(0, "POINTSIZE");
  25566. }
  25567. if (this._defines.LOGARITHMICDEPTH) {
  25568. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  25569. }
  25570. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  25571. if (this._defines.SPECULARTERM) {
  25572. fallbacks.addFallback(0, "SPECULARTERM");
  25573. }
  25574. if (this._defines.DIFFUSEFRESNEL) {
  25575. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  25576. }
  25577. if (this._defines.OPACITYFRESNEL) {
  25578. fallbacks.addFallback(2, "OPACITYFRESNEL");
  25579. }
  25580. if (this._defines.REFLECTIONFRESNEL) {
  25581. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  25582. }
  25583. if (this._defines.EMISSIVEFRESNEL) {
  25584. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  25585. }
  25586. if (this._defines.FRESNEL) {
  25587. fallbacks.addFallback(4, "FRESNEL");
  25588. }
  25589. //Attributes
  25590. var attribs = [BABYLON.VertexBuffer.PositionKind];
  25591. if (this._defines.NORMAL) {
  25592. attribs.push(BABYLON.VertexBuffer.NormalKind);
  25593. }
  25594. if (this._defines.UV1) {
  25595. attribs.push(BABYLON.VertexBuffer.UVKind);
  25596. }
  25597. if (this._defines.UV2) {
  25598. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25599. }
  25600. if (this._defines.VERTEXCOLOR) {
  25601. attribs.push(BABYLON.VertexBuffer.ColorKind);
  25602. }
  25603. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  25604. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  25605. var shaderName = "default";
  25606. var join = this._defines.toString();
  25607. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  25608. "vFogInfos", "vFogColor", "pointSize",
  25609. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  25610. "mBones",
  25611. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  25612. "depthValues",
  25613. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  25614. "logarithmicDepthConstant"
  25615. ];
  25616. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  25617. if (this._defines.CAMERACOLORCURVES) {
  25618. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  25619. }
  25620. if (this._defines.CAMERACOLORGRADING) {
  25621. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  25622. }
  25623. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  25624. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  25625. }
  25626. if (!this._effect.isReady()) {
  25627. return false;
  25628. }
  25629. this._renderId = scene.getRenderId();
  25630. this._wasPreviouslyReady = true;
  25631. if (mesh) {
  25632. if (!mesh._materialDefines) {
  25633. mesh._materialDefines = new StandardMaterialDefines();
  25634. }
  25635. this._defines.cloneTo(mesh._materialDefines);
  25636. }
  25637. return true;
  25638. };
  25639. StandardMaterial.prototype.unbind = function () {
  25640. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  25641. this._effect.setTexture("reflection2DSampler", null);
  25642. }
  25643. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  25644. this._effect.setTexture("refraction2DSampler", null);
  25645. }
  25646. _super.prototype.unbind.call(this);
  25647. };
  25648. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25649. this._effect.setMatrix("world", world);
  25650. };
  25651. StandardMaterial.prototype.bind = function (world, mesh) {
  25652. var scene = this.getScene();
  25653. // Matrices
  25654. this.bindOnlyWorldMatrix(world);
  25655. // Bones
  25656. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  25657. if (scene.getCachedMaterial() !== this) {
  25658. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25659. if (StandardMaterial.FresnelEnabled) {
  25660. // Fresnel
  25661. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25662. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  25663. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  25664. }
  25665. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25666. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  25667. }
  25668. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25669. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  25670. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  25671. }
  25672. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25673. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  25674. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  25675. }
  25676. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25677. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  25678. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  25679. }
  25680. }
  25681. // Textures
  25682. if (scene.texturesEnabled) {
  25683. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25684. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  25685. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  25686. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  25687. }
  25688. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25689. this._effect.setTexture("ambientSampler", this.ambientTexture);
  25690. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  25691. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  25692. }
  25693. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25694. this._effect.setTexture("opacitySampler", this.opacityTexture);
  25695. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  25696. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  25697. }
  25698. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25699. if (this.reflectionTexture.isCube) {
  25700. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  25701. }
  25702. else {
  25703. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  25704. }
  25705. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  25706. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  25707. }
  25708. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25709. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  25710. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  25711. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  25712. }
  25713. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25714. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  25715. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  25716. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  25717. }
  25718. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25719. this._effect.setTexture("specularSampler", this.specularTexture);
  25720. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  25721. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  25722. }
  25723. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  25724. this._effect.setTexture("bumpSampler", this.bumpTexture);
  25725. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  25726. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  25727. }
  25728. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25729. var depth = 1.0;
  25730. if (this.refractionTexture.isCube) {
  25731. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  25732. }
  25733. else {
  25734. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  25735. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  25736. if (this.refractionTexture.depth) {
  25737. depth = this.refractionTexture.depth;
  25738. }
  25739. }
  25740. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  25741. }
  25742. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25743. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  25744. }
  25745. }
  25746. // Clip plane
  25747. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  25748. // Point size
  25749. if (this.pointsCloud) {
  25750. this._effect.setFloat("pointSize", this.pointSize);
  25751. }
  25752. // Colors
  25753. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  25754. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  25755. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  25756. if (this._defines.SPECULARTERM) {
  25757. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  25758. }
  25759. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  25760. }
  25761. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  25762. // Diffuse
  25763. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  25764. // Lights
  25765. if (scene.lightsEnabled && !this.disableLighting) {
  25766. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  25767. }
  25768. // View
  25769. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  25770. this._effect.setMatrix("view", scene.getViewMatrix());
  25771. }
  25772. // Fog
  25773. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  25774. // Log. depth
  25775. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  25776. // Color Curves
  25777. if (this.cameraColorCurves) {
  25778. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  25779. }
  25780. }
  25781. _super.prototype.bind.call(this, world, mesh);
  25782. };
  25783. StandardMaterial.prototype.getAnimatables = function () {
  25784. var results = [];
  25785. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  25786. results.push(this.diffuseTexture);
  25787. }
  25788. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  25789. results.push(this.ambientTexture);
  25790. }
  25791. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  25792. results.push(this.opacityTexture);
  25793. }
  25794. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  25795. results.push(this.reflectionTexture);
  25796. }
  25797. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  25798. results.push(this.emissiveTexture);
  25799. }
  25800. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  25801. results.push(this.specularTexture);
  25802. }
  25803. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  25804. results.push(this.bumpTexture);
  25805. }
  25806. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  25807. results.push(this.lightmapTexture);
  25808. }
  25809. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  25810. results.push(this.refractionTexture);
  25811. }
  25812. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  25813. results.push(this.cameraColorGradingTexture);
  25814. }
  25815. return results;
  25816. };
  25817. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25818. if (forceDisposeTextures) {
  25819. if (this.diffuseTexture) {
  25820. this.diffuseTexture.dispose();
  25821. }
  25822. if (this.ambientTexture) {
  25823. this.ambientTexture.dispose();
  25824. }
  25825. if (this.opacityTexture) {
  25826. this.opacityTexture.dispose();
  25827. }
  25828. if (this.reflectionTexture) {
  25829. this.reflectionTexture.dispose();
  25830. }
  25831. if (this.emissiveTexture) {
  25832. this.emissiveTexture.dispose();
  25833. }
  25834. if (this.specularTexture) {
  25835. this.specularTexture.dispose();
  25836. }
  25837. if (this.bumpTexture) {
  25838. this.bumpTexture.dispose();
  25839. }
  25840. if (this.lightmapTexture) {
  25841. this.lightmapTexture.dispose();
  25842. }
  25843. if (this.refractionTexture) {
  25844. this.refractionTexture.dispose();
  25845. }
  25846. if (this.cameraColorGradingTexture) {
  25847. this.cameraColorGradingTexture.dispose();
  25848. }
  25849. }
  25850. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  25851. };
  25852. StandardMaterial.prototype.clone = function (name) {
  25853. var _this = this;
  25854. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  25855. };
  25856. StandardMaterial.prototype.serialize = function () {
  25857. return BABYLON.SerializationHelper.Serialize(this);
  25858. };
  25859. // Statics
  25860. StandardMaterial.Parse = function (source, scene, rootUrl) {
  25861. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  25862. };
  25863. // Flags used to enable or disable a type of texture for all Standard Materials
  25864. StandardMaterial.DiffuseTextureEnabled = true;
  25865. StandardMaterial.AmbientTextureEnabled = true;
  25866. StandardMaterial.OpacityTextureEnabled = true;
  25867. StandardMaterial.ReflectionTextureEnabled = true;
  25868. StandardMaterial.EmissiveTextureEnabled = true;
  25869. StandardMaterial.SpecularTextureEnabled = true;
  25870. StandardMaterial.BumpTextureEnabled = true;
  25871. StandardMaterial.FresnelEnabled = true;
  25872. StandardMaterial.LightmapTextureEnabled = true;
  25873. StandardMaterial.RefractionTextureEnabled = true;
  25874. StandardMaterial.ColorGradingTextureEnabled = true;
  25875. __decorate([
  25876. BABYLON.serializeAsTexture()
  25877. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  25878. __decorate([
  25879. BABYLON.serializeAsTexture()
  25880. ], StandardMaterial.prototype, "ambientTexture", void 0);
  25881. __decorate([
  25882. BABYLON.serializeAsTexture()
  25883. ], StandardMaterial.prototype, "opacityTexture", void 0);
  25884. __decorate([
  25885. BABYLON.serializeAsTexture()
  25886. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  25887. __decorate([
  25888. BABYLON.serializeAsTexture()
  25889. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  25890. __decorate([
  25891. BABYLON.serializeAsTexture()
  25892. ], StandardMaterial.prototype, "specularTexture", void 0);
  25893. __decorate([
  25894. BABYLON.serializeAsTexture()
  25895. ], StandardMaterial.prototype, "bumpTexture", void 0);
  25896. __decorate([
  25897. BABYLON.serializeAsTexture()
  25898. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  25899. __decorate([
  25900. BABYLON.serializeAsTexture()
  25901. ], StandardMaterial.prototype, "refractionTexture", void 0);
  25902. __decorate([
  25903. BABYLON.serializeAsColor3("ambient")
  25904. ], StandardMaterial.prototype, "ambientColor", void 0);
  25905. __decorate([
  25906. BABYLON.serializeAsColor3("diffuse")
  25907. ], StandardMaterial.prototype, "diffuseColor", void 0);
  25908. __decorate([
  25909. BABYLON.serializeAsColor3("specular")
  25910. ], StandardMaterial.prototype, "specularColor", void 0);
  25911. __decorate([
  25912. BABYLON.serializeAsColor3("emissive")
  25913. ], StandardMaterial.prototype, "emissiveColor", void 0);
  25914. __decorate([
  25915. BABYLON.serialize()
  25916. ], StandardMaterial.prototype, "specularPower", void 0);
  25917. __decorate([
  25918. BABYLON.serialize()
  25919. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  25920. __decorate([
  25921. BABYLON.serialize()
  25922. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  25923. __decorate([
  25924. BABYLON.serialize()
  25925. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  25926. __decorate([
  25927. BABYLON.serialize()
  25928. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  25929. __decorate([
  25930. BABYLON.serialize()
  25931. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  25932. __decorate([
  25933. BABYLON.serialize()
  25934. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  25935. __decorate([
  25936. BABYLON.serialize()
  25937. ], StandardMaterial.prototype, "disableLighting", void 0);
  25938. __decorate([
  25939. BABYLON.serialize()
  25940. ], StandardMaterial.prototype, "useParallax", void 0);
  25941. __decorate([
  25942. BABYLON.serialize()
  25943. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  25944. __decorate([
  25945. BABYLON.serialize()
  25946. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  25947. __decorate([
  25948. BABYLON.serialize()
  25949. ], StandardMaterial.prototype, "roughness", void 0);
  25950. __decorate([
  25951. BABYLON.serialize()
  25952. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  25953. __decorate([
  25954. BABYLON.serialize()
  25955. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  25956. __decorate([
  25957. BABYLON.serialize()
  25958. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  25959. __decorate([
  25960. BABYLON.serializeAsFresnelParameters()
  25961. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  25962. __decorate([
  25963. BABYLON.serializeAsFresnelParameters()
  25964. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  25965. __decorate([
  25966. BABYLON.serializeAsFresnelParameters()
  25967. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  25968. __decorate([
  25969. BABYLON.serializeAsFresnelParameters()
  25970. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  25971. __decorate([
  25972. BABYLON.serializeAsFresnelParameters()
  25973. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  25974. __decorate([
  25975. BABYLON.serialize()
  25976. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  25977. __decorate([
  25978. BABYLON.serialize()
  25979. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  25980. __decorate([
  25981. BABYLON.serialize()
  25982. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  25983. __decorate([
  25984. BABYLON.serialize()
  25985. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  25986. __decorate([
  25987. BABYLON.serializeAsTexture()
  25988. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  25989. __decorate([
  25990. BABYLON.serializeAsColorCurves()
  25991. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  25992. __decorate([
  25993. BABYLON.serialize()
  25994. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  25995. return StandardMaterial;
  25996. })(BABYLON.Material);
  25997. BABYLON.StandardMaterial = StandardMaterial;
  25998. })(BABYLON || (BABYLON = {}));
  25999. var BABYLON;
  26000. (function (BABYLON) {
  26001. var MultiMaterial = (function (_super) {
  26002. __extends(MultiMaterial, _super);
  26003. function MultiMaterial(name, scene) {
  26004. _super.call(this, name, scene, true);
  26005. this.subMaterials = new Array();
  26006. scene.multiMaterials.push(this);
  26007. }
  26008. // Properties
  26009. MultiMaterial.prototype.getSubMaterial = function (index) {
  26010. if (index < 0 || index >= this.subMaterials.length) {
  26011. return this.getScene().defaultMaterial;
  26012. }
  26013. return this.subMaterials[index];
  26014. };
  26015. // Methods
  26016. MultiMaterial.prototype.isReady = function (mesh) {
  26017. for (var index = 0; index < this.subMaterials.length; index++) {
  26018. var subMaterial = this.subMaterials[index];
  26019. if (subMaterial) {
  26020. if (!this.subMaterials[index].isReady(mesh)) {
  26021. return false;
  26022. }
  26023. }
  26024. }
  26025. return true;
  26026. };
  26027. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  26028. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  26029. for (var index = 0; index < this.subMaterials.length; index++) {
  26030. var subMaterial = null;
  26031. if (cloneChildren) {
  26032. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  26033. }
  26034. else {
  26035. subMaterial = this.subMaterials[index];
  26036. }
  26037. newMultiMaterial.subMaterials.push(subMaterial);
  26038. }
  26039. return newMultiMaterial;
  26040. };
  26041. MultiMaterial.prototype.serialize = function () {
  26042. var serializationObject = {};
  26043. serializationObject.name = this.name;
  26044. serializationObject.id = this.id;
  26045. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26046. serializationObject.materials = [];
  26047. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  26048. var subMat = this.subMaterials[matIndex];
  26049. if (subMat) {
  26050. serializationObject.materials.push(subMat.id);
  26051. }
  26052. else {
  26053. serializationObject.materials.push(null);
  26054. }
  26055. }
  26056. return serializationObject;
  26057. };
  26058. return MultiMaterial;
  26059. })(BABYLON.Material);
  26060. BABYLON.MultiMaterial = MultiMaterial;
  26061. })(BABYLON || (BABYLON = {}));
  26062. var BABYLON;
  26063. (function (BABYLON) {
  26064. var SceneLoader = (function () {
  26065. function SceneLoader() {
  26066. }
  26067. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  26068. get: function () {
  26069. return 0;
  26070. },
  26071. enumerable: true,
  26072. configurable: true
  26073. });
  26074. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  26075. get: function () {
  26076. return 1;
  26077. },
  26078. enumerable: true,
  26079. configurable: true
  26080. });
  26081. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  26082. get: function () {
  26083. return 2;
  26084. },
  26085. enumerable: true,
  26086. configurable: true
  26087. });
  26088. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  26089. get: function () {
  26090. return 3;
  26091. },
  26092. enumerable: true,
  26093. configurable: true
  26094. });
  26095. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  26096. get: function () {
  26097. return SceneLoader._ForceFullSceneLoadingForIncremental;
  26098. },
  26099. set: function (value) {
  26100. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  26101. },
  26102. enumerable: true,
  26103. configurable: true
  26104. });
  26105. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  26106. get: function () {
  26107. return SceneLoader._ShowLoadingScreen;
  26108. },
  26109. set: function (value) {
  26110. SceneLoader._ShowLoadingScreen = value;
  26111. },
  26112. enumerable: true,
  26113. configurable: true
  26114. });
  26115. Object.defineProperty(SceneLoader, "loggingLevel", {
  26116. get: function () {
  26117. return SceneLoader._loggingLevel;
  26118. },
  26119. set: function (value) {
  26120. SceneLoader._loggingLevel = value;
  26121. },
  26122. enumerable: true,
  26123. configurable: true
  26124. });
  26125. SceneLoader._getPluginForFilename = function (sceneFilename) {
  26126. var dotPosition = sceneFilename.lastIndexOf(".");
  26127. var queryStringPosition = sceneFilename.indexOf("?");
  26128. if (queryStringPosition === -1) {
  26129. queryStringPosition = sceneFilename.length;
  26130. }
  26131. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  26132. for (var index = 0; index < this._registeredPlugins.length; index++) {
  26133. var plugin = this._registeredPlugins[index];
  26134. if (plugin.extensions.indexOf(extension) !== -1) {
  26135. return plugin;
  26136. }
  26137. }
  26138. return this._registeredPlugins[0];
  26139. };
  26140. // Public functions
  26141. SceneLoader.GetPluginForExtension = function (extension) {
  26142. for (var index = 0; index < this._registeredPlugins.length; index++) {
  26143. var plugin = this._registeredPlugins[index];
  26144. if (plugin.extensions.indexOf(extension) !== -1) {
  26145. return plugin;
  26146. }
  26147. }
  26148. return null;
  26149. };
  26150. SceneLoader.RegisterPlugin = function (plugin) {
  26151. plugin.extensions = plugin.extensions.toLowerCase();
  26152. SceneLoader._registeredPlugins.push(plugin);
  26153. };
  26154. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26155. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26156. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26157. return;
  26158. }
  26159. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26160. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26161. return;
  26162. }
  26163. var loadingToken = {};
  26164. scene._addPendingData(loadingToken);
  26165. var manifestChecked = function (success) {
  26166. scene.database = database;
  26167. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  26168. var importMeshFromData = function (data) {
  26169. var meshes = [];
  26170. var particleSystems = [];
  26171. var skeletons = [];
  26172. try {
  26173. if (plugin.importMesh) {
  26174. var syncedPlugin = plugin;
  26175. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  26176. if (onerror) {
  26177. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26178. }
  26179. scene._removePendingData(loadingToken);
  26180. return;
  26181. }
  26182. if (onsuccess) {
  26183. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26184. onsuccess(meshes, particleSystems, skeletons);
  26185. scene._removePendingData(loadingToken);
  26186. }
  26187. }
  26188. else {
  26189. var asyncedPlugin = plugin;
  26190. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  26191. if (onsuccess) {
  26192. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26193. onsuccess(meshes, particleSystems, skeletons);
  26194. scene._removePendingData(loadingToken);
  26195. }
  26196. }, function () {
  26197. if (onerror) {
  26198. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26199. }
  26200. scene._removePendingData(loadingToken);
  26201. });
  26202. }
  26203. }
  26204. catch (e) {
  26205. if (onerror) {
  26206. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  26207. }
  26208. scene._removePendingData(loadingToken);
  26209. }
  26210. };
  26211. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  26212. // Direct load
  26213. importMeshFromData(sceneFilename.substr(5));
  26214. return;
  26215. }
  26216. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  26217. importMeshFromData(data);
  26218. }, progressCallBack, database);
  26219. };
  26220. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  26221. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26222. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26223. }
  26224. else {
  26225. // If the scene is a data stream or offline support is not enabled, it's a direct load
  26226. manifestChecked(true);
  26227. }
  26228. };
  26229. /**
  26230. * Load a scene
  26231. * @param rootUrl a string that defines the root url for scene and resources
  26232. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26233. * @param engine is the instance of BABYLON.Engine to use to create the scene
  26234. */
  26235. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  26236. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  26237. };
  26238. /**
  26239. * Append a scene
  26240. * @param rootUrl a string that defines the root url for scene and resources
  26241. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26242. * @param scene is the instance of BABYLON.Scene to append to
  26243. */
  26244. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26245. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26246. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26247. return;
  26248. }
  26249. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  26250. var database;
  26251. var loadingToken = {};
  26252. scene._addPendingData(loadingToken);
  26253. if (SceneLoader.ShowLoadingScreen) {
  26254. scene.getEngine().displayLoadingUI();
  26255. }
  26256. var loadSceneFromData = function (data) {
  26257. scene.database = database;
  26258. if (plugin.load) {
  26259. var syncedPlugin = plugin;
  26260. if (!syncedPlugin.load(scene, data, rootUrl)) {
  26261. if (onerror) {
  26262. onerror(scene);
  26263. }
  26264. scene._removePendingData(loadingToken);
  26265. scene.getEngine().hideLoadingUI();
  26266. return;
  26267. }
  26268. if (onsuccess) {
  26269. onsuccess(scene);
  26270. }
  26271. scene._removePendingData(loadingToken);
  26272. }
  26273. else {
  26274. var asyncedPlugin = plugin;
  26275. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  26276. if (onsuccess) {
  26277. onsuccess(scene);
  26278. }
  26279. }, function () {
  26280. if (onerror) {
  26281. onerror(scene);
  26282. }
  26283. scene._removePendingData(loadingToken);
  26284. scene.getEngine().hideLoadingUI();
  26285. });
  26286. }
  26287. if (SceneLoader.ShowLoadingScreen) {
  26288. scene.executeWhenReady(function () {
  26289. scene.getEngine().hideLoadingUI();
  26290. });
  26291. }
  26292. };
  26293. var manifestChecked = function (success) {
  26294. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  26295. };
  26296. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  26297. // Direct load
  26298. loadSceneFromData(sceneFilename.substr(5));
  26299. return;
  26300. }
  26301. if (rootUrl.indexOf("file:") === -1) {
  26302. if (scene.getEngine().enableOfflineSupport) {
  26303. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26304. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26305. }
  26306. else {
  26307. manifestChecked(true);
  26308. }
  26309. }
  26310. else {
  26311. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  26312. }
  26313. };
  26314. // Flags
  26315. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  26316. SceneLoader._ShowLoadingScreen = true;
  26317. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  26318. // Members
  26319. SceneLoader._registeredPlugins = new Array();
  26320. return SceneLoader;
  26321. })();
  26322. BABYLON.SceneLoader = SceneLoader;
  26323. ;
  26324. })(BABYLON || (BABYLON = {}));
  26325. var BABYLON;
  26326. (function (BABYLON) {
  26327. var Internals;
  26328. (function (Internals) {
  26329. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  26330. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26331. var parsedMaterial = parsedData.materials[index];
  26332. if (parsedMaterial.id === id) {
  26333. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26334. }
  26335. }
  26336. return null;
  26337. };
  26338. var isDescendantOf = function (mesh, names, hierarchyIds) {
  26339. names = (names instanceof Array) ? names : [names];
  26340. for (var i in names) {
  26341. if (mesh.name === names[i]) {
  26342. hierarchyIds.push(mesh.id);
  26343. return true;
  26344. }
  26345. }
  26346. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  26347. hierarchyIds.push(mesh.id);
  26348. return true;
  26349. }
  26350. return false;
  26351. };
  26352. var logOperation = function (operation, producer) {
  26353. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  26354. };
  26355. BABYLON.SceneLoader.RegisterPlugin({
  26356. extensions: ".babylon",
  26357. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  26358. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26359. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26360. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26361. // and avoid problems with multiple concurrent .babylon loads.
  26362. var log = "importMesh has failed JSON parse";
  26363. try {
  26364. var parsedData = JSON.parse(data);
  26365. log = "";
  26366. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26367. var loadedSkeletonsIds = [];
  26368. var loadedMaterialsIds = [];
  26369. var hierarchyIds = [];
  26370. var index;
  26371. var cache;
  26372. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26373. var parsedMesh = parsedData.meshes[index];
  26374. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  26375. if (meshesNames instanceof Array) {
  26376. // Remove found mesh name from list.
  26377. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  26378. }
  26379. //Geometry?
  26380. if (parsedMesh.geometryId) {
  26381. //does the file contain geometries?
  26382. if (parsedData.geometries) {
  26383. //find the correct geometry and add it to the scene
  26384. var found = false;
  26385. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  26386. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  26387. return;
  26388. }
  26389. else {
  26390. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  26391. if (parsedGeometryData.id === parsedMesh.geometryId) {
  26392. switch (geometryType) {
  26393. case "boxes":
  26394. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  26395. break;
  26396. case "spheres":
  26397. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  26398. break;
  26399. case "cylinders":
  26400. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  26401. break;
  26402. case "toruses":
  26403. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  26404. break;
  26405. case "grounds":
  26406. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  26407. break;
  26408. case "planes":
  26409. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  26410. break;
  26411. case "torusKnots":
  26412. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  26413. break;
  26414. case "vertexData":
  26415. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  26416. break;
  26417. }
  26418. found = true;
  26419. }
  26420. });
  26421. }
  26422. });
  26423. if (!found) {
  26424. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  26425. }
  26426. }
  26427. }
  26428. // Material ?
  26429. if (parsedMesh.materialId) {
  26430. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  26431. if (!materialFound && parsedData.multiMaterials) {
  26432. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  26433. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  26434. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  26435. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  26436. var subMatId = parsedMultiMaterial.materials[matIndex];
  26437. loadedMaterialsIds.push(subMatId);
  26438. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  26439. log += "\n\tMaterial " + mat.toString(fullDetails);
  26440. }
  26441. loadedMaterialsIds.push(parsedMultiMaterial.id);
  26442. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26443. materialFound = true;
  26444. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  26445. break;
  26446. }
  26447. }
  26448. }
  26449. if (!materialFound) {
  26450. loadedMaterialsIds.push(parsedMesh.materialId);
  26451. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  26452. if (!mat) {
  26453. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  26454. }
  26455. else {
  26456. log += "\n\tMaterial " + mat.toString(fullDetails);
  26457. }
  26458. }
  26459. }
  26460. // Skeleton ?
  26461. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  26462. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  26463. if (!skeletonAlreadyLoaded) {
  26464. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  26465. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  26466. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  26467. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26468. skeletons.push(skeleton);
  26469. loadedSkeletonsIds.push(parsedSkeleton.id);
  26470. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  26471. }
  26472. }
  26473. }
  26474. }
  26475. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26476. meshes.push(mesh);
  26477. log += "\n\tMesh " + mesh.toString(fullDetails);
  26478. }
  26479. }
  26480. // Connecting parents
  26481. var currentMesh;
  26482. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26483. currentMesh = scene.meshes[index];
  26484. if (currentMesh._waitingParentId) {
  26485. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  26486. currentMesh._waitingParentId = undefined;
  26487. }
  26488. }
  26489. // freeze and compute world matrix application
  26490. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26491. currentMesh = scene.meshes[index];
  26492. if (currentMesh._waitingFreezeWorldMatrix) {
  26493. currentMesh.freezeWorldMatrix();
  26494. currentMesh._waitingFreezeWorldMatrix = undefined;
  26495. }
  26496. else {
  26497. currentMesh.computeWorldMatrix(true);
  26498. }
  26499. }
  26500. // Particles
  26501. if (parsedData.particleSystems) {
  26502. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26503. var parsedParticleSystem = parsedData.particleSystems[index];
  26504. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  26505. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  26506. }
  26507. }
  26508. }
  26509. return true;
  26510. }
  26511. catch (err) {
  26512. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  26513. log = null;
  26514. throw err;
  26515. }
  26516. finally {
  26517. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26518. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26519. }
  26520. }
  26521. },
  26522. load: function (scene, data, rootUrl) {
  26523. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26524. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26525. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26526. // and avoid problems with multiple concurrent .babylon loads.
  26527. var log = "importScene has failed JSON parse";
  26528. try {
  26529. var parsedData = JSON.parse(data);
  26530. log = "";
  26531. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26532. // Scene
  26533. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  26534. scene.autoClear = parsedData.autoClear;
  26535. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  26536. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  26537. if (parsedData.gravity) {
  26538. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  26539. }
  26540. // Fog
  26541. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  26542. scene.fogMode = parsedData.fogMode;
  26543. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  26544. scene.fogStart = parsedData.fogStart;
  26545. scene.fogEnd = parsedData.fogEnd;
  26546. scene.fogDensity = parsedData.fogDensity;
  26547. log += "\tFog mode for scene: ";
  26548. switch (scene.fogMode) {
  26549. // getters not compiling, so using hardcoded
  26550. case 1:
  26551. log += "exp\n";
  26552. break;
  26553. case 2:
  26554. log += "exp2\n";
  26555. break;
  26556. case 3:
  26557. log += "linear\n";
  26558. break;
  26559. }
  26560. }
  26561. //Physics
  26562. if (parsedData.physicsEnabled) {
  26563. var physicsPlugin;
  26564. if (parsedData.physicsEngine === "cannon") {
  26565. physicsPlugin = new BABYLON.CannonJSPlugin();
  26566. }
  26567. else if (parsedData.physicsEngine === "oimo") {
  26568. physicsPlugin = new BABYLON.OimoJSPlugin();
  26569. }
  26570. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  26571. //else - default engine, which is currently oimo
  26572. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  26573. scene.enablePhysics(physicsGravity, physicsPlugin);
  26574. }
  26575. //collisions, if defined. otherwise, default is true
  26576. if (parsedData.collisionsEnabled != undefined) {
  26577. scene.collisionsEnabled = parsedData.collisionsEnabled;
  26578. }
  26579. scene.workerCollisions = !!parsedData.workerCollisions;
  26580. var index;
  26581. var cache;
  26582. // Lights
  26583. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  26584. var parsedLight = parsedData.lights[index];
  26585. var light = BABYLON.Light.Parse(parsedLight, scene);
  26586. log += (index === 0 ? "\n\tLights:" : "");
  26587. log += "\n\t\t" + light.toString(fullDetails);
  26588. }
  26589. // Animations
  26590. if (parsedData.animations) {
  26591. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  26592. var parsedAnimation = parsedData.animations[index];
  26593. var animation = BABYLON.Animation.Parse(parsedAnimation);
  26594. scene.animations.push(animation);
  26595. log += (index === 0 ? "\n\tAnimations:" : "");
  26596. log += "\n\t\t" + animation.toString(fullDetails);
  26597. }
  26598. }
  26599. if (parsedData.autoAnimate) {
  26600. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  26601. }
  26602. // Materials
  26603. if (parsedData.materials) {
  26604. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26605. var parsedMaterial = parsedData.materials[index];
  26606. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26607. log += (index === 0 ? "\n\tMaterials:" : "");
  26608. log += "\n\t\t" + mat.toString(fullDetails);
  26609. }
  26610. }
  26611. if (parsedData.multiMaterials) {
  26612. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  26613. var parsedMultiMaterial = parsedData.multiMaterials[index];
  26614. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26615. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  26616. log += "\n\t\t" + mmat.toString(fullDetails);
  26617. }
  26618. }
  26619. // Skeletons
  26620. if (parsedData.skeletons) {
  26621. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  26622. var parsedSkeleton = parsedData.skeletons[index];
  26623. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26624. log += (index === 0 ? "\n\tSkeletons:" : "");
  26625. log += "\n\t\t" + skeleton.toString(fullDetails);
  26626. }
  26627. }
  26628. // Geometries
  26629. var geometries = parsedData.geometries;
  26630. if (geometries) {
  26631. // Boxes
  26632. var boxes = geometries.boxes;
  26633. if (boxes) {
  26634. for (index = 0, cache = boxes.length; index < cache; index++) {
  26635. var parsedBox = boxes[index];
  26636. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  26637. }
  26638. }
  26639. // Spheres
  26640. var spheres = geometries.spheres;
  26641. if (spheres) {
  26642. for (index = 0, cache = spheres.length; index < cache; index++) {
  26643. var parsedSphere = spheres[index];
  26644. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  26645. }
  26646. }
  26647. // Cylinders
  26648. var cylinders = geometries.cylinders;
  26649. if (cylinders) {
  26650. for (index = 0, cache = cylinders.length; index < cache; index++) {
  26651. var parsedCylinder = cylinders[index];
  26652. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  26653. }
  26654. }
  26655. // Toruses
  26656. var toruses = geometries.toruses;
  26657. if (toruses) {
  26658. for (index = 0, cache = toruses.length; index < cache; index++) {
  26659. var parsedTorus = toruses[index];
  26660. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  26661. }
  26662. }
  26663. // Grounds
  26664. var grounds = geometries.grounds;
  26665. if (grounds) {
  26666. for (index = 0, cache = grounds.length; index < cache; index++) {
  26667. var parsedGround = grounds[index];
  26668. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  26669. }
  26670. }
  26671. // Planes
  26672. var planes = geometries.planes;
  26673. if (planes) {
  26674. for (index = 0, cache = planes.length; index < cache; index++) {
  26675. var parsedPlane = planes[index];
  26676. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  26677. }
  26678. }
  26679. // TorusKnots
  26680. var torusKnots = geometries.torusKnots;
  26681. if (torusKnots) {
  26682. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  26683. var parsedTorusKnot = torusKnots[index];
  26684. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  26685. }
  26686. }
  26687. // VertexData
  26688. var vertexData = geometries.vertexData;
  26689. if (vertexData) {
  26690. for (index = 0, cache = vertexData.length; index < cache; index++) {
  26691. var parsedVertexData = vertexData[index];
  26692. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  26693. }
  26694. }
  26695. }
  26696. // Meshes
  26697. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26698. var parsedMesh = parsedData.meshes[index];
  26699. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26700. log += (index === 0 ? "\n\tMeshes:" : "");
  26701. log += "\n\t\t" + mesh.toString(fullDetails);
  26702. }
  26703. // Cameras
  26704. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  26705. var parsedCamera = parsedData.cameras[index];
  26706. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  26707. log += (index === 0 ? "\n\tCameras:" : "");
  26708. log += "\n\t\t" + camera.toString(fullDetails);
  26709. }
  26710. if (parsedData.activeCameraID) {
  26711. scene.setActiveCameraByID(parsedData.activeCameraID);
  26712. }
  26713. // Browsing all the graph to connect the dots
  26714. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  26715. var camera = scene.cameras[index];
  26716. if (camera._waitingParentId) {
  26717. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  26718. camera._waitingParentId = undefined;
  26719. }
  26720. }
  26721. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  26722. var light = scene.lights[index];
  26723. if (light._waitingParentId) {
  26724. light.parent = scene.getLastEntryByID(light._waitingParentId);
  26725. light._waitingParentId = undefined;
  26726. }
  26727. }
  26728. // Sounds
  26729. var loadedSounds = [];
  26730. var loadedSound;
  26731. if (BABYLON.AudioEngine && parsedData.sounds) {
  26732. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  26733. var parsedSound = parsedData.sounds[index];
  26734. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26735. if (!parsedSound.url)
  26736. parsedSound.url = parsedSound.name;
  26737. if (!loadedSounds[parsedSound.url]) {
  26738. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  26739. loadedSounds[parsedSound.url] = loadedSound;
  26740. }
  26741. else {
  26742. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  26743. }
  26744. }
  26745. else {
  26746. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  26747. }
  26748. }
  26749. }
  26750. loadedSounds = [];
  26751. // Connect parents & children and parse actions
  26752. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26753. var mesh = scene.meshes[index];
  26754. if (mesh._waitingParentId) {
  26755. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  26756. mesh._waitingParentId = undefined;
  26757. }
  26758. if (mesh._waitingActions) {
  26759. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  26760. mesh._waitingActions = undefined;
  26761. }
  26762. }
  26763. // freeze world matrix application
  26764. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26765. var currentMesh = scene.meshes[index];
  26766. if (currentMesh._waitingFreezeWorldMatrix) {
  26767. currentMesh.freezeWorldMatrix();
  26768. currentMesh._waitingFreezeWorldMatrix = undefined;
  26769. }
  26770. else {
  26771. currentMesh.computeWorldMatrix(true);
  26772. }
  26773. }
  26774. // Particles Systems
  26775. if (parsedData.particleSystems) {
  26776. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26777. var parsedParticleSystem = parsedData.particleSystems[index];
  26778. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  26779. }
  26780. }
  26781. // Lens flares
  26782. if (parsedData.lensFlareSystems) {
  26783. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  26784. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  26785. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  26786. }
  26787. }
  26788. // Shadows
  26789. if (parsedData.shadowGenerators) {
  26790. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  26791. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  26792. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  26793. }
  26794. }
  26795. // Actions (scene)
  26796. if (parsedData.actions) {
  26797. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  26798. }
  26799. // Finish
  26800. return true;
  26801. }
  26802. catch (err) {
  26803. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  26804. log = null;
  26805. throw err;
  26806. }
  26807. finally {
  26808. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26809. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26810. }
  26811. }
  26812. }
  26813. });
  26814. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26815. })(BABYLON || (BABYLON = {}));
  26816. var BABYLON;
  26817. (function (BABYLON) {
  26818. var SpriteManager = (function () {
  26819. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  26820. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26821. this.name = name;
  26822. this.sprites = new Array();
  26823. this.renderingGroupId = 0;
  26824. this.layerMask = 0x0FFFFFFF;
  26825. this.fogEnabled = true;
  26826. this.isPickable = false;
  26827. /**
  26828. * An event triggered when the manager is disposed.
  26829. * @type {BABYLON.Observable}
  26830. */
  26831. this.onDisposeObservable = new BABYLON.Observable();
  26832. this._vertexBuffers = {};
  26833. this._capacity = capacity;
  26834. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  26835. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26836. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26837. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  26838. if (cellSize.width) {
  26839. this.cellWidth = cellSize.width;
  26840. this.cellHeight = cellSize.height;
  26841. }
  26842. else {
  26843. this.cellWidth = cellSize;
  26844. this.cellHeight = cellSize;
  26845. }
  26846. this._scene = scene;
  26847. this._scene.spriteManagers.push(this);
  26848. var indices = [];
  26849. var index = 0;
  26850. for (var count = 0; count < capacity; count++) {
  26851. indices.push(index);
  26852. indices.push(index + 1);
  26853. indices.push(index + 2);
  26854. indices.push(index);
  26855. indices.push(index + 2);
  26856. indices.push(index + 3);
  26857. index += 4;
  26858. }
  26859. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26860. // VBO
  26861. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  26862. this._vertexData = new Float32Array(capacity * 16 * 4);
  26863. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  26864. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  26865. var options = this._buffer.createVertexBuffer("options", 4, 4);
  26866. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  26867. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  26868. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26869. this._vertexBuffers["options"] = options;
  26870. this._vertexBuffers["cellInfo"] = cellInfo;
  26871. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26872. // Effects
  26873. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  26874. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  26875. }
  26876. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  26877. set: function (callback) {
  26878. if (this._onDisposeObserver) {
  26879. this.onDisposeObservable.remove(this._onDisposeObserver);
  26880. }
  26881. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26882. },
  26883. enumerable: true,
  26884. configurable: true
  26885. });
  26886. Object.defineProperty(SpriteManager.prototype, "texture", {
  26887. get: function () {
  26888. return this._spriteTexture;
  26889. },
  26890. set: function (value) {
  26891. this._spriteTexture = value;
  26892. },
  26893. enumerable: true,
  26894. configurable: true
  26895. });
  26896. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  26897. var arrayOffset = index * 16;
  26898. if (offsetX === 0)
  26899. offsetX = this._epsilon;
  26900. else if (offsetX === 1)
  26901. offsetX = 1 - this._epsilon;
  26902. if (offsetY === 0)
  26903. offsetY = this._epsilon;
  26904. else if (offsetY === 1)
  26905. offsetY = 1 - this._epsilon;
  26906. this._vertexData[arrayOffset] = sprite.position.x;
  26907. this._vertexData[arrayOffset + 1] = sprite.position.y;
  26908. this._vertexData[arrayOffset + 2] = sprite.position.z;
  26909. this._vertexData[arrayOffset + 3] = sprite.angle;
  26910. this._vertexData[arrayOffset + 4] = sprite.width;
  26911. this._vertexData[arrayOffset + 5] = sprite.height;
  26912. this._vertexData[arrayOffset + 6] = offsetX;
  26913. this._vertexData[arrayOffset + 7] = offsetY;
  26914. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  26915. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  26916. var offset = (sprite.cellIndex / rowSize) >> 0;
  26917. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  26918. this._vertexData[arrayOffset + 11] = offset;
  26919. // Color
  26920. this._vertexData[arrayOffset + 12] = sprite.color.r;
  26921. this._vertexData[arrayOffset + 13] = sprite.color.g;
  26922. this._vertexData[arrayOffset + 14] = sprite.color.b;
  26923. this._vertexData[arrayOffset + 15] = sprite.color.a;
  26924. };
  26925. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  26926. var count = Math.min(this._capacity, this.sprites.length);
  26927. var min = BABYLON.Vector3.Zero();
  26928. var max = BABYLON.Vector3.Zero();
  26929. var distance = Number.MAX_VALUE;
  26930. var currentSprite;
  26931. var cameraSpacePosition = BABYLON.Vector3.Zero();
  26932. var cameraView = camera.getViewMatrix();
  26933. for (var index = 0; index < count; index++) {
  26934. var sprite = this.sprites[index];
  26935. if (!sprite) {
  26936. continue;
  26937. }
  26938. if (predicate) {
  26939. if (!predicate(sprite)) {
  26940. continue;
  26941. }
  26942. }
  26943. else if (!sprite.isPickable) {
  26944. continue;
  26945. }
  26946. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  26947. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  26948. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  26949. if (ray.intersectsBoxMinMax(min, max)) {
  26950. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  26951. if (distance > currentDistance) {
  26952. distance = currentDistance;
  26953. currentSprite = sprite;
  26954. if (fastCheck) {
  26955. break;
  26956. }
  26957. }
  26958. }
  26959. }
  26960. if (currentSprite) {
  26961. var result = new BABYLON.PickingInfo();
  26962. result.hit = true;
  26963. result.pickedSprite = currentSprite;
  26964. result.distance = distance;
  26965. return result;
  26966. }
  26967. return null;
  26968. };
  26969. SpriteManager.prototype.render = function () {
  26970. // Check
  26971. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  26972. return;
  26973. var engine = this._scene.getEngine();
  26974. var baseSize = this._spriteTexture.getBaseSize();
  26975. // Sprites
  26976. var deltaTime = engine.getDeltaTime();
  26977. var max = Math.min(this._capacity, this.sprites.length);
  26978. var rowSize = baseSize.width / this.cellWidth;
  26979. var offset = 0;
  26980. for (var index = 0; index < max; index++) {
  26981. var sprite = this.sprites[index];
  26982. if (!sprite) {
  26983. continue;
  26984. }
  26985. sprite._animate(deltaTime);
  26986. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  26987. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  26988. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  26989. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  26990. }
  26991. this._buffer.update(this._vertexData);
  26992. // Render
  26993. var effect = this._effectBase;
  26994. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26995. effect = this._effectFog;
  26996. }
  26997. engine.enableEffect(effect);
  26998. var viewMatrix = this._scene.getViewMatrix();
  26999. effect.setTexture("diffuseSampler", this._spriteTexture);
  27000. effect.setMatrix("view", viewMatrix);
  27001. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27002. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  27003. // Fog
  27004. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27005. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  27006. effect.setColor3("vFogColor", this._scene.fogColor);
  27007. }
  27008. // VBOs
  27009. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27010. // Draw order
  27011. engine.setDepthFunctionToLessOrEqual();
  27012. effect.setBool("alphaTest", true);
  27013. engine.setColorWrite(false);
  27014. engine.draw(true, 0, max * 6);
  27015. engine.setColorWrite(true);
  27016. effect.setBool("alphaTest", false);
  27017. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27018. engine.draw(true, 0, max * 6);
  27019. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27020. };
  27021. SpriteManager.prototype.dispose = function () {
  27022. if (this._buffer) {
  27023. this._buffer.dispose();
  27024. this._buffer = null;
  27025. }
  27026. if (this._indexBuffer) {
  27027. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27028. this._indexBuffer = null;
  27029. }
  27030. if (this._spriteTexture) {
  27031. this._spriteTexture.dispose();
  27032. this._spriteTexture = null;
  27033. }
  27034. // Remove from scene
  27035. var index = this._scene.spriteManagers.indexOf(this);
  27036. this._scene.spriteManagers.splice(index, 1);
  27037. // Callback
  27038. this.onDisposeObservable.notifyObservers(this);
  27039. this.onDisposeObservable.clear();
  27040. };
  27041. return SpriteManager;
  27042. })();
  27043. BABYLON.SpriteManager = SpriteManager;
  27044. })(BABYLON || (BABYLON = {}));
  27045. var BABYLON;
  27046. (function (BABYLON) {
  27047. var Sprite = (function () {
  27048. function Sprite(name, manager) {
  27049. this.name = name;
  27050. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27051. this.width = 1.0;
  27052. this.height = 1.0;
  27053. this.angle = 0;
  27054. this.cellIndex = 0;
  27055. this.invertU = 0;
  27056. this.invertV = 0;
  27057. this.animations = new Array();
  27058. this.isPickable = false;
  27059. this._animationStarted = false;
  27060. this._loopAnimation = false;
  27061. this._fromIndex = 0;
  27062. this._toIndex = 0;
  27063. this._delay = 0;
  27064. this._direction = 1;
  27065. this._frameCount = 0;
  27066. this._time = 0;
  27067. this._manager = manager;
  27068. this._manager.sprites.push(this);
  27069. this.position = BABYLON.Vector3.Zero();
  27070. }
  27071. Object.defineProperty(Sprite.prototype, "size", {
  27072. get: function () {
  27073. return this.width;
  27074. },
  27075. set: function (value) {
  27076. this.width = value;
  27077. this.height = value;
  27078. },
  27079. enumerable: true,
  27080. configurable: true
  27081. });
  27082. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  27083. this._fromIndex = from;
  27084. this._toIndex = to;
  27085. this._loopAnimation = loop;
  27086. this._delay = delay;
  27087. this._animationStarted = true;
  27088. this._direction = from < to ? 1 : -1;
  27089. this.cellIndex = from;
  27090. this._time = 0;
  27091. this._onAnimationEnd = onAnimationEnd;
  27092. };
  27093. Sprite.prototype.stopAnimation = function () {
  27094. this._animationStarted = false;
  27095. };
  27096. Sprite.prototype._animate = function (deltaTime) {
  27097. if (!this._animationStarted)
  27098. return;
  27099. this._time += deltaTime;
  27100. if (this._time > this._delay) {
  27101. this._time = this._time % this._delay;
  27102. this.cellIndex += this._direction;
  27103. if (this.cellIndex === this._toIndex) {
  27104. if (this._loopAnimation) {
  27105. this.cellIndex = this._fromIndex;
  27106. }
  27107. else {
  27108. this._animationStarted = false;
  27109. if (this._onAnimationEnd) {
  27110. this._onAnimationEnd();
  27111. }
  27112. if (this.disposeWhenFinishedAnimating) {
  27113. this.dispose();
  27114. }
  27115. }
  27116. }
  27117. }
  27118. };
  27119. Sprite.prototype.dispose = function () {
  27120. for (var i = 0; i < this._manager.sprites.length; i++) {
  27121. if (this._manager.sprites[i] == this) {
  27122. this._manager.sprites.splice(i, 1);
  27123. }
  27124. }
  27125. };
  27126. return Sprite;
  27127. })();
  27128. BABYLON.Sprite = Sprite;
  27129. })(BABYLON || (BABYLON = {}));
  27130. var BABYLON;
  27131. (function (BABYLON) {
  27132. var Layer = (function () {
  27133. function Layer(name, imgUrl, scene, isBackground, color) {
  27134. this.name = name;
  27135. this.scale = new BABYLON.Vector2(1, 1);
  27136. this.offset = new BABYLON.Vector2(0, 0);
  27137. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  27138. this._vertexBuffers = {};
  27139. // Events
  27140. /**
  27141. * An event triggered when the layer is disposed.
  27142. * @type {BABYLON.Observable}
  27143. */
  27144. this.onDisposeObservable = new BABYLON.Observable();
  27145. /**
  27146. * An event triggered before rendering the scene
  27147. * @type {BABYLON.Observable}
  27148. */
  27149. this.onBeforeRenderObservable = new BABYLON.Observable();
  27150. /**
  27151. * An event triggered after rendering the scene
  27152. * @type {BABYLON.Observable}
  27153. */
  27154. this.onAfterRenderObservable = new BABYLON.Observable();
  27155. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  27156. this.isBackground = isBackground === undefined ? true : isBackground;
  27157. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  27158. this._scene = scene;
  27159. this._scene.layers.push(this);
  27160. var engine = scene.getEngine();
  27161. // VBO
  27162. var vertices = [];
  27163. vertices.push(1, 1);
  27164. vertices.push(-1, 1);
  27165. vertices.push(-1, -1);
  27166. vertices.push(1, -1);
  27167. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27168. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  27169. // Indices
  27170. var indices = [];
  27171. indices.push(0);
  27172. indices.push(1);
  27173. indices.push(2);
  27174. indices.push(0);
  27175. indices.push(2);
  27176. indices.push(3);
  27177. this._indexBuffer = engine.createIndexBuffer(indices);
  27178. // Effects
  27179. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  27180. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  27181. }
  27182. Object.defineProperty(Layer.prototype, "onDispose", {
  27183. set: function (callback) {
  27184. if (this._onDisposeObserver) {
  27185. this.onDisposeObservable.remove(this._onDisposeObserver);
  27186. }
  27187. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27188. },
  27189. enumerable: true,
  27190. configurable: true
  27191. });
  27192. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  27193. set: function (callback) {
  27194. if (this._onBeforeRenderObserver) {
  27195. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27196. }
  27197. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27198. },
  27199. enumerable: true,
  27200. configurable: true
  27201. });
  27202. Object.defineProperty(Layer.prototype, "onAfterRender", {
  27203. set: function (callback) {
  27204. if (this._onAfterRenderObserver) {
  27205. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27206. }
  27207. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27208. },
  27209. enumerable: true,
  27210. configurable: true
  27211. });
  27212. Layer.prototype.render = function () {
  27213. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  27214. // Check
  27215. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  27216. return;
  27217. var engine = this._scene.getEngine();
  27218. this.onBeforeRenderObservable.notifyObservers(this);
  27219. // Render
  27220. engine.enableEffect(currentEffect);
  27221. engine.setState(false);
  27222. // Texture
  27223. currentEffect.setTexture("textureSampler", this.texture);
  27224. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  27225. // Color
  27226. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  27227. // Scale / offset
  27228. currentEffect.setVector2("offset", this.offset);
  27229. currentEffect.setVector2("scale", this.scale);
  27230. // VBOs
  27231. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  27232. // Draw order
  27233. if (!this._alphaTestEffect) {
  27234. engine.setAlphaMode(this.alphaBlendingMode);
  27235. engine.draw(true, 0, 6);
  27236. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27237. }
  27238. else {
  27239. engine.draw(true, 0, 6);
  27240. }
  27241. this.onAfterRenderObservable.notifyObservers(this);
  27242. };
  27243. Layer.prototype.dispose = function () {
  27244. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27245. if (vertexBuffer) {
  27246. vertexBuffer.dispose();
  27247. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27248. }
  27249. if (this._indexBuffer) {
  27250. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27251. this._indexBuffer = null;
  27252. }
  27253. if (this.texture) {
  27254. this.texture.dispose();
  27255. this.texture = null;
  27256. }
  27257. // Remove from scene
  27258. var index = this._scene.layers.indexOf(this);
  27259. this._scene.layers.splice(index, 1);
  27260. // Callback
  27261. this.onDisposeObservable.notifyObservers(this);
  27262. this.onDisposeObservable.clear();
  27263. this.onAfterRenderObservable.clear();
  27264. this.onBeforeRenderObservable.clear();
  27265. };
  27266. return Layer;
  27267. })();
  27268. BABYLON.Layer = Layer;
  27269. })(BABYLON || (BABYLON = {}));
  27270. var BABYLON;
  27271. (function (BABYLON) {
  27272. var Particle = (function () {
  27273. function Particle() {
  27274. this.position = BABYLON.Vector3.Zero();
  27275. this.direction = BABYLON.Vector3.Zero();
  27276. this.color = new BABYLON.Color4(0, 0, 0, 0);
  27277. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  27278. this.lifeTime = 1.0;
  27279. this.age = 0;
  27280. this.size = 0;
  27281. this.angle = 0;
  27282. this.angularSpeed = 0;
  27283. }
  27284. Particle.prototype.copyTo = function (other) {
  27285. other.position.copyFrom(this.position);
  27286. other.direction.copyFrom(this.direction);
  27287. other.color.copyFrom(this.color);
  27288. other.colorStep.copyFrom(this.colorStep);
  27289. other.lifeTime = this.lifeTime;
  27290. other.age = this.age;
  27291. other.size = this.size;
  27292. other.angle = this.angle;
  27293. other.angularSpeed = this.angularSpeed;
  27294. };
  27295. return Particle;
  27296. })();
  27297. BABYLON.Particle = Particle;
  27298. })(BABYLON || (BABYLON = {}));
  27299. var BABYLON;
  27300. (function (BABYLON) {
  27301. var randomNumber = function (min, max) {
  27302. if (min === max) {
  27303. return (min);
  27304. }
  27305. var random = Math.random();
  27306. return ((random * (max - min)) + min);
  27307. };
  27308. var ParticleSystem = (function () {
  27309. function ParticleSystem(name, capacity, scene, customEffect) {
  27310. var _this = this;
  27311. this.name = name;
  27312. // Members
  27313. this.animations = [];
  27314. this.renderingGroupId = 0;
  27315. this.emitter = null;
  27316. this.emitRate = 10;
  27317. this.manualEmitCount = -1;
  27318. this.updateSpeed = 0.01;
  27319. this.targetStopDuration = 0;
  27320. this.disposeOnStop = false;
  27321. this.minEmitPower = 1;
  27322. this.maxEmitPower = 1;
  27323. this.minLifeTime = 1;
  27324. this.maxLifeTime = 1;
  27325. this.minSize = 1;
  27326. this.maxSize = 1;
  27327. this.minAngularSpeed = 0;
  27328. this.maxAngularSpeed = 0;
  27329. this.layerMask = 0x0FFFFFFF;
  27330. /**
  27331. * An event triggered when the system is disposed.
  27332. * @type {BABYLON.Observable}
  27333. */
  27334. this.onDisposeObservable = new BABYLON.Observable();
  27335. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  27336. this.forceDepthWrite = false;
  27337. this.gravity = BABYLON.Vector3.Zero();
  27338. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  27339. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  27340. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  27341. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  27342. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27343. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27344. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  27345. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27346. this.particles = new Array();
  27347. this._stockParticles = new Array();
  27348. this._newPartsExcess = 0;
  27349. this._vertexBuffers = {};
  27350. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  27351. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  27352. this._scaledDirection = BABYLON.Vector3.Zero();
  27353. this._scaledGravity = BABYLON.Vector3.Zero();
  27354. this._currentRenderId = -1;
  27355. this._started = false;
  27356. this._stopped = false;
  27357. this._actualFrame = 0;
  27358. this.id = name;
  27359. this._capacity = capacity;
  27360. this._scene = scene;
  27361. this._customEffect = customEffect;
  27362. scene.particleSystems.push(this);
  27363. var indices = [];
  27364. var index = 0;
  27365. for (var count = 0; count < capacity; count++) {
  27366. indices.push(index);
  27367. indices.push(index + 1);
  27368. indices.push(index + 2);
  27369. indices.push(index);
  27370. indices.push(index + 2);
  27371. indices.push(index + 3);
  27372. index += 4;
  27373. }
  27374. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27375. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  27376. this._vertexData = new Float32Array(capacity * 11 * 4);
  27377. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  27378. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  27379. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  27380. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  27381. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27382. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27383. this._vertexBuffers["options"] = options;
  27384. // Default behaviors
  27385. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  27386. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  27387. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  27388. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  27389. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  27390. };
  27391. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  27392. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  27393. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  27394. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  27395. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  27396. };
  27397. this.updateFunction = function (particles) {
  27398. for (var index = 0; index < particles.length; index++) {
  27399. var particle = particles[index];
  27400. particle.age += _this._scaledUpdateSpeed;
  27401. if (particle.age >= particle.lifeTime) {
  27402. _this.recycleParticle(particle);
  27403. index--;
  27404. continue;
  27405. }
  27406. else {
  27407. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  27408. particle.color.addInPlace(_this._scaledColorStep);
  27409. if (particle.color.a < 0)
  27410. particle.color.a = 0;
  27411. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  27412. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  27413. particle.position.addInPlace(_this._scaledDirection);
  27414. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  27415. particle.direction.addInPlace(_this._scaledGravity);
  27416. }
  27417. }
  27418. };
  27419. }
  27420. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  27421. set: function (callback) {
  27422. if (this._onDisposeObserver) {
  27423. this.onDisposeObservable.remove(this._onDisposeObserver);
  27424. }
  27425. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27426. },
  27427. enumerable: true,
  27428. configurable: true
  27429. });
  27430. ParticleSystem.prototype.recycleParticle = function (particle) {
  27431. var lastParticle = this.particles.pop();
  27432. if (lastParticle !== particle) {
  27433. lastParticle.copyTo(particle);
  27434. this._stockParticles.push(lastParticle);
  27435. }
  27436. };
  27437. ParticleSystem.prototype.getCapacity = function () {
  27438. return this._capacity;
  27439. };
  27440. ParticleSystem.prototype.isAlive = function () {
  27441. return this._alive;
  27442. };
  27443. ParticleSystem.prototype.isStarted = function () {
  27444. return this._started;
  27445. };
  27446. ParticleSystem.prototype.start = function () {
  27447. this._started = true;
  27448. this._stopped = false;
  27449. this._actualFrame = 0;
  27450. };
  27451. ParticleSystem.prototype.stop = function () {
  27452. this._stopped = true;
  27453. };
  27454. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  27455. var offset = index * 11;
  27456. this._vertexData[offset] = particle.position.x;
  27457. this._vertexData[offset + 1] = particle.position.y;
  27458. this._vertexData[offset + 2] = particle.position.z;
  27459. this._vertexData[offset + 3] = particle.color.r;
  27460. this._vertexData[offset + 4] = particle.color.g;
  27461. this._vertexData[offset + 5] = particle.color.b;
  27462. this._vertexData[offset + 6] = particle.color.a;
  27463. this._vertexData[offset + 7] = particle.angle;
  27464. this._vertexData[offset + 8] = particle.size;
  27465. this._vertexData[offset + 9] = offsetX;
  27466. this._vertexData[offset + 10] = offsetY;
  27467. };
  27468. ParticleSystem.prototype._update = function (newParticles) {
  27469. // Update current
  27470. this._alive = this.particles.length > 0;
  27471. this.updateFunction(this.particles);
  27472. // Add new ones
  27473. var worldMatrix;
  27474. if (this.emitter.position) {
  27475. worldMatrix = this.emitter.getWorldMatrix();
  27476. }
  27477. else {
  27478. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  27479. }
  27480. var particle;
  27481. for (var index = 0; index < newParticles; index++) {
  27482. if (this.particles.length === this._capacity) {
  27483. break;
  27484. }
  27485. if (this._stockParticles.length !== 0) {
  27486. particle = this._stockParticles.pop();
  27487. particle.age = 0;
  27488. }
  27489. else {
  27490. particle = new BABYLON.Particle();
  27491. }
  27492. this.particles.push(particle);
  27493. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  27494. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  27495. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  27496. particle.size = randomNumber(this.minSize, this.maxSize);
  27497. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  27498. this.startPositionFunction(worldMatrix, particle.position, particle);
  27499. var step = randomNumber(0, 1.0);
  27500. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  27501. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  27502. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  27503. }
  27504. };
  27505. ParticleSystem.prototype._getEffect = function () {
  27506. if (this._customEffect) {
  27507. return this._customEffect;
  27508. }
  27509. ;
  27510. var defines = [];
  27511. if (this._scene.clipPlane) {
  27512. defines.push("#define CLIPPLANE");
  27513. }
  27514. // Effect
  27515. var join = defines.join("\n");
  27516. if (this._cachedDefines !== join) {
  27517. this._cachedDefines = join;
  27518. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  27519. }
  27520. return this._effect;
  27521. };
  27522. ParticleSystem.prototype.animate = function () {
  27523. if (!this._started)
  27524. return;
  27525. var effect = this._getEffect();
  27526. // Check
  27527. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  27528. return;
  27529. if (this._currentRenderId === this._scene.getRenderId()) {
  27530. return;
  27531. }
  27532. this._currentRenderId = this._scene.getRenderId();
  27533. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  27534. // determine the number of particles we need to create
  27535. var newParticles;
  27536. if (this.manualEmitCount > -1) {
  27537. newParticles = this.manualEmitCount;
  27538. this._newPartsExcess = 0;
  27539. this.manualEmitCount = 0;
  27540. }
  27541. else {
  27542. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  27543. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  27544. }
  27545. if (this._newPartsExcess > 1.0) {
  27546. newParticles += this._newPartsExcess >> 0;
  27547. this._newPartsExcess -= this._newPartsExcess >> 0;
  27548. }
  27549. this._alive = false;
  27550. if (!this._stopped) {
  27551. this._actualFrame += this._scaledUpdateSpeed;
  27552. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  27553. this.stop();
  27554. }
  27555. else {
  27556. newParticles = 0;
  27557. }
  27558. this._update(newParticles);
  27559. // Stopped?
  27560. if (this._stopped) {
  27561. if (!this._alive) {
  27562. this._started = false;
  27563. if (this.disposeOnStop) {
  27564. this._scene._toBeDisposed.push(this);
  27565. }
  27566. }
  27567. }
  27568. // Update VBO
  27569. var offset = 0;
  27570. for (var index = 0; index < this.particles.length; index++) {
  27571. var particle = this.particles[index];
  27572. this._appendParticleVertex(offset++, particle, 0, 0);
  27573. this._appendParticleVertex(offset++, particle, 1, 0);
  27574. this._appendParticleVertex(offset++, particle, 1, 1);
  27575. this._appendParticleVertex(offset++, particle, 0, 1);
  27576. }
  27577. this._vertexBuffer.update(this._vertexData);
  27578. };
  27579. ParticleSystem.prototype.render = function () {
  27580. var effect = this._getEffect();
  27581. // Check
  27582. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  27583. return 0;
  27584. var engine = this._scene.getEngine();
  27585. // Render
  27586. engine.enableEffect(effect);
  27587. engine.setState(false);
  27588. var viewMatrix = this._scene.getViewMatrix();
  27589. effect.setTexture("diffuseSampler", this.particleTexture);
  27590. effect.setMatrix("view", viewMatrix);
  27591. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27592. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  27593. if (this._scene.clipPlane) {
  27594. var clipPlane = this._scene.clipPlane;
  27595. var invView = viewMatrix.clone();
  27596. invView.invert();
  27597. effect.setMatrix("invView", invView);
  27598. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27599. }
  27600. // VBOs
  27601. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27602. // Draw order
  27603. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  27604. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  27605. }
  27606. else {
  27607. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27608. }
  27609. if (this.forceDepthWrite) {
  27610. engine.setDepthWrite(true);
  27611. }
  27612. engine.draw(true, 0, this.particles.length * 6);
  27613. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27614. return this.particles.length;
  27615. };
  27616. ParticleSystem.prototype.dispose = function () {
  27617. if (this._vertexBuffer) {
  27618. this._vertexBuffer.dispose();
  27619. this._vertexBuffer = null;
  27620. }
  27621. if (this._indexBuffer) {
  27622. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27623. this._indexBuffer = null;
  27624. }
  27625. if (this.particleTexture) {
  27626. this.particleTexture.dispose();
  27627. this.particleTexture = null;
  27628. }
  27629. // Remove from scene
  27630. var index = this._scene.particleSystems.indexOf(this);
  27631. this._scene.particleSystems.splice(index, 1);
  27632. // Callback
  27633. this.onDisposeObservable.notifyObservers(this);
  27634. this.onDisposeObservable.clear();
  27635. };
  27636. // Clone
  27637. ParticleSystem.prototype.clone = function (name, newEmitter) {
  27638. var result = new ParticleSystem(name, this._capacity, this._scene);
  27639. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  27640. if (newEmitter === undefined) {
  27641. newEmitter = this.emitter;
  27642. }
  27643. result.emitter = newEmitter;
  27644. if (this.particleTexture) {
  27645. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  27646. }
  27647. result.start();
  27648. return result;
  27649. };
  27650. ParticleSystem.prototype.serialize = function () {
  27651. var serializationObject = {};
  27652. serializationObject.name = this.name;
  27653. serializationObject.id = this.id;
  27654. // Emitter
  27655. if (this.emitter.position) {
  27656. serializationObject.emitterId = this.emitter.id;
  27657. }
  27658. else {
  27659. serializationObject.emitter = this.emitter.asArray();
  27660. }
  27661. serializationObject.capacity = this.getCapacity();
  27662. if (this.particleTexture) {
  27663. serializationObject.textureName = this.particleTexture.name;
  27664. }
  27665. // Animations
  27666. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27667. // Particle system
  27668. serializationObject.minAngularSpeed = this.minAngularSpeed;
  27669. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  27670. serializationObject.minSize = this.minSize;
  27671. serializationObject.maxSize = this.maxSize;
  27672. serializationObject.minEmitPower = this.minEmitPower;
  27673. serializationObject.maxEmitPower = this.maxEmitPower;
  27674. serializationObject.minLifeTime = this.minLifeTime;
  27675. serializationObject.maxLifeTime = this.maxLifeTime;
  27676. serializationObject.emitRate = this.emitRate;
  27677. serializationObject.minEmitBox = this.minEmitBox.asArray();
  27678. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  27679. serializationObject.gravity = this.gravity.asArray();
  27680. serializationObject.direction1 = this.direction1.asArray();
  27681. serializationObject.direction2 = this.direction2.asArray();
  27682. serializationObject.color1 = this.color1.asArray();
  27683. serializationObject.color2 = this.color2.asArray();
  27684. serializationObject.colorDead = this.colorDead.asArray();
  27685. serializationObject.updateSpeed = this.updateSpeed;
  27686. serializationObject.targetStopDuration = this.targetStopDuration;
  27687. serializationObject.textureMask = this.textureMask.asArray();
  27688. serializationObject.blendMode = this.blendMode;
  27689. return serializationObject;
  27690. };
  27691. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  27692. var name = parsedParticleSystem.name;
  27693. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  27694. if (parsedParticleSystem.id) {
  27695. particleSystem.id = parsedParticleSystem.id;
  27696. }
  27697. // Texture
  27698. if (parsedParticleSystem.textureName) {
  27699. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  27700. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  27701. }
  27702. // Emitter
  27703. if (parsedParticleSystem.emitterId) {
  27704. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  27705. }
  27706. else {
  27707. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  27708. }
  27709. // Animations
  27710. if (parsedParticleSystem.animations) {
  27711. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  27712. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  27713. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27714. }
  27715. }
  27716. if (parsedParticleSystem.autoAnimate) {
  27717. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  27718. }
  27719. // Particle system
  27720. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  27721. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  27722. particleSystem.minSize = parsedParticleSystem.minSize;
  27723. particleSystem.maxSize = parsedParticleSystem.maxSize;
  27724. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  27725. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  27726. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  27727. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  27728. particleSystem.emitRate = parsedParticleSystem.emitRate;
  27729. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  27730. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  27731. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  27732. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  27733. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  27734. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  27735. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  27736. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  27737. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  27738. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  27739. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  27740. particleSystem.blendMode = parsedParticleSystem.blendMode;
  27741. if (!parsedParticleSystem.preventAutoStart) {
  27742. particleSystem.start();
  27743. }
  27744. return particleSystem;
  27745. };
  27746. // Statics
  27747. ParticleSystem.BLENDMODE_ONEONE = 0;
  27748. ParticleSystem.BLENDMODE_STANDARD = 1;
  27749. return ParticleSystem;
  27750. })();
  27751. BABYLON.ParticleSystem = ParticleSystem;
  27752. })(BABYLON || (BABYLON = {}));
  27753. var BABYLON;
  27754. (function (BABYLON) {
  27755. var AnimationRange = (function () {
  27756. function AnimationRange(name, from, to) {
  27757. this.name = name;
  27758. this.from = from;
  27759. this.to = to;
  27760. }
  27761. AnimationRange.prototype.clone = function () {
  27762. return new AnimationRange(this.name, this.from, this.to);
  27763. };
  27764. return AnimationRange;
  27765. })();
  27766. BABYLON.AnimationRange = AnimationRange;
  27767. /**
  27768. * Composed of a frame, and an action function
  27769. */
  27770. var AnimationEvent = (function () {
  27771. function AnimationEvent(frame, action, onlyOnce) {
  27772. this.frame = frame;
  27773. this.action = action;
  27774. this.onlyOnce = onlyOnce;
  27775. this.isDone = false;
  27776. }
  27777. return AnimationEvent;
  27778. })();
  27779. BABYLON.AnimationEvent = AnimationEvent;
  27780. var PathCursor = (function () {
  27781. function PathCursor(path) {
  27782. this.path = path;
  27783. this._onchange = new Array();
  27784. this.value = 0;
  27785. this.animations = new Array();
  27786. }
  27787. PathCursor.prototype.getPoint = function () {
  27788. var point = this.path.getPointAtLengthPosition(this.value);
  27789. return new BABYLON.Vector3(point.x, 0, point.y);
  27790. };
  27791. PathCursor.prototype.moveAhead = function (step) {
  27792. if (step === void 0) { step = 0.002; }
  27793. this.move(step);
  27794. return this;
  27795. };
  27796. PathCursor.prototype.moveBack = function (step) {
  27797. if (step === void 0) { step = 0.002; }
  27798. this.move(-step);
  27799. return this;
  27800. };
  27801. PathCursor.prototype.move = function (step) {
  27802. if (Math.abs(step) > 1) {
  27803. throw "step size should be less than 1.";
  27804. }
  27805. this.value += step;
  27806. this.ensureLimits();
  27807. this.raiseOnChange();
  27808. return this;
  27809. };
  27810. PathCursor.prototype.ensureLimits = function () {
  27811. while (this.value > 1) {
  27812. this.value -= 1;
  27813. }
  27814. while (this.value < 0) {
  27815. this.value += 1;
  27816. }
  27817. return this;
  27818. };
  27819. // used by animation engine
  27820. PathCursor.prototype.markAsDirty = function (propertyName) {
  27821. this.ensureLimits();
  27822. this.raiseOnChange();
  27823. return this;
  27824. };
  27825. PathCursor.prototype.raiseOnChange = function () {
  27826. var _this = this;
  27827. this._onchange.forEach(function (f) { return f(_this); });
  27828. return this;
  27829. };
  27830. PathCursor.prototype.onchange = function (f) {
  27831. this._onchange.push(f);
  27832. return this;
  27833. };
  27834. return PathCursor;
  27835. })();
  27836. BABYLON.PathCursor = PathCursor;
  27837. var Animation = (function () {
  27838. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  27839. this.name = name;
  27840. this.targetProperty = targetProperty;
  27841. this.framePerSecond = framePerSecond;
  27842. this.dataType = dataType;
  27843. this.loopMode = loopMode;
  27844. this.enableBlending = enableBlending;
  27845. this._offsetsCache = {};
  27846. this._highLimitsCache = {};
  27847. this._stopped = false;
  27848. this._blendingFactor = 0;
  27849. // The set of event that will be linked to this animation
  27850. this._events = new Array();
  27851. this.allowMatricesInterpolation = false;
  27852. this.blendingSpeed = 0.01;
  27853. this._ranges = {};
  27854. this.targetPropertyPath = targetProperty.split(".");
  27855. this.dataType = dataType;
  27856. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  27857. }
  27858. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  27859. var dataType = undefined;
  27860. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  27861. dataType = Animation.ANIMATIONTYPE_FLOAT;
  27862. }
  27863. else if (from instanceof BABYLON.Quaternion) {
  27864. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  27865. }
  27866. else if (from instanceof BABYLON.Vector3) {
  27867. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  27868. }
  27869. else if (from instanceof BABYLON.Vector2) {
  27870. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  27871. }
  27872. else if (from instanceof BABYLON.Color3) {
  27873. dataType = Animation.ANIMATIONTYPE_COLOR3;
  27874. }
  27875. else if (from instanceof BABYLON.Size) {
  27876. dataType = Animation.ANIMATIONTYPE_SIZE;
  27877. }
  27878. if (dataType == undefined) {
  27879. return null;
  27880. }
  27881. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  27882. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  27883. animation.setKeys(keys);
  27884. if (easingFunction !== undefined) {
  27885. animation.setEasingFunction(easingFunction);
  27886. }
  27887. return animation;
  27888. };
  27889. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27890. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27891. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27892. };
  27893. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27894. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27895. node.animations.push(animation);
  27896. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27897. };
  27898. // Methods
  27899. /**
  27900. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27901. */
  27902. Animation.prototype.toString = function (fullDetails) {
  27903. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  27904. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  27905. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  27906. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  27907. if (fullDetails) {
  27908. ret += ", Ranges: {";
  27909. var first = true;
  27910. for (var name in this._ranges) {
  27911. if (first) {
  27912. ret += ", ";
  27913. first = false;
  27914. }
  27915. ret += name;
  27916. }
  27917. ret += "}";
  27918. }
  27919. return ret;
  27920. };
  27921. /**
  27922. * Add an event to this animation.
  27923. */
  27924. Animation.prototype.addEvent = function (event) {
  27925. this._events.push(event);
  27926. };
  27927. /**
  27928. * Remove all events found at the given frame
  27929. * @param frame
  27930. */
  27931. Animation.prototype.removeEvents = function (frame) {
  27932. for (var index = 0; index < this._events.length; index++) {
  27933. if (this._events[index].frame === frame) {
  27934. this._events.splice(index, 1);
  27935. index--;
  27936. }
  27937. }
  27938. };
  27939. Animation.prototype.createRange = function (name, from, to) {
  27940. // check name not already in use; could happen for bones after serialized
  27941. if (!this._ranges[name]) {
  27942. this._ranges[name] = new AnimationRange(name, from, to);
  27943. }
  27944. };
  27945. Animation.prototype.deleteRange = function (name, deleteFrames) {
  27946. if (deleteFrames === void 0) { deleteFrames = true; }
  27947. if (this._ranges[name]) {
  27948. if (deleteFrames) {
  27949. var from = this._ranges[name].from;
  27950. var to = this._ranges[name].to;
  27951. // this loop MUST go high to low for multiple splices to work
  27952. for (var key = this._keys.length - 1; key >= 0; key--) {
  27953. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  27954. this._keys.splice(key, 1);
  27955. }
  27956. }
  27957. }
  27958. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  27959. }
  27960. };
  27961. Animation.prototype.getRange = function (name) {
  27962. return this._ranges[name];
  27963. };
  27964. Animation.prototype.reset = function () {
  27965. this._offsetsCache = {};
  27966. this._highLimitsCache = {};
  27967. this.currentFrame = 0;
  27968. this._blendingFactor = 0;
  27969. this._originalBlendValue = null;
  27970. };
  27971. Animation.prototype.isStopped = function () {
  27972. return this._stopped;
  27973. };
  27974. Animation.prototype.getKeys = function () {
  27975. return this._keys;
  27976. };
  27977. Animation.prototype.getHighestFrame = function () {
  27978. var ret = 0;
  27979. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  27980. if (ret < this._keys[key].frame) {
  27981. ret = this._keys[key].frame;
  27982. }
  27983. }
  27984. return ret;
  27985. };
  27986. Animation.prototype.getEasingFunction = function () {
  27987. return this._easingFunction;
  27988. };
  27989. Animation.prototype.setEasingFunction = function (easingFunction) {
  27990. this._easingFunction = easingFunction;
  27991. };
  27992. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  27993. return startValue + (endValue - startValue) * gradient;
  27994. };
  27995. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  27996. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  27997. };
  27998. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  27999. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28000. };
  28001. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28002. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28003. };
  28004. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28005. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28006. };
  28007. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28008. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28009. };
  28010. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28011. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28012. };
  28013. Animation.prototype.clone = function () {
  28014. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28015. if (this._keys) {
  28016. clone.setKeys(this._keys);
  28017. }
  28018. if (this._ranges) {
  28019. clone._ranges = {};
  28020. for (var name in this._ranges) {
  28021. clone._ranges[name] = this._ranges[name].clone();
  28022. }
  28023. }
  28024. return clone;
  28025. };
  28026. Animation.prototype.setKeys = function (values) {
  28027. this._keys = values.slice(0);
  28028. this._offsetsCache = {};
  28029. this._highLimitsCache = {};
  28030. };
  28031. Animation.prototype._getKeyValue = function (value) {
  28032. if (typeof value === "function") {
  28033. return value();
  28034. }
  28035. return value;
  28036. };
  28037. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28038. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28039. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28040. }
  28041. this.currentFrame = currentFrame;
  28042. // Try to get a hash to find the right key
  28043. 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));
  28044. if (this._keys[startKey].frame >= currentFrame) {
  28045. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  28046. startKey--;
  28047. }
  28048. }
  28049. for (var key = startKey; key < this._keys.length; key++) {
  28050. if (this._keys[key + 1].frame >= currentFrame) {
  28051. var startValue = this._getKeyValue(this._keys[key].value);
  28052. var endValue = this._getKeyValue(this._keys[key + 1].value);
  28053. // gradient : percent of currentFrame between the frame inf and the frame sup
  28054. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  28055. // check for easingFunction and correction of gradient
  28056. if (this._easingFunction != null) {
  28057. gradient = this._easingFunction.ease(gradient);
  28058. }
  28059. switch (this.dataType) {
  28060. // Float
  28061. case Animation.ANIMATIONTYPE_FLOAT:
  28062. switch (loopMode) {
  28063. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28064. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28065. return this.floatInterpolateFunction(startValue, endValue, gradient);
  28066. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28067. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  28068. }
  28069. break;
  28070. // Quaternion
  28071. case Animation.ANIMATIONTYPE_QUATERNION:
  28072. var quaternion = null;
  28073. switch (loopMode) {
  28074. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28075. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28076. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28077. break;
  28078. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28079. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28080. break;
  28081. }
  28082. return quaternion;
  28083. // Vector3
  28084. case Animation.ANIMATIONTYPE_VECTOR3:
  28085. switch (loopMode) {
  28086. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28087. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28088. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  28089. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28090. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28091. }
  28092. // Vector2
  28093. case Animation.ANIMATIONTYPE_VECTOR2:
  28094. switch (loopMode) {
  28095. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28096. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28097. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  28098. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28099. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28100. }
  28101. // Size
  28102. case Animation.ANIMATIONTYPE_SIZE:
  28103. switch (loopMode) {
  28104. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28105. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28106. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28107. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28108. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28109. }
  28110. // Color3
  28111. case Animation.ANIMATIONTYPE_COLOR3:
  28112. switch (loopMode) {
  28113. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28114. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28115. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28116. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28117. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28118. }
  28119. // Matrix
  28120. case Animation.ANIMATIONTYPE_MATRIX:
  28121. switch (loopMode) {
  28122. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28123. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28124. if (this.allowMatricesInterpolation) {
  28125. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28126. }
  28127. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28128. return startValue;
  28129. }
  28130. default:
  28131. break;
  28132. }
  28133. break;
  28134. }
  28135. }
  28136. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28137. };
  28138. Animation.prototype.setValue = function (currentValue, blend) {
  28139. if (blend === void 0) { blend = false; }
  28140. // Set value
  28141. var path;
  28142. var destination;
  28143. if (this.targetPropertyPath.length > 1) {
  28144. var property = this._target[this.targetPropertyPath[0]];
  28145. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28146. property = property[this.targetPropertyPath[index]];
  28147. }
  28148. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28149. destination = property;
  28150. }
  28151. else {
  28152. path = this.targetPropertyPath[0];
  28153. destination = this._target;
  28154. }
  28155. // Blending
  28156. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28157. if (!this._originalBlendValue) {
  28158. if (destination[path].clone) {
  28159. this._originalBlendValue = destination[path].clone();
  28160. }
  28161. else {
  28162. this._originalBlendValue = destination[path];
  28163. }
  28164. }
  28165. if (this._originalBlendValue.prototype) {
  28166. if (this._originalBlendValue.prototype.Lerp) {
  28167. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28168. }
  28169. else {
  28170. destination[path] = currentValue;
  28171. }
  28172. }
  28173. else if (this._originalBlendValue.m) {
  28174. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28175. }
  28176. else {
  28177. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28178. }
  28179. this._blendingFactor += this.blendingSpeed;
  28180. }
  28181. else {
  28182. destination[path] = currentValue;
  28183. }
  28184. if (this._target.markAsDirty) {
  28185. this._target.markAsDirty(this.targetProperty);
  28186. }
  28187. };
  28188. Animation.prototype.goToFrame = function (frame) {
  28189. if (frame < this._keys[0].frame) {
  28190. frame = this._keys[0].frame;
  28191. }
  28192. else if (frame > this._keys[this._keys.length - 1].frame) {
  28193. frame = this._keys[this._keys.length - 1].frame;
  28194. }
  28195. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28196. this.setValue(currentValue);
  28197. };
  28198. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28199. if (blend === void 0) { blend = false; }
  28200. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28201. this._stopped = true;
  28202. return false;
  28203. }
  28204. var returnValue = true;
  28205. // Adding a start key at frame 0 if missing
  28206. if (this._keys[0].frame !== 0) {
  28207. var newKey = { frame: 0, value: this._keys[0].value };
  28208. this._keys.splice(0, 0, newKey);
  28209. }
  28210. // Check limits
  28211. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28212. from = this._keys[0].frame;
  28213. }
  28214. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28215. to = this._keys[this._keys.length - 1].frame;
  28216. }
  28217. // Compute ratio
  28218. var range = to - from;
  28219. var offsetValue;
  28220. // ratio represents the frame delta between from and to
  28221. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28222. var highLimitValue = 0;
  28223. if (ratio > range && !loop) {
  28224. returnValue = false;
  28225. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28226. }
  28227. else {
  28228. // Get max value if required
  28229. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28230. var keyOffset = to.toString() + from.toString();
  28231. if (!this._offsetsCache[keyOffset]) {
  28232. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28233. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28234. switch (this.dataType) {
  28235. // Float
  28236. case Animation.ANIMATIONTYPE_FLOAT:
  28237. this._offsetsCache[keyOffset] = toValue - fromValue;
  28238. break;
  28239. // Quaternion
  28240. case Animation.ANIMATIONTYPE_QUATERNION:
  28241. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28242. break;
  28243. // Vector3
  28244. case Animation.ANIMATIONTYPE_VECTOR3:
  28245. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28246. // Vector2
  28247. case Animation.ANIMATIONTYPE_VECTOR2:
  28248. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28249. // Size
  28250. case Animation.ANIMATIONTYPE_SIZE:
  28251. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28252. // Color3
  28253. case Animation.ANIMATIONTYPE_COLOR3:
  28254. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28255. default:
  28256. break;
  28257. }
  28258. this._highLimitsCache[keyOffset] = toValue;
  28259. }
  28260. highLimitValue = this._highLimitsCache[keyOffset];
  28261. offsetValue = this._offsetsCache[keyOffset];
  28262. }
  28263. }
  28264. if (offsetValue === undefined) {
  28265. switch (this.dataType) {
  28266. // Float
  28267. case Animation.ANIMATIONTYPE_FLOAT:
  28268. offsetValue = 0;
  28269. break;
  28270. // Quaternion
  28271. case Animation.ANIMATIONTYPE_QUATERNION:
  28272. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28273. break;
  28274. // Vector3
  28275. case Animation.ANIMATIONTYPE_VECTOR3:
  28276. offsetValue = BABYLON.Vector3.Zero();
  28277. break;
  28278. // Vector2
  28279. case Animation.ANIMATIONTYPE_VECTOR2:
  28280. offsetValue = BABYLON.Vector2.Zero();
  28281. break;
  28282. // Size
  28283. case Animation.ANIMATIONTYPE_SIZE:
  28284. offsetValue = BABYLON.Size.Zero();
  28285. break;
  28286. // Color3
  28287. case Animation.ANIMATIONTYPE_COLOR3:
  28288. offsetValue = BABYLON.Color3.Black();
  28289. }
  28290. }
  28291. // Compute value
  28292. var repeatCount = (ratio / range) >> 0;
  28293. var currentFrame = returnValue ? from + ratio % range : to;
  28294. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28295. // Set value
  28296. this.setValue(currentValue);
  28297. // Check events
  28298. for (var index = 0; index < this._events.length; index++) {
  28299. if (currentFrame >= this._events[index].frame) {
  28300. var event = this._events[index];
  28301. if (!event.isDone) {
  28302. // If event should be done only once, remove it.
  28303. if (event.onlyOnce) {
  28304. this._events.splice(index, 1);
  28305. index--;
  28306. }
  28307. event.isDone = true;
  28308. event.action();
  28309. } // Don't do anything if the event has already be done.
  28310. }
  28311. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28312. // reset event, the animation is looping
  28313. this._events[index].isDone = false;
  28314. }
  28315. }
  28316. if (!returnValue) {
  28317. this._stopped = true;
  28318. }
  28319. return returnValue;
  28320. };
  28321. Animation.prototype.serialize = function () {
  28322. var serializationObject = {};
  28323. serializationObject.name = this.name;
  28324. serializationObject.property = this.targetProperty;
  28325. serializationObject.framePerSecond = this.framePerSecond;
  28326. serializationObject.dataType = this.dataType;
  28327. serializationObject.loopBehavior = this.loopMode;
  28328. var dataType = this.dataType;
  28329. serializationObject.keys = [];
  28330. var keys = this.getKeys();
  28331. for (var index = 0; index < keys.length; index++) {
  28332. var animationKey = keys[index];
  28333. var key = {};
  28334. key.frame = animationKey.frame;
  28335. switch (dataType) {
  28336. case Animation.ANIMATIONTYPE_FLOAT:
  28337. key.values = [animationKey.value];
  28338. break;
  28339. case Animation.ANIMATIONTYPE_QUATERNION:
  28340. case Animation.ANIMATIONTYPE_MATRIX:
  28341. case Animation.ANIMATIONTYPE_VECTOR3:
  28342. case Animation.ANIMATIONTYPE_COLOR3:
  28343. key.values = animationKey.value.asArray();
  28344. break;
  28345. }
  28346. serializationObject.keys.push(key);
  28347. }
  28348. serializationObject.ranges = [];
  28349. for (var name in this._ranges) {
  28350. var range = {};
  28351. range.name = name;
  28352. range.from = this._ranges[name].from;
  28353. range.to = this._ranges[name].to;
  28354. serializationObject.ranges.push(range);
  28355. }
  28356. return serializationObject;
  28357. };
  28358. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28359. get: function () {
  28360. return Animation._ANIMATIONTYPE_FLOAT;
  28361. },
  28362. enumerable: true,
  28363. configurable: true
  28364. });
  28365. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28366. get: function () {
  28367. return Animation._ANIMATIONTYPE_VECTOR3;
  28368. },
  28369. enumerable: true,
  28370. configurable: true
  28371. });
  28372. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  28373. get: function () {
  28374. return Animation._ANIMATIONTYPE_VECTOR2;
  28375. },
  28376. enumerable: true,
  28377. configurable: true
  28378. });
  28379. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  28380. get: function () {
  28381. return Animation._ANIMATIONTYPE_SIZE;
  28382. },
  28383. enumerable: true,
  28384. configurable: true
  28385. });
  28386. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  28387. get: function () {
  28388. return Animation._ANIMATIONTYPE_QUATERNION;
  28389. },
  28390. enumerable: true,
  28391. configurable: true
  28392. });
  28393. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  28394. get: function () {
  28395. return Animation._ANIMATIONTYPE_MATRIX;
  28396. },
  28397. enumerable: true,
  28398. configurable: true
  28399. });
  28400. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  28401. get: function () {
  28402. return Animation._ANIMATIONTYPE_COLOR3;
  28403. },
  28404. enumerable: true,
  28405. configurable: true
  28406. });
  28407. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28408. get: function () {
  28409. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28410. },
  28411. enumerable: true,
  28412. configurable: true
  28413. });
  28414. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28415. get: function () {
  28416. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28417. },
  28418. enumerable: true,
  28419. configurable: true
  28420. });
  28421. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28422. get: function () {
  28423. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28424. },
  28425. enumerable: true,
  28426. configurable: true
  28427. });
  28428. Animation.Parse = function (parsedAnimation) {
  28429. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28430. var dataType = parsedAnimation.dataType;
  28431. var keys = [];
  28432. var data;
  28433. var index;
  28434. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28435. var key = parsedAnimation.keys[index];
  28436. switch (dataType) {
  28437. case Animation.ANIMATIONTYPE_FLOAT:
  28438. data = key.values[0];
  28439. break;
  28440. case Animation.ANIMATIONTYPE_QUATERNION:
  28441. data = BABYLON.Quaternion.FromArray(key.values);
  28442. break;
  28443. case Animation.ANIMATIONTYPE_MATRIX:
  28444. data = BABYLON.Matrix.FromArray(key.values);
  28445. break;
  28446. case Animation.ANIMATIONTYPE_COLOR3:
  28447. data = BABYLON.Color3.FromArray(key.values);
  28448. break;
  28449. case Animation.ANIMATIONTYPE_VECTOR3:
  28450. default:
  28451. data = BABYLON.Vector3.FromArray(key.values);
  28452. break;
  28453. }
  28454. keys.push({
  28455. frame: key.frame,
  28456. value: data
  28457. });
  28458. }
  28459. animation.setKeys(keys);
  28460. if (parsedAnimation.ranges) {
  28461. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  28462. data = parsedAnimation.ranges[index];
  28463. animation.createRange(data.name, data.from, data.to);
  28464. }
  28465. }
  28466. return animation;
  28467. };
  28468. Animation.AppendSerializedAnimations = function (source, destination) {
  28469. if (source.animations) {
  28470. destination.animations = [];
  28471. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28472. var animation = source.animations[animationIndex];
  28473. destination.animations.push(animation.serialize());
  28474. }
  28475. }
  28476. };
  28477. // Statics
  28478. Animation._ANIMATIONTYPE_FLOAT = 0;
  28479. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  28480. Animation._ANIMATIONTYPE_QUATERNION = 2;
  28481. Animation._ANIMATIONTYPE_MATRIX = 3;
  28482. Animation._ANIMATIONTYPE_COLOR3 = 4;
  28483. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  28484. Animation._ANIMATIONTYPE_SIZE = 6;
  28485. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  28486. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  28487. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  28488. return Animation;
  28489. })();
  28490. BABYLON.Animation = Animation;
  28491. })(BABYLON || (BABYLON = {}));
  28492. var BABYLON;
  28493. (function (BABYLON) {
  28494. var Animatable = (function () {
  28495. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  28496. if (fromFrame === void 0) { fromFrame = 0; }
  28497. if (toFrame === void 0) { toFrame = 100; }
  28498. if (loopAnimation === void 0) { loopAnimation = false; }
  28499. if (speedRatio === void 0) { speedRatio = 1.0; }
  28500. this.target = target;
  28501. this.fromFrame = fromFrame;
  28502. this.toFrame = toFrame;
  28503. this.loopAnimation = loopAnimation;
  28504. this.speedRatio = speedRatio;
  28505. this.onAnimationEnd = onAnimationEnd;
  28506. this._animations = new Array();
  28507. this._paused = false;
  28508. this.animationStarted = false;
  28509. if (animations) {
  28510. this.appendAnimations(target, animations);
  28511. }
  28512. this._scene = scene;
  28513. scene._activeAnimatables.push(this);
  28514. }
  28515. // Methods
  28516. Animatable.prototype.getAnimations = function () {
  28517. return this._animations;
  28518. };
  28519. Animatable.prototype.appendAnimations = function (target, animations) {
  28520. for (var index = 0; index < animations.length; index++) {
  28521. var animation = animations[index];
  28522. animation._target = target;
  28523. this._animations.push(animation);
  28524. }
  28525. };
  28526. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  28527. var animations = this._animations;
  28528. for (var index = 0; index < animations.length; index++) {
  28529. if (animations[index].targetProperty === property) {
  28530. return animations[index];
  28531. }
  28532. }
  28533. return null;
  28534. };
  28535. Animatable.prototype.reset = function () {
  28536. var animations = this._animations;
  28537. for (var index = 0; index < animations.length; index++) {
  28538. animations[index].reset();
  28539. }
  28540. this._localDelayOffset = null;
  28541. this._pausedDelay = null;
  28542. };
  28543. Animatable.prototype.enableBlending = function (blendingSpeed) {
  28544. var animations = this._animations;
  28545. for (var index = 0; index < animations.length; index++) {
  28546. animations[index].enableBlending = true;
  28547. animations[index].blendingSpeed = blendingSpeed;
  28548. }
  28549. };
  28550. Animatable.prototype.disableBlending = function () {
  28551. var animations = this._animations;
  28552. for (var index = 0; index < animations.length; index++) {
  28553. animations[index].enableBlending = false;
  28554. }
  28555. };
  28556. Animatable.prototype.goToFrame = function (frame) {
  28557. var animations = this._animations;
  28558. for (var index = 0; index < animations.length; index++) {
  28559. animations[index].goToFrame(frame);
  28560. }
  28561. };
  28562. Animatable.prototype.pause = function () {
  28563. if (this._paused) {
  28564. return;
  28565. }
  28566. this._paused = true;
  28567. };
  28568. Animatable.prototype.restart = function () {
  28569. this._paused = false;
  28570. };
  28571. Animatable.prototype.stop = function () {
  28572. var index = this._scene._activeAnimatables.indexOf(this);
  28573. if (index > -1) {
  28574. this._scene._activeAnimatables.splice(index, 1);
  28575. var animations = this._animations;
  28576. for (var index = 0; index < animations.length; index++) {
  28577. animations[index].reset();
  28578. }
  28579. if (this.onAnimationEnd) {
  28580. this.onAnimationEnd();
  28581. }
  28582. }
  28583. };
  28584. Animatable.prototype._animate = function (delay) {
  28585. if (this._paused) {
  28586. this.animationStarted = false;
  28587. if (!this._pausedDelay) {
  28588. this._pausedDelay = delay;
  28589. }
  28590. return true;
  28591. }
  28592. if (!this._localDelayOffset) {
  28593. this._localDelayOffset = delay;
  28594. }
  28595. else if (this._pausedDelay) {
  28596. this._localDelayOffset += delay - this._pausedDelay;
  28597. this._pausedDelay = null;
  28598. }
  28599. // Animating
  28600. var running = false;
  28601. var animations = this._animations;
  28602. var index;
  28603. for (index = 0; index < animations.length; index++) {
  28604. var animation = animations[index];
  28605. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  28606. running = running || isRunning;
  28607. }
  28608. this.animationStarted = running;
  28609. if (!running) {
  28610. // Remove from active animatables
  28611. index = this._scene._activeAnimatables.indexOf(this);
  28612. this._scene._activeAnimatables.splice(index, 1);
  28613. }
  28614. if (!running && this.onAnimationEnd) {
  28615. this.onAnimationEnd();
  28616. this.onAnimationEnd = null;
  28617. }
  28618. return running;
  28619. };
  28620. return Animatable;
  28621. })();
  28622. BABYLON.Animatable = Animatable;
  28623. })(BABYLON || (BABYLON = {}));
  28624. var BABYLON;
  28625. (function (BABYLON) {
  28626. var EasingFunction = (function () {
  28627. function EasingFunction() {
  28628. // Properties
  28629. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  28630. }
  28631. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  28632. get: function () {
  28633. return EasingFunction._EASINGMODE_EASEIN;
  28634. },
  28635. enumerable: true,
  28636. configurable: true
  28637. });
  28638. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  28639. get: function () {
  28640. return EasingFunction._EASINGMODE_EASEOUT;
  28641. },
  28642. enumerable: true,
  28643. configurable: true
  28644. });
  28645. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  28646. get: function () {
  28647. return EasingFunction._EASINGMODE_EASEINOUT;
  28648. },
  28649. enumerable: true,
  28650. configurable: true
  28651. });
  28652. EasingFunction.prototype.setEasingMode = function (easingMode) {
  28653. var n = Math.min(Math.max(easingMode, 0), 2);
  28654. this._easingMode = n;
  28655. };
  28656. EasingFunction.prototype.getEasingMode = function () {
  28657. return this._easingMode;
  28658. };
  28659. EasingFunction.prototype.easeInCore = function (gradient) {
  28660. throw new Error('You must implement this method');
  28661. };
  28662. EasingFunction.prototype.ease = function (gradient) {
  28663. switch (this._easingMode) {
  28664. case EasingFunction.EASINGMODE_EASEIN:
  28665. return this.easeInCore(gradient);
  28666. case EasingFunction.EASINGMODE_EASEOUT:
  28667. return (1 - this.easeInCore(1 - gradient));
  28668. }
  28669. if (gradient >= 0.5) {
  28670. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  28671. }
  28672. return (this.easeInCore(gradient * 2) * 0.5);
  28673. };
  28674. //Statics
  28675. EasingFunction._EASINGMODE_EASEIN = 0;
  28676. EasingFunction._EASINGMODE_EASEOUT = 1;
  28677. EasingFunction._EASINGMODE_EASEINOUT = 2;
  28678. return EasingFunction;
  28679. })();
  28680. BABYLON.EasingFunction = EasingFunction;
  28681. var CircleEase = (function (_super) {
  28682. __extends(CircleEase, _super);
  28683. function CircleEase() {
  28684. _super.apply(this, arguments);
  28685. }
  28686. CircleEase.prototype.easeInCore = function (gradient) {
  28687. gradient = Math.max(0, Math.min(1, gradient));
  28688. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  28689. };
  28690. return CircleEase;
  28691. })(EasingFunction);
  28692. BABYLON.CircleEase = CircleEase;
  28693. var BackEase = (function (_super) {
  28694. __extends(BackEase, _super);
  28695. function BackEase(amplitude) {
  28696. if (amplitude === void 0) { amplitude = 1; }
  28697. _super.call(this);
  28698. this.amplitude = amplitude;
  28699. }
  28700. BackEase.prototype.easeInCore = function (gradient) {
  28701. var num = Math.max(0, this.amplitude);
  28702. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  28703. };
  28704. return BackEase;
  28705. })(EasingFunction);
  28706. BABYLON.BackEase = BackEase;
  28707. var BounceEase = (function (_super) {
  28708. __extends(BounceEase, _super);
  28709. function BounceEase(bounces, bounciness) {
  28710. if (bounces === void 0) { bounces = 3; }
  28711. if (bounciness === void 0) { bounciness = 2; }
  28712. _super.call(this);
  28713. this.bounces = bounces;
  28714. this.bounciness = bounciness;
  28715. }
  28716. BounceEase.prototype.easeInCore = function (gradient) {
  28717. var y = Math.max(0.0, this.bounces);
  28718. var bounciness = this.bounciness;
  28719. if (bounciness <= 1.0) {
  28720. bounciness = 1.001;
  28721. }
  28722. var num9 = Math.pow(bounciness, y);
  28723. var num5 = 1.0 - bounciness;
  28724. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  28725. var num15 = gradient * num4;
  28726. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  28727. var num3 = Math.floor(num65);
  28728. var num13 = num3 + 1.0;
  28729. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  28730. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  28731. var num7 = (num8 + num12) * 0.5;
  28732. var num6 = gradient - num7;
  28733. var num2 = num7 - num8;
  28734. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  28735. };
  28736. return BounceEase;
  28737. })(EasingFunction);
  28738. BABYLON.BounceEase = BounceEase;
  28739. var CubicEase = (function (_super) {
  28740. __extends(CubicEase, _super);
  28741. function CubicEase() {
  28742. _super.apply(this, arguments);
  28743. }
  28744. CubicEase.prototype.easeInCore = function (gradient) {
  28745. return (gradient * gradient * gradient);
  28746. };
  28747. return CubicEase;
  28748. })(EasingFunction);
  28749. BABYLON.CubicEase = CubicEase;
  28750. var ElasticEase = (function (_super) {
  28751. __extends(ElasticEase, _super);
  28752. function ElasticEase(oscillations, springiness) {
  28753. if (oscillations === void 0) { oscillations = 3; }
  28754. if (springiness === void 0) { springiness = 3; }
  28755. _super.call(this);
  28756. this.oscillations = oscillations;
  28757. this.springiness = springiness;
  28758. }
  28759. ElasticEase.prototype.easeInCore = function (gradient) {
  28760. var num2;
  28761. var num3 = Math.max(0.0, this.oscillations);
  28762. var num = Math.max(0.0, this.springiness);
  28763. if (num == 0) {
  28764. num2 = gradient;
  28765. }
  28766. else {
  28767. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  28768. }
  28769. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  28770. };
  28771. return ElasticEase;
  28772. })(EasingFunction);
  28773. BABYLON.ElasticEase = ElasticEase;
  28774. var ExponentialEase = (function (_super) {
  28775. __extends(ExponentialEase, _super);
  28776. function ExponentialEase(exponent) {
  28777. if (exponent === void 0) { exponent = 2; }
  28778. _super.call(this);
  28779. this.exponent = exponent;
  28780. }
  28781. ExponentialEase.prototype.easeInCore = function (gradient) {
  28782. if (this.exponent <= 0) {
  28783. return gradient;
  28784. }
  28785. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  28786. };
  28787. return ExponentialEase;
  28788. })(EasingFunction);
  28789. BABYLON.ExponentialEase = ExponentialEase;
  28790. var PowerEase = (function (_super) {
  28791. __extends(PowerEase, _super);
  28792. function PowerEase(power) {
  28793. if (power === void 0) { power = 2; }
  28794. _super.call(this);
  28795. this.power = power;
  28796. }
  28797. PowerEase.prototype.easeInCore = function (gradient) {
  28798. var y = Math.max(0.0, this.power);
  28799. return Math.pow(gradient, y);
  28800. };
  28801. return PowerEase;
  28802. })(EasingFunction);
  28803. BABYLON.PowerEase = PowerEase;
  28804. var QuadraticEase = (function (_super) {
  28805. __extends(QuadraticEase, _super);
  28806. function QuadraticEase() {
  28807. _super.apply(this, arguments);
  28808. }
  28809. QuadraticEase.prototype.easeInCore = function (gradient) {
  28810. return (gradient * gradient);
  28811. };
  28812. return QuadraticEase;
  28813. })(EasingFunction);
  28814. BABYLON.QuadraticEase = QuadraticEase;
  28815. var QuarticEase = (function (_super) {
  28816. __extends(QuarticEase, _super);
  28817. function QuarticEase() {
  28818. _super.apply(this, arguments);
  28819. }
  28820. QuarticEase.prototype.easeInCore = function (gradient) {
  28821. return (gradient * gradient * gradient * gradient);
  28822. };
  28823. return QuarticEase;
  28824. })(EasingFunction);
  28825. BABYLON.QuarticEase = QuarticEase;
  28826. var QuinticEase = (function (_super) {
  28827. __extends(QuinticEase, _super);
  28828. function QuinticEase() {
  28829. _super.apply(this, arguments);
  28830. }
  28831. QuinticEase.prototype.easeInCore = function (gradient) {
  28832. return (gradient * gradient * gradient * gradient * gradient);
  28833. };
  28834. return QuinticEase;
  28835. })(EasingFunction);
  28836. BABYLON.QuinticEase = QuinticEase;
  28837. var SineEase = (function (_super) {
  28838. __extends(SineEase, _super);
  28839. function SineEase() {
  28840. _super.apply(this, arguments);
  28841. }
  28842. SineEase.prototype.easeInCore = function (gradient) {
  28843. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  28844. };
  28845. return SineEase;
  28846. })(EasingFunction);
  28847. BABYLON.SineEase = SineEase;
  28848. var BezierCurveEase = (function (_super) {
  28849. __extends(BezierCurveEase, _super);
  28850. function BezierCurveEase(x1, y1, x2, y2) {
  28851. if (x1 === void 0) { x1 = 0; }
  28852. if (y1 === void 0) { y1 = 0; }
  28853. if (x2 === void 0) { x2 = 1; }
  28854. if (y2 === void 0) { y2 = 1; }
  28855. _super.call(this);
  28856. this.x1 = x1;
  28857. this.y1 = y1;
  28858. this.x2 = x2;
  28859. this.y2 = y2;
  28860. }
  28861. BezierCurveEase.prototype.easeInCore = function (gradient) {
  28862. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  28863. };
  28864. return BezierCurveEase;
  28865. })(EasingFunction);
  28866. BABYLON.BezierCurveEase = BezierCurveEase;
  28867. })(BABYLON || (BABYLON = {}));
  28868. var BABYLON;
  28869. (function (BABYLON) {
  28870. var Bone = (function (_super) {
  28871. __extends(Bone, _super);
  28872. function Bone(name, skeleton, parentBone, matrix, restPose) {
  28873. _super.call(this, name, skeleton.getScene());
  28874. this.name = name;
  28875. this.children = new Array();
  28876. this.animations = new Array();
  28877. this._worldTransform = new BABYLON.Matrix();
  28878. this._absoluteTransform = new BABYLON.Matrix();
  28879. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  28880. this._skeleton = skeleton;
  28881. this._matrix = matrix;
  28882. this._baseMatrix = matrix;
  28883. this._restPose = restPose ? restPose : matrix.clone();
  28884. skeleton.bones.push(this);
  28885. if (parentBone) {
  28886. this._parent = parentBone;
  28887. parentBone.children.push(this);
  28888. }
  28889. else {
  28890. this._parent = null;
  28891. }
  28892. this._updateDifferenceMatrix();
  28893. }
  28894. // Members
  28895. Bone.prototype.getParent = function () {
  28896. return this._parent;
  28897. };
  28898. Bone.prototype.getLocalMatrix = function () {
  28899. return this._matrix;
  28900. };
  28901. Bone.prototype.getBaseMatrix = function () {
  28902. return this._baseMatrix;
  28903. };
  28904. Bone.prototype.getRestPose = function () {
  28905. return this._restPose;
  28906. };
  28907. Bone.prototype.returnToRest = function () {
  28908. this.updateMatrix(this._restPose.clone());
  28909. };
  28910. Bone.prototype.getWorldMatrix = function () {
  28911. return this._worldTransform;
  28912. };
  28913. Bone.prototype.getInvertedAbsoluteTransform = function () {
  28914. return this._invertedAbsoluteTransform;
  28915. };
  28916. Bone.prototype.getAbsoluteTransform = function () {
  28917. return this._absoluteTransform;
  28918. };
  28919. // Methods
  28920. Bone.prototype.updateMatrix = function (matrix) {
  28921. this._baseMatrix = matrix.clone();
  28922. this._matrix = matrix.clone();
  28923. this._skeleton._markAsDirty();
  28924. this._updateDifferenceMatrix();
  28925. };
  28926. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  28927. if (!rootMatrix) {
  28928. rootMatrix = this._baseMatrix;
  28929. }
  28930. if (this._parent) {
  28931. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  28932. }
  28933. else {
  28934. this._absoluteTransform.copyFrom(rootMatrix);
  28935. }
  28936. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  28937. for (var index = 0; index < this.children.length; index++) {
  28938. this.children[index]._updateDifferenceMatrix();
  28939. }
  28940. };
  28941. Bone.prototype.markAsDirty = function () {
  28942. this._currentRenderId++;
  28943. this._skeleton._markAsDirty();
  28944. };
  28945. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  28946. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28947. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  28948. // all animation may be coming from a library skeleton, so may need to create animation
  28949. if (this.animations.length === 0) {
  28950. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  28951. this.animations[0].setKeys([]);
  28952. }
  28953. // get animation info / verify there is such a range from the source bone
  28954. var sourceRange = source.animations[0].getRange(rangeName);
  28955. if (!sourceRange) {
  28956. return false;
  28957. }
  28958. var from = sourceRange.from;
  28959. var to = sourceRange.to;
  28960. var sourceKeys = source.animations[0].getKeys();
  28961. // rescaling prep
  28962. var sourceBoneLength = source.length;
  28963. var sourceParent = source.getParent();
  28964. var parent = this.getParent();
  28965. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  28966. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  28967. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  28968. var destKeys = this.animations[0].getKeys();
  28969. // loop vars declaration
  28970. var orig;
  28971. var origTranslation;
  28972. var mat;
  28973. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  28974. orig = sourceKeys[key];
  28975. if (orig.frame >= from && orig.frame <= to) {
  28976. if (rescaleAsRequired) {
  28977. mat = orig.value.clone();
  28978. // scale based on parent ratio, when bone has parent
  28979. if (parentScalingReqd) {
  28980. origTranslation = mat.getTranslation();
  28981. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  28982. }
  28983. else if (dimensionsScalingReqd) {
  28984. origTranslation = mat.getTranslation();
  28985. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  28986. }
  28987. else {
  28988. mat = orig.value;
  28989. }
  28990. }
  28991. else {
  28992. mat = orig.value;
  28993. }
  28994. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  28995. }
  28996. }
  28997. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  28998. return true;
  28999. };
  29000. return Bone;
  29001. })(BABYLON.Node);
  29002. BABYLON.Bone = Bone;
  29003. })(BABYLON || (BABYLON = {}));
  29004. var BABYLON;
  29005. (function (BABYLON) {
  29006. var Skeleton = (function () {
  29007. function Skeleton(name, id, scene) {
  29008. this.name = name;
  29009. this.id = id;
  29010. this.bones = new Array();
  29011. this.needInitialSkinMatrix = false;
  29012. this._isDirty = true;
  29013. this._meshesWithPoseMatrix = new Array();
  29014. this._identity = BABYLON.Matrix.Identity();
  29015. this._ranges = {};
  29016. this.bones = [];
  29017. this._scene = scene;
  29018. scene.skeletons.push(this);
  29019. //make sure it will recalculate the matrix next time prepare is called.
  29020. this._isDirty = true;
  29021. }
  29022. // Members
  29023. Skeleton.prototype.getTransformMatrices = function (mesh) {
  29024. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  29025. return mesh._bonesTransformMatrices;
  29026. }
  29027. return this._transformMatrices;
  29028. };
  29029. Skeleton.prototype.getScene = function () {
  29030. return this._scene;
  29031. };
  29032. // Methods
  29033. /**
  29034. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29035. */
  29036. Skeleton.prototype.toString = function (fullDetails) {
  29037. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  29038. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29039. if (fullDetails) {
  29040. ret += ", Ranges: {";
  29041. var first = true;
  29042. for (var name_1 in this._ranges) {
  29043. if (first) {
  29044. ret += ", ";
  29045. first = false;
  29046. }
  29047. ret += name_1;
  29048. }
  29049. ret += "}";
  29050. }
  29051. return ret;
  29052. };
  29053. /**
  29054. * Get bone's index searching by name
  29055. * @param {string} name is bone's name to search for
  29056. * @return {number} Indice of the bone. Returns -1 if not found
  29057. */
  29058. Skeleton.prototype.getBoneIndexByName = function (name) {
  29059. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  29060. if (this.bones[boneIndex].name === name) {
  29061. return boneIndex;
  29062. }
  29063. }
  29064. return -1;
  29065. };
  29066. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  29067. // check name not already in use
  29068. if (!this._ranges[name]) {
  29069. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  29070. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29071. if (this.bones[i].animations[0]) {
  29072. this.bones[i].animations[0].createRange(name, from, to);
  29073. }
  29074. }
  29075. }
  29076. };
  29077. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  29078. if (deleteFrames === void 0) { deleteFrames = true; }
  29079. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29080. if (this.bones[i].animations[0]) {
  29081. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  29082. }
  29083. }
  29084. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29085. };
  29086. Skeleton.prototype.getAnimationRange = function (name) {
  29087. return this._ranges[name];
  29088. };
  29089. /**
  29090. * Returns as an Array, all AnimationRanges defined on this skeleton
  29091. */
  29092. Skeleton.prototype.getAnimationRanges = function () {
  29093. var animationRanges = [];
  29094. var name;
  29095. var i = 0;
  29096. for (name in this._ranges) {
  29097. animationRanges[i] = this._ranges[name];
  29098. i++;
  29099. }
  29100. return animationRanges;
  29101. };
  29102. /**
  29103. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  29104. */
  29105. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  29106. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29107. if (this._ranges[name] || !source.getAnimationRange(name)) {
  29108. return false;
  29109. }
  29110. var ret = true;
  29111. var frameOffset = this._getHighestAnimationFrame() + 1;
  29112. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  29113. var boneDict = {};
  29114. var sourceBones = source.bones;
  29115. var nBones;
  29116. var i;
  29117. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  29118. boneDict[sourceBones[i].name] = sourceBones[i];
  29119. }
  29120. if (this.bones.length !== sourceBones.length) {
  29121. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  29122. ret = false;
  29123. }
  29124. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  29125. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  29126. var boneName = this.bones[i].name;
  29127. var sourceBone = boneDict[boneName];
  29128. if (sourceBone) {
  29129. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  29130. }
  29131. else {
  29132. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  29133. ret = false;
  29134. }
  29135. }
  29136. // do not call createAnimationRange(), since it also is done to bones, which was already done
  29137. var range = source.getAnimationRange(name);
  29138. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  29139. return ret;
  29140. };
  29141. Skeleton.prototype.returnToRest = function () {
  29142. for (var index = 0; index < this.bones.length; index++) {
  29143. this.bones[index].returnToRest();
  29144. }
  29145. };
  29146. Skeleton.prototype._getHighestAnimationFrame = function () {
  29147. var ret = 0;
  29148. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29149. if (this.bones[i].animations[0]) {
  29150. var highest = this.bones[i].animations[0].getHighestFrame();
  29151. if (ret < highest) {
  29152. ret = highest;
  29153. }
  29154. }
  29155. }
  29156. return ret;
  29157. };
  29158. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  29159. var range = this.getAnimationRange(name);
  29160. if (!range) {
  29161. return null;
  29162. }
  29163. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  29164. };
  29165. Skeleton.prototype._markAsDirty = function () {
  29166. this._isDirty = true;
  29167. };
  29168. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  29169. this._meshesWithPoseMatrix.push(mesh);
  29170. };
  29171. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  29172. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  29173. if (index > -1) {
  29174. this._meshesWithPoseMatrix.splice(index, 1);
  29175. }
  29176. };
  29177. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  29178. for (var index = 0; index < this.bones.length; index++) {
  29179. var bone = this.bones[index];
  29180. var parentBone = bone.getParent();
  29181. if (parentBone) {
  29182. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  29183. }
  29184. else {
  29185. if (initialSkinMatrix) {
  29186. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  29187. }
  29188. else {
  29189. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  29190. }
  29191. }
  29192. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  29193. }
  29194. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  29195. };
  29196. Skeleton.prototype.prepare = function () {
  29197. if (!this._isDirty) {
  29198. return;
  29199. }
  29200. if (this.needInitialSkinMatrix) {
  29201. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  29202. var mesh = this._meshesWithPoseMatrix[index];
  29203. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  29204. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29205. }
  29206. var poseMatrix = mesh.getPoseMatrix();
  29207. // Prepare bones
  29208. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  29209. var bone = this.bones[boneIndex];
  29210. if (!bone.getParent()) {
  29211. var matrix = bone.getBaseMatrix();
  29212. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  29213. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  29214. }
  29215. }
  29216. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  29217. }
  29218. }
  29219. else {
  29220. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  29221. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29222. }
  29223. this._computeTransformMatrices(this._transformMatrices, null);
  29224. }
  29225. this._isDirty = false;
  29226. this._scene._activeBones.addCount(this.bones.length, false);
  29227. };
  29228. Skeleton.prototype.getAnimatables = function () {
  29229. if (!this._animatables || this._animatables.length !== this.bones.length) {
  29230. this._animatables = [];
  29231. for (var index = 0; index < this.bones.length; index++) {
  29232. this._animatables.push(this.bones[index]);
  29233. }
  29234. }
  29235. return this._animatables;
  29236. };
  29237. Skeleton.prototype.clone = function (name, id) {
  29238. var result = new Skeleton(name, id || name, this._scene);
  29239. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29240. for (var index = 0; index < this.bones.length; index++) {
  29241. var source = this.bones[index];
  29242. var parentBone = null;
  29243. if (source.getParent()) {
  29244. var parentIndex = this.bones.indexOf(source.getParent());
  29245. parentBone = result.bones[parentIndex];
  29246. }
  29247. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  29248. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  29249. }
  29250. if (this._ranges) {
  29251. result._ranges = {};
  29252. for (var rangeName in this._ranges) {
  29253. result._ranges[rangeName] = this._ranges[rangeName].clone();
  29254. }
  29255. }
  29256. this._isDirty = true;
  29257. return result;
  29258. };
  29259. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  29260. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  29261. this.bones.forEach(function (bone) {
  29262. bone.animations.forEach(function (animation) {
  29263. animation.enableBlending = true;
  29264. animation.blendingSpeed = blendingSpeed;
  29265. });
  29266. });
  29267. };
  29268. Skeleton.prototype.dispose = function () {
  29269. this._meshesWithPoseMatrix = [];
  29270. // Animations
  29271. this.getScene().stopAnimation(this);
  29272. // Remove from scene
  29273. this.getScene().removeSkeleton(this);
  29274. };
  29275. Skeleton.prototype.serialize = function () {
  29276. var serializationObject = {};
  29277. serializationObject.name = this.name;
  29278. serializationObject.id = this.id;
  29279. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  29280. serializationObject.bones = [];
  29281. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29282. for (var index = 0; index < this.bones.length; index++) {
  29283. var bone = this.bones[index];
  29284. var serializedBone = {
  29285. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  29286. name: bone.name,
  29287. matrix: bone.getLocalMatrix().toArray(),
  29288. rest: bone.getRestPose().toArray()
  29289. };
  29290. serializationObject.bones.push(serializedBone);
  29291. if (bone.length) {
  29292. serializedBone.length = bone.length;
  29293. }
  29294. if (bone.animations && bone.animations.length > 0) {
  29295. serializedBone.animation = bone.animations[0].serialize();
  29296. }
  29297. serializationObject.ranges = [];
  29298. for (var name in this._ranges) {
  29299. var range = {};
  29300. range.name = name;
  29301. range.from = this._ranges[name].from;
  29302. range.to = this._ranges[name].to;
  29303. serializationObject.ranges.push(range);
  29304. }
  29305. }
  29306. return serializationObject;
  29307. };
  29308. Skeleton.Parse = function (parsedSkeleton, scene) {
  29309. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  29310. if (parsedSkeleton.dimensionsAtRest) {
  29311. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  29312. }
  29313. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  29314. var index;
  29315. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  29316. var parsedBone = parsedSkeleton.bones[index];
  29317. var parentBone = null;
  29318. if (parsedBone.parentBoneIndex > -1) {
  29319. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  29320. }
  29321. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  29322. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  29323. if (parsedBone.length) {
  29324. bone.length = parsedBone.length;
  29325. }
  29326. if (parsedBone.animation) {
  29327. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  29328. }
  29329. }
  29330. // placed after bones, so createAnimationRange can cascade down
  29331. if (parsedSkeleton.ranges) {
  29332. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  29333. var data = parsedSkeleton.ranges[index];
  29334. skeleton.createAnimationRange(data.name, data.from, data.to);
  29335. }
  29336. }
  29337. return skeleton;
  29338. };
  29339. return Skeleton;
  29340. })();
  29341. BABYLON.Skeleton = Skeleton;
  29342. })(BABYLON || (BABYLON = {}));
  29343. var BABYLON;
  29344. (function (BABYLON) {
  29345. var PostProcess = (function () {
  29346. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  29347. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  29348. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  29349. this.name = name;
  29350. this.width = -1;
  29351. this.height = -1;
  29352. /*
  29353. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  29354. Can only be used on a single postprocess or on the last one of a chain.
  29355. */
  29356. this.enablePixelPerfectMode = false;
  29357. this._reusable = false;
  29358. this._textures = new BABYLON.SmartArray(2);
  29359. this._currentRenderTextureInd = 0;
  29360. this._scaleRatio = new BABYLON.Vector2(1, 1);
  29361. // Events
  29362. /**
  29363. * An event triggered when the postprocess is activated.
  29364. * @type {BABYLON.Observable}
  29365. */
  29366. this.onActivateObservable = new BABYLON.Observable();
  29367. /**
  29368. * An event triggered when the postprocess changes its size.
  29369. * @type {BABYLON.Observable}
  29370. */
  29371. this.onSizeChangedObservable = new BABYLON.Observable();
  29372. /**
  29373. * An event triggered when the postprocess applies its effect.
  29374. * @type {BABYLON.Observable}
  29375. */
  29376. this.onApplyObservable = new BABYLON.Observable();
  29377. /**
  29378. * An event triggered before rendering the postprocess
  29379. * @type {BABYLON.Observable}
  29380. */
  29381. this.onBeforeRenderObservable = new BABYLON.Observable();
  29382. /**
  29383. * An event triggered after rendering the postprocess
  29384. * @type {BABYLON.Observable}
  29385. */
  29386. this.onAfterRenderObservable = new BABYLON.Observable();
  29387. if (camera != null) {
  29388. this._camera = camera;
  29389. this._scene = camera.getScene();
  29390. camera.attachPostProcess(this);
  29391. this._engine = this._scene.getEngine();
  29392. }
  29393. else {
  29394. this._engine = engine;
  29395. }
  29396. this._options = options;
  29397. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  29398. this._reusable = reusable || false;
  29399. this._textureType = textureType;
  29400. this._samplers = samplers || [];
  29401. this._samplers.push("textureSampler");
  29402. this._fragmentUrl = fragmentUrl;
  29403. this._parameters = parameters || [];
  29404. this._parameters.push("scale");
  29405. this.updateEffect(defines);
  29406. }
  29407. Object.defineProperty(PostProcess.prototype, "onActivate", {
  29408. set: function (callback) {
  29409. if (this._onActivateObserver) {
  29410. this.onActivateObservable.remove(this._onActivateObserver);
  29411. }
  29412. this._onActivateObserver = this.onActivateObservable.add(callback);
  29413. },
  29414. enumerable: true,
  29415. configurable: true
  29416. });
  29417. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  29418. set: function (callback) {
  29419. if (this._onSizeChangedObserver) {
  29420. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  29421. }
  29422. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  29423. },
  29424. enumerable: true,
  29425. configurable: true
  29426. });
  29427. Object.defineProperty(PostProcess.prototype, "onApply", {
  29428. set: function (callback) {
  29429. if (this._onApplyObserver) {
  29430. this.onApplyObservable.remove(this._onApplyObserver);
  29431. }
  29432. this._onApplyObserver = this.onApplyObservable.add(callback);
  29433. },
  29434. enumerable: true,
  29435. configurable: true
  29436. });
  29437. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  29438. set: function (callback) {
  29439. if (this._onBeforeRenderObserver) {
  29440. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29441. }
  29442. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29443. },
  29444. enumerable: true,
  29445. configurable: true
  29446. });
  29447. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  29448. set: function (callback) {
  29449. if (this._onAfterRenderObserver) {
  29450. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29451. }
  29452. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29453. },
  29454. enumerable: true,
  29455. configurable: true
  29456. });
  29457. PostProcess.prototype.updateEffect = function (defines) {
  29458. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  29459. };
  29460. PostProcess.prototype.isReusable = function () {
  29461. return this._reusable;
  29462. };
  29463. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  29464. PostProcess.prototype.markTextureDirty = function () {
  29465. this.width = -1;
  29466. };
  29467. PostProcess.prototype.activate = function (camera, sourceTexture) {
  29468. camera = camera || this._camera;
  29469. var scene = camera.getScene();
  29470. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  29471. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  29472. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  29473. var desiredWidth = this._options.width || requiredWidth;
  29474. var desiredHeight = this._options.height || requiredHeight;
  29475. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  29476. if (!this._options.width) {
  29477. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  29478. }
  29479. if (!this._options.height) {
  29480. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  29481. }
  29482. }
  29483. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  29484. if (this._textures.length > 0) {
  29485. for (var i = 0; i < this._textures.length; i++) {
  29486. this._engine._releaseTexture(this._textures.data[i]);
  29487. }
  29488. this._textures.reset();
  29489. }
  29490. this.width = desiredWidth;
  29491. this.height = desiredHeight;
  29492. var textureSize = { width: this.width, height: this.height };
  29493. var textureOptions = {
  29494. generateMipMaps: false,
  29495. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  29496. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  29497. samplingMode: this.renderTargetSamplingMode,
  29498. type: this._textureType
  29499. };
  29500. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29501. if (this._reusable) {
  29502. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29503. }
  29504. this.onSizeChangedObservable.notifyObservers(this);
  29505. }
  29506. if (this.enablePixelPerfectMode) {
  29507. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  29508. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  29509. }
  29510. else {
  29511. this._scaleRatio.copyFromFloats(1, 1);
  29512. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  29513. }
  29514. this.onActivateObservable.notifyObservers(camera);
  29515. // Clear
  29516. if (this.clearColor) {
  29517. this._engine.clear(this.clearColor, true, true, true);
  29518. }
  29519. else {
  29520. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  29521. }
  29522. if (this._reusable) {
  29523. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  29524. }
  29525. };
  29526. Object.defineProperty(PostProcess.prototype, "isSupported", {
  29527. get: function () {
  29528. return this._effect.isSupported;
  29529. },
  29530. enumerable: true,
  29531. configurable: true
  29532. });
  29533. PostProcess.prototype.apply = function () {
  29534. // Check
  29535. if (!this._effect.isReady())
  29536. return null;
  29537. // States
  29538. this._engine.enableEffect(this._effect);
  29539. this._engine.setState(false);
  29540. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29541. this._engine.setDepthBuffer(false);
  29542. this._engine.setDepthWrite(false);
  29543. // Texture
  29544. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  29545. // Parameters
  29546. this._effect.setVector2("scale", this._scaleRatio);
  29547. this.onApplyObservable.notifyObservers(this._effect);
  29548. return this._effect;
  29549. };
  29550. PostProcess.prototype.dispose = function (camera) {
  29551. camera = camera || this._camera;
  29552. if (this._textures.length > 0) {
  29553. for (var i = 0; i < this._textures.length; i++) {
  29554. this._engine._releaseTexture(this._textures.data[i]);
  29555. }
  29556. this._textures.reset();
  29557. }
  29558. if (!camera) {
  29559. return;
  29560. }
  29561. camera.detachPostProcess(this);
  29562. var index = camera._postProcesses.indexOf(this);
  29563. if (index === 0 && camera._postProcesses.length > 0) {
  29564. this._camera._postProcesses[0].markTextureDirty();
  29565. }
  29566. this.onActivateObservable.clear();
  29567. this.onAfterRenderObservable.clear();
  29568. this.onApplyObservable.clear();
  29569. this.onBeforeRenderObservable.clear();
  29570. this.onSizeChangedObservable.clear();
  29571. };
  29572. return PostProcess;
  29573. })();
  29574. BABYLON.PostProcess = PostProcess;
  29575. })(BABYLON || (BABYLON = {}));
  29576. var BABYLON;
  29577. (function (BABYLON) {
  29578. var PostProcessManager = (function () {
  29579. function PostProcessManager(scene) {
  29580. this._vertexBuffers = {};
  29581. this._scene = scene;
  29582. }
  29583. PostProcessManager.prototype._prepareBuffers = function () {
  29584. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29585. return;
  29586. }
  29587. // VBO
  29588. var vertices = [];
  29589. vertices.push(1, 1);
  29590. vertices.push(-1, 1);
  29591. vertices.push(-1, -1);
  29592. vertices.push(1, -1);
  29593. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29594. // Indices
  29595. var indices = [];
  29596. indices.push(0);
  29597. indices.push(1);
  29598. indices.push(2);
  29599. indices.push(0);
  29600. indices.push(2);
  29601. indices.push(3);
  29602. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29603. };
  29604. // Methods
  29605. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  29606. var postProcesses = this._scene.activeCamera._postProcesses;
  29607. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29608. return false;
  29609. }
  29610. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  29611. return true;
  29612. };
  29613. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29614. var engine = this._scene.getEngine();
  29615. for (var index = 0; index < postProcesses.length; index++) {
  29616. if (index < postProcesses.length - 1) {
  29617. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29618. }
  29619. else {
  29620. if (targetTexture) {
  29621. engine.bindFramebuffer(targetTexture);
  29622. }
  29623. else {
  29624. engine.restoreDefaultFramebuffer();
  29625. }
  29626. }
  29627. var pp = postProcesses[index];
  29628. var effect = pp.apply();
  29629. if (effect) {
  29630. pp.onBeforeRenderObservable.notifyObservers(effect);
  29631. // VBOs
  29632. this._prepareBuffers();
  29633. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29634. // Draw order
  29635. engine.draw(true, 0, 6);
  29636. pp.onAfterRenderObservable.notifyObservers(effect);
  29637. }
  29638. }
  29639. // Restore depth buffer
  29640. engine.setDepthBuffer(true);
  29641. engine.setDepthWrite(true);
  29642. };
  29643. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29644. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29645. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29646. return;
  29647. }
  29648. var engine = this._scene.getEngine();
  29649. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29650. if (index < len - 1) {
  29651. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29652. }
  29653. else {
  29654. if (targetTexture) {
  29655. engine.bindFramebuffer(targetTexture, faceIndex);
  29656. }
  29657. else {
  29658. engine.restoreDefaultFramebuffer();
  29659. }
  29660. }
  29661. if (doNotPresent) {
  29662. break;
  29663. }
  29664. var pp = postProcesses[index];
  29665. var effect = pp.apply();
  29666. if (effect) {
  29667. pp.onBeforeRenderObservable.notifyObservers(effect);
  29668. // VBOs
  29669. this._prepareBuffers();
  29670. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29671. // Draw order
  29672. engine.draw(true, 0, 6);
  29673. pp.onAfterRenderObservable.notifyObservers(effect);
  29674. }
  29675. }
  29676. // Restore depth buffer
  29677. engine.setDepthBuffer(true);
  29678. engine.setDepthWrite(true);
  29679. };
  29680. PostProcessManager.prototype.dispose = function () {
  29681. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29682. if (buffer) {
  29683. buffer.dispose();
  29684. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29685. }
  29686. if (this._indexBuffer) {
  29687. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29688. this._indexBuffer = null;
  29689. }
  29690. };
  29691. return PostProcessManager;
  29692. })();
  29693. BABYLON.PostProcessManager = PostProcessManager;
  29694. })(BABYLON || (BABYLON = {}));
  29695. var BABYLON;
  29696. (function (BABYLON) {
  29697. var PassPostProcess = (function (_super) {
  29698. __extends(PassPostProcess, _super);
  29699. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  29700. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  29701. }
  29702. return PassPostProcess;
  29703. })(BABYLON.PostProcess);
  29704. BABYLON.PassPostProcess = PassPostProcess;
  29705. })(BABYLON || (BABYLON = {}));
  29706. var BABYLON;
  29707. (function (BABYLON) {
  29708. /**
  29709. * This is a holder class for the physics joint created by the physics plugin.
  29710. * It holds a set of functions to control the underlying joint.
  29711. */
  29712. var PhysicsJoint = (function () {
  29713. function PhysicsJoint(type, jointData) {
  29714. this.type = type;
  29715. this.jointData = jointData;
  29716. jointData.nativeParams = jointData.nativeParams || {};
  29717. }
  29718. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  29719. get: function () {
  29720. return this._physicsJoint;
  29721. },
  29722. set: function (newJoint) {
  29723. if (this._physicsJoint) {
  29724. }
  29725. this._physicsJoint = newJoint;
  29726. },
  29727. enumerable: true,
  29728. configurable: true
  29729. });
  29730. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  29731. set: function (physicsPlugin) {
  29732. this._physicsPlugin = physicsPlugin;
  29733. },
  29734. enumerable: true,
  29735. configurable: true
  29736. });
  29737. /**
  29738. * Execute a function that is physics-plugin specific.
  29739. * @param {Function} func the function that will be executed.
  29740. * It accepts two parameters: the physics world and the physics joint.
  29741. */
  29742. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  29743. func(this._physicsPlugin.world, this._physicsJoint);
  29744. };
  29745. //TODO check if the native joints are the same
  29746. //Joint Types
  29747. PhysicsJoint.DistanceJoint = 0;
  29748. PhysicsJoint.HingeJoint = 1;
  29749. PhysicsJoint.BallAndSocketJoint = 2;
  29750. PhysicsJoint.WheelJoint = 3;
  29751. PhysicsJoint.SliderJoint = 4;
  29752. //OIMO
  29753. PhysicsJoint.PrismaticJoint = 5;
  29754. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  29755. PhysicsJoint.UniversalJoint = 6;
  29756. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  29757. //Cannon
  29758. //Similar to a Ball-Joint. Different in params
  29759. PhysicsJoint.PointToPointJoint = 8;
  29760. //Cannon only at the moment
  29761. PhysicsJoint.SpringJoint = 9;
  29762. PhysicsJoint.LockJoint = 10;
  29763. return PhysicsJoint;
  29764. })();
  29765. BABYLON.PhysicsJoint = PhysicsJoint;
  29766. /**
  29767. * A class representing a physics distance joint.
  29768. */
  29769. var DistanceJoint = (function (_super) {
  29770. __extends(DistanceJoint, _super);
  29771. function DistanceJoint(jointData) {
  29772. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  29773. }
  29774. /**
  29775. * Update the predefined distance.
  29776. */
  29777. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  29778. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  29779. };
  29780. return DistanceJoint;
  29781. })(PhysicsJoint);
  29782. BABYLON.DistanceJoint = DistanceJoint;
  29783. var MotorEnabledJoint = (function (_super) {
  29784. __extends(MotorEnabledJoint, _super);
  29785. function MotorEnabledJoint(type, jointData) {
  29786. _super.call(this, type, jointData);
  29787. }
  29788. /**
  29789. * Set the motor values.
  29790. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29791. * @param {number} force the force to apply
  29792. * @param {number} maxForce max force for this motor.
  29793. */
  29794. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  29795. this._physicsPlugin.setMotor(this, force, maxForce);
  29796. };
  29797. /**
  29798. * Set the motor's limits.
  29799. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29800. */
  29801. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29802. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29803. };
  29804. return MotorEnabledJoint;
  29805. })(PhysicsJoint);
  29806. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  29807. /**
  29808. * This class represents a single hinge physics joint
  29809. */
  29810. var HingeJoint = (function (_super) {
  29811. __extends(HingeJoint, _super);
  29812. function HingeJoint(jointData) {
  29813. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  29814. }
  29815. /**
  29816. * Set the motor values.
  29817. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29818. * @param {number} force the force to apply
  29819. * @param {number} maxForce max force for this motor.
  29820. */
  29821. HingeJoint.prototype.setMotor = function (force, maxForce) {
  29822. this._physicsPlugin.setMotor(this, force, maxForce);
  29823. };
  29824. /**
  29825. * Set the motor's limits.
  29826. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29827. */
  29828. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29829. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29830. };
  29831. return HingeJoint;
  29832. })(MotorEnabledJoint);
  29833. BABYLON.HingeJoint = HingeJoint;
  29834. /**
  29835. * This class represents a dual hinge physics joint (same as wheel joint)
  29836. */
  29837. var Hinge2Joint = (function (_super) {
  29838. __extends(Hinge2Joint, _super);
  29839. function Hinge2Joint(jointData) {
  29840. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  29841. }
  29842. /**
  29843. * Set the motor values.
  29844. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29845. * @param {number} force the force to apply
  29846. * @param {number} maxForce max force for this motor.
  29847. * @param {motorIndex} the motor's index, 0 or 1.
  29848. */
  29849. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  29850. if (motorIndex === void 0) { motorIndex = 0; }
  29851. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  29852. };
  29853. /**
  29854. * Set the motor limits.
  29855. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29856. * @param {number} upperLimit the upper limit
  29857. * @param {number} lowerLimit lower limit
  29858. * @param {motorIndex} the motor's index, 0 or 1.
  29859. */
  29860. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  29861. if (motorIndex === void 0) { motorIndex = 0; }
  29862. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  29863. };
  29864. return Hinge2Joint;
  29865. })(MotorEnabledJoint);
  29866. BABYLON.Hinge2Joint = Hinge2Joint;
  29867. })(BABYLON || (BABYLON = {}));
  29868. var BABYLON;
  29869. (function (BABYLON) {
  29870. var PhysicsImpostor = (function () {
  29871. function PhysicsImpostor(object, type, _options, _scene) {
  29872. var _this = this;
  29873. if (_options === void 0) { _options = { mass: 0 }; }
  29874. this.object = object;
  29875. this.type = type;
  29876. this._options = _options;
  29877. this._scene = _scene;
  29878. this._bodyUpdateRequired = false;
  29879. this._onBeforePhysicsStepCallbacks = new Array();
  29880. this._onAfterPhysicsStepCallbacks = new Array();
  29881. this._onPhysicsCollideCallbacks = [];
  29882. this._deltaPosition = BABYLON.Vector3.Zero();
  29883. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  29884. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  29885. /**
  29886. * this function is executed by the physics engine.
  29887. */
  29888. this.beforeStep = function () {
  29889. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  29890. //conjugate deltaRotation
  29891. if (_this._deltaRotationConjugated) {
  29892. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  29893. }
  29894. else {
  29895. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  29896. }
  29897. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  29898. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  29899. func(_this);
  29900. });
  29901. };
  29902. /**
  29903. * this function is executed by the physics engine.
  29904. */
  29905. this.afterStep = function () {
  29906. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  29907. func(_this);
  29908. });
  29909. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  29910. _this.object.position.addInPlace(_this._deltaPosition);
  29911. if (_this._deltaRotation) {
  29912. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  29913. }
  29914. };
  29915. //event and body object due to cannon's event-based architecture.
  29916. this.onCollide = function (e) {
  29917. if (!_this._onPhysicsCollideCallbacks.length)
  29918. return;
  29919. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  29920. if (otherImpostor) {
  29921. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  29922. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  29923. }).forEach(function (obj) {
  29924. obj.callback(_this, otherImpostor);
  29925. });
  29926. }
  29927. };
  29928. //sanity check!
  29929. if (!this.object) {
  29930. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  29931. return;
  29932. }
  29933. //legacy support for old syntax.
  29934. if (!this._scene && object.getScene) {
  29935. this._scene = object.getScene();
  29936. }
  29937. this._physicsEngine = this._scene.getPhysicsEngine();
  29938. if (!this._physicsEngine) {
  29939. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  29940. }
  29941. else {
  29942. //set the object's quaternion, if not set
  29943. if (!this.object.rotationQuaternion) {
  29944. if (this.object.rotation) {
  29945. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  29946. }
  29947. else {
  29948. this.object.rotationQuaternion = new BABYLON.Quaternion();
  29949. }
  29950. }
  29951. //default options params
  29952. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  29953. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  29954. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  29955. this._joints = [];
  29956. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  29957. if (!this.object.parent) {
  29958. this._init();
  29959. }
  29960. }
  29961. }
  29962. /**
  29963. * This function will completly initialize this impostor.
  29964. * It will create a new body - but only if this mesh has no parent.
  29965. * If it has, this impostor will not be used other than to define the impostor
  29966. * of the child mesh.
  29967. */
  29968. PhysicsImpostor.prototype._init = function () {
  29969. this._physicsEngine.removeImpostor(this);
  29970. this.physicsBody = null;
  29971. this._parent = this._parent || this._getPhysicsParent();
  29972. if (!this.parent) {
  29973. this._physicsEngine.addImpostor(this);
  29974. }
  29975. };
  29976. PhysicsImpostor.prototype._getPhysicsParent = function () {
  29977. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  29978. var parentMesh = this.object.parent;
  29979. return parentMesh.physicsImpostor;
  29980. }
  29981. return;
  29982. };
  29983. /**
  29984. * Should a new body be generated.
  29985. */
  29986. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  29987. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  29988. };
  29989. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  29990. this.forceUpdate();
  29991. };
  29992. /**
  29993. * Force a regeneration of this or the parent's impostor's body.
  29994. * Use under cautious - This will remove all joints already implemented.
  29995. */
  29996. PhysicsImpostor.prototype.forceUpdate = function () {
  29997. this._init();
  29998. if (this.parent) {
  29999. this.parent.forceUpdate();
  30000. }
  30001. };
  30002. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  30003. /*public get mesh(): AbstractMesh {
  30004. return this._mesh;
  30005. }*/
  30006. /**
  30007. * Gets the body that holds this impostor. Either its own, or its parent.
  30008. */
  30009. get: function () {
  30010. return this._parent ? this._parent.physicsBody : this._physicsBody;
  30011. },
  30012. /**
  30013. * Set the physics body. Used mainly by the physics engine/plugin
  30014. */
  30015. set: function (physicsBody) {
  30016. if (this._physicsBody) {
  30017. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  30018. }
  30019. this._physicsBody = physicsBody;
  30020. this.resetUpdateFlags();
  30021. },
  30022. enumerable: true,
  30023. configurable: true
  30024. });
  30025. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  30026. get: function () {
  30027. return this._parent;
  30028. },
  30029. enumerable: true,
  30030. configurable: true
  30031. });
  30032. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  30033. this._bodyUpdateRequired = false;
  30034. };
  30035. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  30036. if (this.object.getBoundingInfo) {
  30037. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  30038. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  30039. }
  30040. else {
  30041. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  30042. }
  30043. };
  30044. PhysicsImpostor.prototype.getObjectCenter = function () {
  30045. if (this.object.getBoundingInfo) {
  30046. return this.object.getBoundingInfo().boundingBox.center;
  30047. }
  30048. else {
  30049. return this.object.position;
  30050. }
  30051. };
  30052. /**
  30053. * Get a specific parametes from the options parameter.
  30054. */
  30055. PhysicsImpostor.prototype.getParam = function (paramName) {
  30056. return this._options[paramName];
  30057. };
  30058. /**
  30059. * Sets a specific parameter in the options given to the physics plugin
  30060. */
  30061. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  30062. this._options[paramName] = value;
  30063. this._bodyUpdateRequired = true;
  30064. };
  30065. /**
  30066. * Specifically change the body's mass option. Won't recreate the physics body object
  30067. */
  30068. PhysicsImpostor.prototype.setMass = function (mass) {
  30069. if (this.getParam("mass") !== mass) {
  30070. this.setParam("mass", mass);
  30071. }
  30072. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  30073. };
  30074. PhysicsImpostor.prototype.getLinearVelocity = function () {
  30075. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  30076. };
  30077. /**
  30078. * Set the body's linear velocity.
  30079. */
  30080. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  30081. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  30082. };
  30083. PhysicsImpostor.prototype.getAngularVelocity = function () {
  30084. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  30085. };
  30086. /**
  30087. * Set the body's linear velocity.
  30088. */
  30089. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  30090. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  30091. };
  30092. /**
  30093. * Execute a function with the physics plugin native code.
  30094. * Provide a function the will have two variables - the world object and the physics body object.
  30095. */
  30096. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  30097. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  30098. };
  30099. /**
  30100. * Register a function that will be executed before the physics world is stepping forward.
  30101. */
  30102. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  30103. this._onBeforePhysicsStepCallbacks.push(func);
  30104. };
  30105. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  30106. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  30107. if (index > -1) {
  30108. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  30109. }
  30110. else {
  30111. BABYLON.Tools.Warn("Function to remove was not found");
  30112. }
  30113. };
  30114. /**
  30115. * Register a function that will be executed after the physics step
  30116. */
  30117. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  30118. this._onAfterPhysicsStepCallbacks.push(func);
  30119. };
  30120. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  30121. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  30122. if (index > -1) {
  30123. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  30124. }
  30125. else {
  30126. BABYLON.Tools.Warn("Function to remove was not found");
  30127. }
  30128. };
  30129. /**
  30130. * register a function that will be executed when this impostor collides against a different body.
  30131. */
  30132. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  30133. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30134. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  30135. };
  30136. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  30137. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30138. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  30139. if (index > -1) {
  30140. this._onPhysicsCollideCallbacks.splice(index, 1);
  30141. }
  30142. else {
  30143. BABYLON.Tools.Warn("Function to remove was not found");
  30144. }
  30145. };
  30146. /**
  30147. * Apply a force
  30148. */
  30149. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  30150. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  30151. };
  30152. /**
  30153. * Apply an impulse
  30154. */
  30155. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  30156. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  30157. };
  30158. /**
  30159. * A help function to create a joint.
  30160. */
  30161. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  30162. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  30163. this.addJoint(otherImpostor, joint);
  30164. };
  30165. /**
  30166. * Add a joint to this impostor with a different impostor.
  30167. */
  30168. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  30169. this._joints.push({
  30170. otherImpostor: otherImpostor,
  30171. joint: joint
  30172. });
  30173. this._physicsEngine.addJoint(this, otherImpostor, joint);
  30174. };
  30175. /**
  30176. * Will keep this body still, in a sleep mode.
  30177. */
  30178. PhysicsImpostor.prototype.sleep = function () {
  30179. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  30180. };
  30181. /**
  30182. * Wake the body up.
  30183. */
  30184. PhysicsImpostor.prototype.wakeUp = function () {
  30185. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  30186. };
  30187. PhysicsImpostor.prototype.clone = function (newObject) {
  30188. if (!newObject)
  30189. return null;
  30190. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  30191. };
  30192. PhysicsImpostor.prototype.dispose = function () {
  30193. var _this = this;
  30194. //no dispose if no physics engine is available.
  30195. if (!this._physicsEngine) {
  30196. return;
  30197. }
  30198. this._joints.forEach(function (j) {
  30199. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  30200. });
  30201. //dispose the physics body
  30202. this._physicsEngine.removeImpostor(this);
  30203. if (this.parent) {
  30204. this.parent.forceUpdate();
  30205. }
  30206. else {
  30207. }
  30208. };
  30209. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  30210. this._deltaPosition.copyFrom(position);
  30211. };
  30212. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  30213. if (!this._deltaRotation) {
  30214. this._deltaRotation = new BABYLON.Quaternion();
  30215. }
  30216. this._deltaRotation.copyFrom(rotation);
  30217. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  30218. };
  30219. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  30220. //Impostor types
  30221. PhysicsImpostor.NoImpostor = 0;
  30222. PhysicsImpostor.SphereImpostor = 1;
  30223. PhysicsImpostor.BoxImpostor = 2;
  30224. PhysicsImpostor.PlaneImpostor = 3;
  30225. PhysicsImpostor.MeshImpostor = 4;
  30226. PhysicsImpostor.CylinderImpostor = 7;
  30227. PhysicsImpostor.ParticleImpostor = 8;
  30228. PhysicsImpostor.HeightmapImpostor = 9;
  30229. return PhysicsImpostor;
  30230. })();
  30231. BABYLON.PhysicsImpostor = PhysicsImpostor;
  30232. })(BABYLON || (BABYLON = {}));
  30233. var BABYLON;
  30234. (function (BABYLON) {
  30235. var PhysicsEngine = (function () {
  30236. function PhysicsEngine(gravity, _physicsPlugin) {
  30237. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  30238. this._physicsPlugin = _physicsPlugin;
  30239. //new methods and parameters
  30240. this._impostors = [];
  30241. this._joints = [];
  30242. if (!this._physicsPlugin.isSupported()) {
  30243. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  30244. + "Please make sure it is included.");
  30245. }
  30246. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  30247. this.setGravity(gravity);
  30248. this.setTimeStep();
  30249. }
  30250. PhysicsEngine.prototype.setGravity = function (gravity) {
  30251. this.gravity = gravity;
  30252. this._physicsPlugin.setGravity(this.gravity);
  30253. };
  30254. /**
  30255. * Set the time step of the physics engine.
  30256. * default is 1/60.
  30257. * To slow it down, enter 1/600 for example.
  30258. * To speed it up, 1/30
  30259. * @param {number} newTimeStep the new timestep to apply to this world.
  30260. */
  30261. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  30262. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  30263. this._physicsPlugin.setTimeStep(newTimeStep);
  30264. };
  30265. PhysicsEngine.prototype.dispose = function () {
  30266. this._impostors.forEach(function (impostor) {
  30267. impostor.dispose();
  30268. });
  30269. this._physicsPlugin.dispose();
  30270. };
  30271. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  30272. return this._physicsPlugin.name;
  30273. };
  30274. /**
  30275. * Adding a new impostor for the impostor tracking.
  30276. * This will be done by the impostor itself.
  30277. * @param {PhysicsImpostor} impostor the impostor to add
  30278. */
  30279. PhysicsEngine.prototype.addImpostor = function (impostor) {
  30280. impostor.uniqueId = this._impostors.push(impostor);
  30281. //if no parent, generate the body
  30282. if (!impostor.parent) {
  30283. this._physicsPlugin.generatePhysicsBody(impostor);
  30284. }
  30285. };
  30286. /**
  30287. * Remove an impostor from the engine.
  30288. * This impostor and its mesh will not longer be updated by the physics engine.
  30289. * @param {PhysicsImpostor} impostor the impostor to remove
  30290. */
  30291. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  30292. var index = this._impostors.indexOf(impostor);
  30293. if (index > -1) {
  30294. var removed = this._impostors.splice(index, 1);
  30295. //Is it needed?
  30296. if (removed.length) {
  30297. //this will also remove it from the world.
  30298. removed[0].physicsBody = null;
  30299. }
  30300. }
  30301. };
  30302. /**
  30303. * Add a joint to the physics engine
  30304. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  30305. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  30306. * @param {PhysicsJoint} the joint that will connect both impostors.
  30307. */
  30308. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  30309. var impostorJoint = {
  30310. mainImpostor: mainImpostor,
  30311. connectedImpostor: connectedImpostor,
  30312. joint: joint
  30313. };
  30314. joint.physicsPlugin = this._physicsPlugin;
  30315. this._joints.push(impostorJoint);
  30316. this._physicsPlugin.generateJoint(impostorJoint);
  30317. };
  30318. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  30319. var matchingJoints = this._joints.filter(function (impostorJoint) {
  30320. return (impostorJoint.connectedImpostor === connectedImpostor
  30321. && impostorJoint.joint === joint
  30322. && impostorJoint.mainImpostor === mainImpostor);
  30323. });
  30324. if (matchingJoints.length) {
  30325. this._physicsPlugin.removeJoint(matchingJoints[0]);
  30326. }
  30327. };
  30328. /**
  30329. * Called by the scene. no need to call it.
  30330. */
  30331. PhysicsEngine.prototype._step = function (delta) {
  30332. var _this = this;
  30333. //check if any mesh has no body / requires an update
  30334. this._impostors.forEach(function (impostor) {
  30335. if (impostor.isBodyInitRequired()) {
  30336. _this._physicsPlugin.generatePhysicsBody(impostor);
  30337. }
  30338. });
  30339. if (delta > 0.1) {
  30340. delta = 0.1;
  30341. }
  30342. else if (delta <= 0) {
  30343. delta = 1.0 / 60.0;
  30344. }
  30345. this._physicsPlugin.executeStep(delta, this._impostors);
  30346. };
  30347. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  30348. return this._physicsPlugin;
  30349. };
  30350. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  30351. for (var i = 0; i < this._impostors.length; ++i) {
  30352. if (this._impostors[i].object === object) {
  30353. return this._impostors[i];
  30354. }
  30355. }
  30356. };
  30357. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  30358. for (var i = 0; i < this._impostors.length; ++i) {
  30359. if (this._impostors[i].physicsBody === body) {
  30360. return this._impostors[i];
  30361. }
  30362. }
  30363. };
  30364. // Statics, Legacy support.
  30365. /**
  30366. * @Deprecated
  30367. *
  30368. */
  30369. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  30370. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  30371. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  30372. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  30373. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  30374. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  30375. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  30376. PhysicsEngine.CapsuleImpostor = -1;
  30377. PhysicsEngine.ConeImpostor = -1;
  30378. PhysicsEngine.ConvexHullImpostor = -1;
  30379. PhysicsEngine.Epsilon = 0.001;
  30380. return PhysicsEngine;
  30381. })();
  30382. BABYLON.PhysicsEngine = PhysicsEngine;
  30383. })(BABYLON || (BABYLON = {}));
  30384. var BABYLON;
  30385. (function (BABYLON) {
  30386. var VertexData = (function () {
  30387. function VertexData() {
  30388. }
  30389. VertexData.prototype.set = function (data, kind) {
  30390. switch (kind) {
  30391. case BABYLON.VertexBuffer.PositionKind:
  30392. this.positions = data;
  30393. break;
  30394. case BABYLON.VertexBuffer.NormalKind:
  30395. this.normals = data;
  30396. break;
  30397. case BABYLON.VertexBuffer.UVKind:
  30398. this.uvs = data;
  30399. break;
  30400. case BABYLON.VertexBuffer.UV2Kind:
  30401. this.uvs2 = data;
  30402. break;
  30403. case BABYLON.VertexBuffer.UV3Kind:
  30404. this.uvs3 = data;
  30405. break;
  30406. case BABYLON.VertexBuffer.UV4Kind:
  30407. this.uvs4 = data;
  30408. break;
  30409. case BABYLON.VertexBuffer.UV5Kind:
  30410. this.uvs5 = data;
  30411. break;
  30412. case BABYLON.VertexBuffer.UV6Kind:
  30413. this.uvs6 = data;
  30414. break;
  30415. case BABYLON.VertexBuffer.ColorKind:
  30416. this.colors = data;
  30417. break;
  30418. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30419. this.matricesIndices = data;
  30420. break;
  30421. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30422. this.matricesWeights = data;
  30423. break;
  30424. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30425. this.matricesIndicesExtra = data;
  30426. break;
  30427. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30428. this.matricesWeightsExtra = data;
  30429. break;
  30430. }
  30431. };
  30432. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30433. this._applyTo(mesh, updatable);
  30434. };
  30435. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30436. this._applyTo(geometry, updatable);
  30437. };
  30438. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30439. this._update(mesh);
  30440. };
  30441. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30442. this._update(geometry);
  30443. };
  30444. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30445. if (this.positions) {
  30446. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30447. }
  30448. if (this.normals) {
  30449. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30450. }
  30451. if (this.uvs) {
  30452. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30453. }
  30454. if (this.uvs2) {
  30455. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30456. }
  30457. if (this.uvs3) {
  30458. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30459. }
  30460. if (this.uvs4) {
  30461. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30462. }
  30463. if (this.uvs5) {
  30464. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30465. }
  30466. if (this.uvs6) {
  30467. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30468. }
  30469. if (this.colors) {
  30470. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30471. }
  30472. if (this.matricesIndices) {
  30473. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30474. }
  30475. if (this.matricesWeights) {
  30476. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30477. }
  30478. if (this.matricesIndicesExtra) {
  30479. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30480. }
  30481. if (this.matricesWeightsExtra) {
  30482. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30483. }
  30484. if (this.indices) {
  30485. meshOrGeometry.setIndices(this.indices);
  30486. }
  30487. };
  30488. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30489. if (this.positions) {
  30490. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30491. }
  30492. if (this.normals) {
  30493. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30494. }
  30495. if (this.uvs) {
  30496. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30497. }
  30498. if (this.uvs2) {
  30499. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30500. }
  30501. if (this.uvs3) {
  30502. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30503. }
  30504. if (this.uvs4) {
  30505. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30506. }
  30507. if (this.uvs5) {
  30508. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30509. }
  30510. if (this.uvs6) {
  30511. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30512. }
  30513. if (this.colors) {
  30514. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30515. }
  30516. if (this.matricesIndices) {
  30517. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30518. }
  30519. if (this.matricesWeights) {
  30520. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30521. }
  30522. if (this.matricesIndicesExtra) {
  30523. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30524. }
  30525. if (this.matricesWeightsExtra) {
  30526. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30527. }
  30528. if (this.indices) {
  30529. meshOrGeometry.setIndices(this.indices);
  30530. }
  30531. };
  30532. VertexData.prototype.transform = function (matrix) {
  30533. var transformed = BABYLON.Vector3.Zero();
  30534. var index;
  30535. if (this.positions) {
  30536. var position = BABYLON.Vector3.Zero();
  30537. for (index = 0; index < this.positions.length; index += 3) {
  30538. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30539. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30540. this.positions[index] = transformed.x;
  30541. this.positions[index + 1] = transformed.y;
  30542. this.positions[index + 2] = transformed.z;
  30543. }
  30544. }
  30545. if (this.normals) {
  30546. var normal = BABYLON.Vector3.Zero();
  30547. for (index = 0; index < this.normals.length; index += 3) {
  30548. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30549. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30550. this.normals[index] = transformed.x;
  30551. this.normals[index + 1] = transformed.y;
  30552. this.normals[index + 2] = transformed.z;
  30553. }
  30554. }
  30555. };
  30556. VertexData.prototype.merge = function (other) {
  30557. if (other.indices) {
  30558. if (!this.indices) {
  30559. this.indices = [];
  30560. }
  30561. var offset = this.positions ? this.positions.length / 3 : 0;
  30562. for (var index = 0; index < other.indices.length; index++) {
  30563. //TODO check type - if Int32Array!
  30564. this.indices.push(other.indices[index] + offset);
  30565. }
  30566. }
  30567. this.positions = this._mergeElement(this.positions, other.positions);
  30568. this.normals = this._mergeElement(this.normals, other.normals);
  30569. this.uvs = this._mergeElement(this.uvs, other.uvs);
  30570. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  30571. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  30572. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  30573. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  30574. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  30575. this.colors = this._mergeElement(this.colors, other.colors);
  30576. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  30577. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  30578. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  30579. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  30580. };
  30581. VertexData.prototype._mergeElement = function (source, other) {
  30582. if (!other)
  30583. return source;
  30584. if (!source)
  30585. return other;
  30586. var len = other.length + source.length;
  30587. var isSrcTypedArray = source instanceof Float32Array;
  30588. var isOthTypedArray = other instanceof Float32Array;
  30589. // use non-loop method when the source is Float32Array
  30590. if (isSrcTypedArray) {
  30591. var ret32 = new Float32Array(len);
  30592. ret32.set(source);
  30593. ret32.set(other, source.length);
  30594. return ret32;
  30595. }
  30596. else if (!isOthTypedArray) {
  30597. return source.concat(other);
  30598. }
  30599. else {
  30600. var ret = source.slice(0); // copy source to a separate array
  30601. for (var i = 0, len = other.length; i < len; i++) {
  30602. ret.push(other[i]);
  30603. }
  30604. return ret;
  30605. }
  30606. };
  30607. VertexData.prototype.serialize = function () {
  30608. var serializationObject = this.serialize();
  30609. if (this.positions) {
  30610. serializationObject.positions = this.positions;
  30611. }
  30612. if (this.normals) {
  30613. serializationObject.normals = this.normals;
  30614. }
  30615. if (this.uvs) {
  30616. serializationObject.uvs = this.uvs;
  30617. }
  30618. if (this.uvs2) {
  30619. serializationObject.uvs2 = this.uvs2;
  30620. }
  30621. if (this.uvs3) {
  30622. serializationObject.uvs3 = this.uvs3;
  30623. }
  30624. if (this.uvs4) {
  30625. serializationObject.uvs4 = this.uvs4;
  30626. }
  30627. if (this.uvs5) {
  30628. serializationObject.uvs5 = this.uvs5;
  30629. }
  30630. if (this.uvs6) {
  30631. serializationObject.uvs6 = this.uvs6;
  30632. }
  30633. if (this.colors) {
  30634. serializationObject.colors = this.colors;
  30635. }
  30636. if (this.matricesIndices) {
  30637. serializationObject.matricesIndices = this.matricesIndices;
  30638. serializationObject.matricesIndices._isExpanded = true;
  30639. }
  30640. if (this.matricesWeights) {
  30641. serializationObject.matricesWeights = this.matricesWeights;
  30642. }
  30643. if (this.matricesIndicesExtra) {
  30644. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30645. serializationObject.matricesIndicesExtra._isExpanded = true;
  30646. }
  30647. if (this.matricesWeightsExtra) {
  30648. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30649. }
  30650. serializationObject.indices = this.indices;
  30651. return serializationObject;
  30652. };
  30653. // Statics
  30654. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  30655. return VertexData._ExtractFrom(mesh, copyWhenShared);
  30656. };
  30657. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  30658. return VertexData._ExtractFrom(geometry, copyWhenShared);
  30659. };
  30660. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  30661. var result = new VertexData();
  30662. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30663. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  30664. }
  30665. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30666. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  30667. }
  30668. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30669. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  30670. }
  30671. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30672. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  30673. }
  30674. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30675. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  30676. }
  30677. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30678. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  30679. }
  30680. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30681. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  30682. }
  30683. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30684. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  30685. }
  30686. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30687. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  30688. }
  30689. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30690. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  30691. }
  30692. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30693. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  30694. }
  30695. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30696. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  30697. }
  30698. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30699. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  30700. }
  30701. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30702. return result;
  30703. };
  30704. VertexData.CreateRibbon = function (options) {
  30705. var pathArray = options.pathArray;
  30706. var closeArray = options.closeArray || false;
  30707. var closePath = options.closePath || false;
  30708. var invertUV = options.invertUV || false;
  30709. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30710. var offset = options.offset || defaultOffset;
  30711. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30712. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30713. var positions = [];
  30714. var indices = [];
  30715. var normals = [];
  30716. var uvs = [];
  30717. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30718. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30719. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30720. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30721. var minlg; // minimal length among all paths from pathArray
  30722. var lg = []; // array of path lengths : nb of vertex per path
  30723. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30724. var p; // path iterator
  30725. var i; // point iterator
  30726. var j; // point iterator
  30727. // if single path in pathArray
  30728. if (pathArray.length < 2) {
  30729. var ar1 = [];
  30730. var ar2 = [];
  30731. for (i = 0; i < pathArray[0].length - offset; i++) {
  30732. ar1.push(pathArray[0][i]);
  30733. ar2.push(pathArray[0][i + offset]);
  30734. }
  30735. pathArray = [ar1, ar2];
  30736. }
  30737. // positions and horizontal distances (u)
  30738. var idc = 0;
  30739. var closePathCorr = (closePath) ? 1 : 0;
  30740. var path;
  30741. var l;
  30742. minlg = pathArray[0].length;
  30743. var vectlg;
  30744. var dist;
  30745. for (p = 0; p < pathArray.length; p++) {
  30746. uTotalDistance[p] = 0;
  30747. us[p] = [0];
  30748. path = pathArray[p];
  30749. l = path.length;
  30750. minlg = (minlg < l) ? minlg : l;
  30751. j = 0;
  30752. while (j < l) {
  30753. positions.push(path[j].x, path[j].y, path[j].z);
  30754. if (j > 0) {
  30755. vectlg = path[j].subtract(path[j - 1]).length();
  30756. dist = vectlg + uTotalDistance[p];
  30757. us[p].push(dist);
  30758. uTotalDistance[p] = dist;
  30759. }
  30760. j++;
  30761. }
  30762. if (closePath) {
  30763. j--;
  30764. positions.push(path[0].x, path[0].y, path[0].z);
  30765. vectlg = path[j].subtract(path[0]).length();
  30766. dist = vectlg + uTotalDistance[p];
  30767. us[p].push(dist);
  30768. uTotalDistance[p] = dist;
  30769. }
  30770. lg[p] = l + closePathCorr;
  30771. idx[p] = idc;
  30772. idc += (l + closePathCorr);
  30773. }
  30774. // vertical distances (v)
  30775. var path1;
  30776. var path2;
  30777. var vertex1;
  30778. var vertex2;
  30779. for (i = 0; i < minlg + closePathCorr; i++) {
  30780. vTotalDistance[i] = 0;
  30781. vs[i] = [0];
  30782. for (p = 0; p < pathArray.length - 1; p++) {
  30783. path1 = pathArray[p];
  30784. path2 = pathArray[p + 1];
  30785. if (i === minlg) {
  30786. vertex1 = path1[0];
  30787. vertex2 = path2[0];
  30788. }
  30789. else {
  30790. vertex1 = path1[i];
  30791. vertex2 = path2[i];
  30792. }
  30793. vectlg = vertex2.subtract(vertex1).length();
  30794. dist = vectlg + vTotalDistance[i];
  30795. vs[i].push(dist);
  30796. vTotalDistance[i] = dist;
  30797. }
  30798. if (closeArray) {
  30799. path1 = pathArray[p];
  30800. path2 = pathArray[0];
  30801. if (i === minlg) {
  30802. vertex2 = path2[0];
  30803. }
  30804. vectlg = vertex2.subtract(vertex1).length();
  30805. dist = vectlg + vTotalDistance[i];
  30806. vTotalDistance[i] = dist;
  30807. }
  30808. }
  30809. // uvs
  30810. var u;
  30811. var v;
  30812. for (p = 0; p < pathArray.length; p++) {
  30813. for (i = 0; i < minlg + closePathCorr; i++) {
  30814. u = us[p][i] / uTotalDistance[p];
  30815. v = vs[i][p] / vTotalDistance[i];
  30816. if (invertUV) {
  30817. uvs.push(v, u);
  30818. }
  30819. else {
  30820. uvs.push(u, v);
  30821. }
  30822. }
  30823. }
  30824. // indices
  30825. p = 0; // path index
  30826. var pi = 0; // positions array index
  30827. var l1 = lg[p] - 1; // path1 length
  30828. var l2 = lg[p + 1] - 1; // path2 length
  30829. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30830. var shft = idx[1] - idx[0]; // shift
  30831. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30832. while (pi <= min && p < path1nb) {
  30833. // 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
  30834. indices.push(pi, pi + shft, pi + 1);
  30835. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30836. pi += 1;
  30837. if (pi === min) {
  30838. p++;
  30839. if (p === lg.length - 1) {
  30840. shft = idx[0] - idx[p];
  30841. l1 = lg[p] - 1;
  30842. l2 = lg[0] - 1;
  30843. }
  30844. else {
  30845. shft = idx[p + 1] - idx[p];
  30846. l1 = lg[p] - 1;
  30847. l2 = lg[p + 1] - 1;
  30848. }
  30849. pi = idx[p];
  30850. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30851. }
  30852. }
  30853. // normals
  30854. VertexData.ComputeNormals(positions, indices, normals);
  30855. if (closePath) {
  30856. var indexFirst = 0;
  30857. var indexLast = 0;
  30858. for (p = 0; p < pathArray.length; p++) {
  30859. indexFirst = idx[p] * 3;
  30860. if (p + 1 < pathArray.length) {
  30861. indexLast = (idx[p + 1] - 1) * 3;
  30862. }
  30863. else {
  30864. indexLast = normals.length - 3;
  30865. }
  30866. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30867. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30868. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30869. normals[indexLast] = normals[indexFirst];
  30870. normals[indexLast + 1] = normals[indexFirst + 1];
  30871. normals[indexLast + 2] = normals[indexFirst + 2];
  30872. }
  30873. }
  30874. // sides
  30875. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30876. // Result
  30877. var vertexData = new VertexData();
  30878. vertexData.indices = indices;
  30879. vertexData.positions = positions;
  30880. vertexData.normals = normals;
  30881. vertexData.uvs = uvs;
  30882. if (closePath) {
  30883. vertexData._idx = idx;
  30884. }
  30885. return vertexData;
  30886. };
  30887. VertexData.CreateBox = function (options) {
  30888. var normalsSource = [
  30889. new BABYLON.Vector3(0, 0, 1),
  30890. new BABYLON.Vector3(0, 0, -1),
  30891. new BABYLON.Vector3(1, 0, 0),
  30892. new BABYLON.Vector3(-1, 0, 0),
  30893. new BABYLON.Vector3(0, 1, 0),
  30894. new BABYLON.Vector3(0, -1, 0)
  30895. ];
  30896. var indices = [];
  30897. var positions = [];
  30898. var normals = [];
  30899. var uvs = [];
  30900. var width = options.width || options.size || 1;
  30901. var height = options.height || options.size || 1;
  30902. var depth = options.depth || options.size || 1;
  30903. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30904. var faceUV = options.faceUV || new Array(6);
  30905. var faceColors = options.faceColors;
  30906. var colors = [];
  30907. // default face colors and UV if undefined
  30908. for (var f = 0; f < 6; f++) {
  30909. if (faceUV[f] === undefined) {
  30910. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30911. }
  30912. if (faceColors && faceColors[f] === undefined) {
  30913. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30914. }
  30915. }
  30916. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30917. // Create each face in turn.
  30918. for (var index = 0; index < normalsSource.length; index++) {
  30919. var normal = normalsSource[index];
  30920. // Get two vectors perpendicular to the face normal and to each other.
  30921. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30922. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30923. // Six indices (two triangles) per face.
  30924. var verticesLength = positions.length / 3;
  30925. indices.push(verticesLength);
  30926. indices.push(verticesLength + 1);
  30927. indices.push(verticesLength + 2);
  30928. indices.push(verticesLength);
  30929. indices.push(verticesLength + 2);
  30930. indices.push(verticesLength + 3);
  30931. // Four vertices per face.
  30932. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30933. positions.push(vertex.x, vertex.y, vertex.z);
  30934. normals.push(normal.x, normal.y, normal.z);
  30935. uvs.push(faceUV[index].z, faceUV[index].w);
  30936. if (faceColors) {
  30937. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30938. }
  30939. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30940. positions.push(vertex.x, vertex.y, vertex.z);
  30941. normals.push(normal.x, normal.y, normal.z);
  30942. uvs.push(faceUV[index].x, faceUV[index].w);
  30943. if (faceColors) {
  30944. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30945. }
  30946. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30947. positions.push(vertex.x, vertex.y, vertex.z);
  30948. normals.push(normal.x, normal.y, normal.z);
  30949. uvs.push(faceUV[index].x, faceUV[index].y);
  30950. if (faceColors) {
  30951. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30952. }
  30953. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30954. positions.push(vertex.x, vertex.y, vertex.z);
  30955. normals.push(normal.x, normal.y, normal.z);
  30956. uvs.push(faceUV[index].z, faceUV[index].y);
  30957. if (faceColors) {
  30958. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30959. }
  30960. }
  30961. // sides
  30962. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30963. // Result
  30964. var vertexData = new VertexData();
  30965. vertexData.indices = indices;
  30966. vertexData.positions = positions;
  30967. vertexData.normals = normals;
  30968. vertexData.uvs = uvs;
  30969. if (faceColors) {
  30970. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30971. vertexData.colors = totalColors;
  30972. }
  30973. return vertexData;
  30974. };
  30975. VertexData.CreateSphere = function (options) {
  30976. var segments = options.segments || 32;
  30977. var diameterX = options.diameterX || options.diameter || 1;
  30978. var diameterY = options.diameterY || options.diameter || 1;
  30979. var diameterZ = options.diameterZ || options.diameter || 1;
  30980. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30981. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30982. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30983. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30984. var totalZRotationSteps = 2 + segments;
  30985. var totalYRotationSteps = 2 * totalZRotationSteps;
  30986. var indices = [];
  30987. var positions = [];
  30988. var normals = [];
  30989. var uvs = [];
  30990. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30991. var normalizedZ = zRotationStep / totalZRotationSteps;
  30992. var angleZ = normalizedZ * Math.PI * slice;
  30993. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30994. var normalizedY = yRotationStep / totalYRotationSteps;
  30995. var angleY = normalizedY * Math.PI * 2 * arc;
  30996. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30997. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30998. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30999. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31000. var vertex = complete.multiply(radius);
  31001. var normal = complete.divide(radius).normalize();
  31002. positions.push(vertex.x, vertex.y, vertex.z);
  31003. normals.push(normal.x, normal.y, normal.z);
  31004. uvs.push(normalizedY, normalizedZ);
  31005. }
  31006. if (zRotationStep > 0) {
  31007. var verticesCount = positions.length / 3;
  31008. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31009. indices.push((firstIndex));
  31010. indices.push((firstIndex + 1));
  31011. indices.push(firstIndex + totalYRotationSteps + 1);
  31012. indices.push((firstIndex + totalYRotationSteps + 1));
  31013. indices.push((firstIndex + 1));
  31014. indices.push((firstIndex + totalYRotationSteps + 2));
  31015. }
  31016. }
  31017. }
  31018. // Sides
  31019. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31020. // Result
  31021. var vertexData = new VertexData();
  31022. vertexData.indices = indices;
  31023. vertexData.positions = positions;
  31024. vertexData.normals = normals;
  31025. vertexData.uvs = uvs;
  31026. return vertexData;
  31027. };
  31028. // Cylinder and cone
  31029. VertexData.CreateCylinder = function (options) {
  31030. var height = options.height || 2;
  31031. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31032. var diameterBottom = options.diameterBottom || options.diameter || 1;
  31033. var tessellation = options.tessellation || 24;
  31034. var subdivisions = options.subdivisions || 1;
  31035. var hasRings = options.hasRings;
  31036. var enclose = options.enclose;
  31037. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31038. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31039. var faceUV = options.faceUV || new Array(3);
  31040. var faceColors = options.faceColors;
  31041. // default face colors and UV if undefined
  31042. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31043. var ringNb = (hasRings) ? subdivisions : 1;
  31044. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31045. var f;
  31046. for (f = 0; f < surfaceNb; f++) {
  31047. if (faceColors && faceColors[f] === undefined) {
  31048. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31049. }
  31050. }
  31051. for (f = 0; f < surfaceNb; f++) {
  31052. if (faceUV && faceUV[f] === undefined) {
  31053. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31054. }
  31055. }
  31056. var indices = [];
  31057. var positions = [];
  31058. var normals = [];
  31059. var uvs = [];
  31060. var colors = [];
  31061. var angle_step = Math.PI * 2 * arc / tessellation;
  31062. var angle;
  31063. var h;
  31064. var radius;
  31065. var tan = (diameterBottom - diameterTop) / 2 / height;
  31066. var ringVertex = BABYLON.Vector3.Zero();
  31067. var ringNormal = BABYLON.Vector3.Zero();
  31068. var ringFirstVertex = BABYLON.Vector3.Zero();
  31069. var ringFirstNormal = BABYLON.Vector3.Zero();
  31070. var quadNormal = BABYLON.Vector3.Zero();
  31071. var Y = BABYLON.Axis.Y;
  31072. // positions, normals, uvs
  31073. var i;
  31074. var j;
  31075. var r;
  31076. var ringIdx = 1;
  31077. var s = 1; // surface index
  31078. var cs = 0;
  31079. var v = 0;
  31080. for (i = 0; i <= subdivisions; i++) {
  31081. h = i / subdivisions;
  31082. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31083. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31084. for (r = 0; r < ringIdx; r++) {
  31085. if (hasRings) {
  31086. s += r;
  31087. }
  31088. if (enclose) {
  31089. s += 2 * r;
  31090. }
  31091. for (j = 0; j <= tessellation; j++) {
  31092. angle = j * angle_step;
  31093. // position
  31094. ringVertex.x = Math.cos(-angle) * radius;
  31095. ringVertex.y = -height / 2 + h * height;
  31096. ringVertex.z = Math.sin(-angle) * radius;
  31097. // normal
  31098. if (diameterTop === 0 && i === subdivisions) {
  31099. // if no top cap, reuse former normals
  31100. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31101. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31102. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31103. }
  31104. else {
  31105. ringNormal.x = ringVertex.x;
  31106. ringNormal.z = ringVertex.z;
  31107. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31108. ringNormal.normalize();
  31109. }
  31110. // keep first ring vertex values for enclose
  31111. if (j === 0) {
  31112. ringFirstVertex.copyFrom(ringVertex);
  31113. ringFirstNormal.copyFrom(ringNormal);
  31114. }
  31115. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31116. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31117. if (hasRings) {
  31118. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31119. }
  31120. else {
  31121. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31122. }
  31123. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31124. if (faceColors) {
  31125. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31126. }
  31127. }
  31128. // if enclose, add four vertices and their dedicated normals
  31129. if (arc !== 1 && enclose) {
  31130. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31131. positions.push(0, ringVertex.y, 0);
  31132. positions.push(0, ringVertex.y, 0);
  31133. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31134. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31135. quadNormal.normalize();
  31136. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31137. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31138. quadNormal.normalize();
  31139. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31140. if (hasRings) {
  31141. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31142. }
  31143. else {
  31144. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31145. }
  31146. uvs.push(faceUV[s + 1].x, v);
  31147. uvs.push(faceUV[s + 1].z, v);
  31148. if (hasRings) {
  31149. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31150. }
  31151. else {
  31152. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31153. }
  31154. uvs.push(faceUV[s + 2].x, v);
  31155. uvs.push(faceUV[s + 2].z, v);
  31156. if (faceColors) {
  31157. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31158. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31159. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31160. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31161. }
  31162. }
  31163. if (cs !== s) {
  31164. cs = s;
  31165. }
  31166. }
  31167. }
  31168. // indices
  31169. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31170. var s;
  31171. i = 0;
  31172. for (s = 0; s < subdivisions; s++) {
  31173. for (j = 0; j < tessellation; j++) {
  31174. var i0 = i * (e + 1) + j;
  31175. var i1 = (i + 1) * (e + 1) + j;
  31176. var i2 = i * (e + 1) + (j + 1);
  31177. var i3 = (i + 1) * (e + 1) + (j + 1);
  31178. indices.push(i0, i1, i2);
  31179. indices.push(i3, i2, i1);
  31180. }
  31181. if (arc !== 1 && enclose) {
  31182. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31183. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31184. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31185. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31186. }
  31187. i = (hasRings) ? (i + 2) : (i + 1);
  31188. }
  31189. // Caps
  31190. var createCylinderCap = function (isTop) {
  31191. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31192. if (radius === 0) {
  31193. return;
  31194. }
  31195. // Cap positions, normals & uvs
  31196. var angle;
  31197. var circleVector;
  31198. var i;
  31199. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31200. var c;
  31201. if (faceColors) {
  31202. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31203. }
  31204. // cap center
  31205. var vbase = positions.length / 3;
  31206. var offset = isTop ? height / 2 : -height / 2;
  31207. var center = new BABYLON.Vector3(0, offset, 0);
  31208. positions.push(center.x, center.y, center.z);
  31209. normals.push(0, isTop ? 1 : -1, 0);
  31210. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31211. if (faceColors) {
  31212. colors.push(c.r, c.g, c.b, c.a);
  31213. }
  31214. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31215. for (i = 0; i <= tessellation; i++) {
  31216. angle = Math.PI * 2 * i * arc / tessellation;
  31217. var cos = Math.cos(-angle);
  31218. var sin = Math.sin(-angle);
  31219. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31220. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31221. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31222. normals.push(0, isTop ? 1 : -1, 0);
  31223. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31224. if (faceColors) {
  31225. colors.push(c.r, c.g, c.b, c.a);
  31226. }
  31227. }
  31228. // Cap indices
  31229. for (i = 0; i < tessellation; i++) {
  31230. if (!isTop) {
  31231. indices.push(vbase);
  31232. indices.push(vbase + (i + 1));
  31233. indices.push(vbase + (i + 2));
  31234. }
  31235. else {
  31236. indices.push(vbase);
  31237. indices.push(vbase + (i + 2));
  31238. indices.push(vbase + (i + 1));
  31239. }
  31240. }
  31241. };
  31242. // add caps to geometry
  31243. createCylinderCap(false);
  31244. createCylinderCap(true);
  31245. // Sides
  31246. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31247. var vertexData = new VertexData();
  31248. vertexData.indices = indices;
  31249. vertexData.positions = positions;
  31250. vertexData.normals = normals;
  31251. vertexData.uvs = uvs;
  31252. if (faceColors) {
  31253. vertexData.colors = colors;
  31254. }
  31255. return vertexData;
  31256. };
  31257. VertexData.CreateTorus = function (options) {
  31258. var indices = [];
  31259. var positions = [];
  31260. var normals = [];
  31261. var uvs = [];
  31262. var diameter = options.diameter || 1;
  31263. var thickness = options.thickness || 0.5;
  31264. var tessellation = options.tessellation || 16;
  31265. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31266. var stride = tessellation + 1;
  31267. for (var i = 0; i <= tessellation; i++) {
  31268. var u = i / tessellation;
  31269. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31270. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31271. for (var j = 0; j <= tessellation; j++) {
  31272. var v = 1 - j / tessellation;
  31273. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31274. var dx = Math.cos(innerAngle);
  31275. var dy = Math.sin(innerAngle);
  31276. // Create a vertex.
  31277. var normal = new BABYLON.Vector3(dx, dy, 0);
  31278. var position = normal.scale(thickness / 2);
  31279. var textureCoordinate = new BABYLON.Vector2(u, v);
  31280. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31281. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31282. positions.push(position.x, position.y, position.z);
  31283. normals.push(normal.x, normal.y, normal.z);
  31284. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31285. // And create indices for two triangles.
  31286. var nextI = (i + 1) % stride;
  31287. var nextJ = (j + 1) % stride;
  31288. indices.push(i * stride + j);
  31289. indices.push(i * stride + nextJ);
  31290. indices.push(nextI * stride + j);
  31291. indices.push(i * stride + nextJ);
  31292. indices.push(nextI * stride + nextJ);
  31293. indices.push(nextI * stride + j);
  31294. }
  31295. }
  31296. // Sides
  31297. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31298. // Result
  31299. var vertexData = new VertexData();
  31300. vertexData.indices = indices;
  31301. vertexData.positions = positions;
  31302. vertexData.normals = normals;
  31303. vertexData.uvs = uvs;
  31304. return vertexData;
  31305. };
  31306. VertexData.CreateLineSystem = function (options) {
  31307. var indices = [];
  31308. var positions = [];
  31309. var lines = options.lines;
  31310. var idx = 0;
  31311. for (var l = 0; l < lines.length; l++) {
  31312. var points = lines[l];
  31313. for (var index = 0; index < points.length; index++) {
  31314. positions.push(points[index].x, points[index].y, points[index].z);
  31315. if (index > 0) {
  31316. indices.push(idx - 1);
  31317. indices.push(idx);
  31318. }
  31319. idx++;
  31320. }
  31321. }
  31322. var vertexData = new VertexData();
  31323. vertexData.indices = indices;
  31324. vertexData.positions = positions;
  31325. return vertexData;
  31326. };
  31327. VertexData.CreateDashedLines = function (options) {
  31328. var dashSize = options.dashSize || 3;
  31329. var gapSize = options.gapSize || 1;
  31330. var dashNb = options.dashNb || 200;
  31331. var points = options.points;
  31332. var positions = new Array();
  31333. var indices = new Array();
  31334. var curvect = BABYLON.Vector3.Zero();
  31335. var lg = 0;
  31336. var nb = 0;
  31337. var shft = 0;
  31338. var dashshft = 0;
  31339. var curshft = 0;
  31340. var idx = 0;
  31341. var i = 0;
  31342. for (i = 0; i < points.length - 1; i++) {
  31343. points[i + 1].subtractToRef(points[i], curvect);
  31344. lg += curvect.length();
  31345. }
  31346. shft = lg / dashNb;
  31347. dashshft = dashSize * shft / (dashSize + gapSize);
  31348. for (i = 0; i < points.length - 1; i++) {
  31349. points[i + 1].subtractToRef(points[i], curvect);
  31350. nb = Math.floor(curvect.length() / shft);
  31351. curvect.normalize();
  31352. for (var j = 0; j < nb; j++) {
  31353. curshft = shft * j;
  31354. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31355. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31356. indices.push(idx, idx + 1);
  31357. idx += 2;
  31358. }
  31359. }
  31360. // Result
  31361. var vertexData = new VertexData();
  31362. vertexData.positions = positions;
  31363. vertexData.indices = indices;
  31364. return vertexData;
  31365. };
  31366. VertexData.CreateGround = function (options) {
  31367. var indices = [];
  31368. var positions = [];
  31369. var normals = [];
  31370. var uvs = [];
  31371. var row, col;
  31372. var width = options.width || 1;
  31373. var height = options.height || 1;
  31374. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31375. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31376. for (row = 0; row <= subdivisionsY; row++) {
  31377. for (col = 0; col <= subdivisionsX; col++) {
  31378. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31379. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31380. positions.push(position.x, position.y, position.z);
  31381. normals.push(normal.x, normal.y, normal.z);
  31382. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  31383. }
  31384. }
  31385. for (row = 0; row < subdivisionsY; row++) {
  31386. for (col = 0; col < subdivisionsX; col++) {
  31387. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31388. indices.push(col + 1 + row * (subdivisionsX + 1));
  31389. indices.push(col + row * (subdivisionsX + 1));
  31390. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31391. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31392. indices.push(col + row * (subdivisionsX + 1));
  31393. }
  31394. }
  31395. // Result
  31396. var vertexData = new VertexData();
  31397. vertexData.indices = indices;
  31398. vertexData.positions = positions;
  31399. vertexData.normals = normals;
  31400. vertexData.uvs = uvs;
  31401. return vertexData;
  31402. };
  31403. VertexData.CreateTiledGround = function (options) {
  31404. var xmin = options.xmin || -1.0;
  31405. var zmin = options.zmin || -1.0;
  31406. var xmax = options.xmax || 1.0;
  31407. var zmax = options.zmax || 1.0;
  31408. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31409. var precision = options.precision || { w: 1, h: 1 };
  31410. var indices = [];
  31411. var positions = [];
  31412. var normals = [];
  31413. var uvs = [];
  31414. var row, col, tileRow, tileCol;
  31415. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31416. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31417. precision.w = (precision.w < 1) ? 1 : precision.w;
  31418. precision.h = (precision.h < 1) ? 1 : precision.h;
  31419. var tileSize = {
  31420. 'w': (xmax - xmin) / subdivisions.w,
  31421. 'h': (zmax - zmin) / subdivisions.h
  31422. };
  31423. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31424. // Indices
  31425. var base = positions.length / 3;
  31426. var rowLength = precision.w + 1;
  31427. for (row = 0; row < precision.h; row++) {
  31428. for (col = 0; col < precision.w; col++) {
  31429. var square = [
  31430. base + col + row * rowLength,
  31431. base + (col + 1) + row * rowLength,
  31432. base + (col + 1) + (row + 1) * rowLength,
  31433. base + col + (row + 1) * rowLength
  31434. ];
  31435. indices.push(square[1]);
  31436. indices.push(square[2]);
  31437. indices.push(square[3]);
  31438. indices.push(square[0]);
  31439. indices.push(square[1]);
  31440. indices.push(square[3]);
  31441. }
  31442. }
  31443. // Position, normals and uvs
  31444. var position = BABYLON.Vector3.Zero();
  31445. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31446. for (row = 0; row <= precision.h; row++) {
  31447. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31448. for (col = 0; col <= precision.w; col++) {
  31449. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31450. position.y = 0;
  31451. positions.push(position.x, position.y, position.z);
  31452. normals.push(normal.x, normal.y, normal.z);
  31453. uvs.push(col / precision.w, row / precision.h);
  31454. }
  31455. }
  31456. }
  31457. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31458. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31459. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31460. }
  31461. }
  31462. // Result
  31463. var vertexData = new VertexData();
  31464. vertexData.indices = indices;
  31465. vertexData.positions = positions;
  31466. vertexData.normals = normals;
  31467. vertexData.uvs = uvs;
  31468. return vertexData;
  31469. };
  31470. VertexData.CreateGroundFromHeightMap = function (options) {
  31471. var indices = [];
  31472. var positions = [];
  31473. var normals = [];
  31474. var uvs = [];
  31475. var row, col;
  31476. // Vertices
  31477. for (row = 0; row <= options.subdivisions; row++) {
  31478. for (col = 0; col <= options.subdivisions; col++) {
  31479. 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));
  31480. // Compute height
  31481. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31482. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31483. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31484. var r = options.buffer[pos] / 255.0;
  31485. var g = options.buffer[pos + 1] / 255.0;
  31486. var b = options.buffer[pos + 2] / 255.0;
  31487. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31488. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31489. // Add vertex
  31490. positions.push(position.x, position.y, position.z);
  31491. normals.push(0, 0, 0);
  31492. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31493. }
  31494. }
  31495. // Indices
  31496. for (row = 0; row < options.subdivisions; row++) {
  31497. for (col = 0; col < options.subdivisions; col++) {
  31498. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31499. indices.push(col + 1 + row * (options.subdivisions + 1));
  31500. indices.push(col + row * (options.subdivisions + 1));
  31501. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31502. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31503. indices.push(col + row * (options.subdivisions + 1));
  31504. }
  31505. }
  31506. // Normals
  31507. VertexData.ComputeNormals(positions, indices, normals);
  31508. // Result
  31509. var vertexData = new VertexData();
  31510. vertexData.indices = indices;
  31511. vertexData.positions = positions;
  31512. vertexData.normals = normals;
  31513. vertexData.uvs = uvs;
  31514. return vertexData;
  31515. };
  31516. VertexData.CreatePlane = function (options) {
  31517. var indices = [];
  31518. var positions = [];
  31519. var normals = [];
  31520. var uvs = [];
  31521. var width = options.width || options.size || 1;
  31522. var height = options.height || options.size || 1;
  31523. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31524. // Vertices
  31525. var halfWidth = width / 2.0;
  31526. var halfHeight = height / 2.0;
  31527. positions.push(-halfWidth, -halfHeight, 0);
  31528. normals.push(0, 0, -1.0);
  31529. uvs.push(0.0, 0.0);
  31530. positions.push(halfWidth, -halfHeight, 0);
  31531. normals.push(0, 0, -1.0);
  31532. uvs.push(1.0, 0.0);
  31533. positions.push(halfWidth, halfHeight, 0);
  31534. normals.push(0, 0, -1.0);
  31535. uvs.push(1.0, 1.0);
  31536. positions.push(-halfWidth, halfHeight, 0);
  31537. normals.push(0, 0, -1.0);
  31538. uvs.push(0.0, 1.0);
  31539. // Indices
  31540. indices.push(0);
  31541. indices.push(1);
  31542. indices.push(2);
  31543. indices.push(0);
  31544. indices.push(2);
  31545. indices.push(3);
  31546. // Sides
  31547. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31548. // Result
  31549. var vertexData = new VertexData();
  31550. vertexData.indices = indices;
  31551. vertexData.positions = positions;
  31552. vertexData.normals = normals;
  31553. vertexData.uvs = uvs;
  31554. return vertexData;
  31555. };
  31556. VertexData.CreateDisc = function (options) {
  31557. var positions = [];
  31558. var indices = [];
  31559. var normals = [];
  31560. var uvs = [];
  31561. var radius = options.radius || 0.5;
  31562. var tessellation = options.tessellation || 64;
  31563. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31564. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31565. // positions and uvs
  31566. positions.push(0, 0, 0); // disc center first
  31567. uvs.push(0.5, 0.5);
  31568. var theta = Math.PI * 2 * arc;
  31569. var step = theta / tessellation;
  31570. for (var a = 0; a < theta; a += step) {
  31571. var x = Math.cos(a);
  31572. var y = Math.sin(a);
  31573. var u = (x + 1) / 2;
  31574. var v = (1 - y) / 2;
  31575. positions.push(radius * x, radius * y, 0);
  31576. uvs.push(u, v);
  31577. }
  31578. if (arc === 1) {
  31579. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31580. uvs.push(uvs[2], uvs[3]);
  31581. }
  31582. //indices
  31583. var vertexNb = positions.length / 3;
  31584. for (var i = 1; i < vertexNb - 1; i++) {
  31585. indices.push(i + 1, 0, i);
  31586. }
  31587. // result
  31588. VertexData.ComputeNormals(positions, indices, normals);
  31589. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31590. var vertexData = new VertexData();
  31591. vertexData.indices = indices;
  31592. vertexData.positions = positions;
  31593. vertexData.normals = normals;
  31594. vertexData.uvs = uvs;
  31595. return vertexData;
  31596. };
  31597. VertexData.CreateIcoSphere = function (options) {
  31598. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31599. var radius = options.radius || 1;
  31600. var flat = (options.flat === undefined) ? true : options.flat;
  31601. var subdivisions = options.subdivisions || 4;
  31602. var radiusX = options.radiusX || radius;
  31603. var radiusY = options.radiusY || radius;
  31604. var radiusZ = options.radiusZ || radius;
  31605. var t = (1 + Math.sqrt(5)) / 2;
  31606. // 12 vertex x,y,z
  31607. var ico_vertices = [
  31608. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31609. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31610. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31611. ];
  31612. // index of 3 vertex makes a face of icopshere
  31613. var ico_indices = [
  31614. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31615. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31616. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31617. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31618. ];
  31619. // vertex for uv have aliased position, not for UV
  31620. var vertices_unalias_id = [
  31621. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31622. // vertex alias
  31623. 0,
  31624. 2,
  31625. 3,
  31626. 3,
  31627. 3,
  31628. 4,
  31629. 7,
  31630. 8,
  31631. 9,
  31632. 9,
  31633. 10,
  31634. 11 // 23: B + 12
  31635. ];
  31636. // uv as integer step (not pixels !)
  31637. var ico_vertexuv = [
  31638. 5, 1, 3, 1, 6, 4, 0, 0,
  31639. 5, 3, 4, 2, 2, 2, 4, 0,
  31640. 2, 0, 1, 1, 6, 0, 6, 2,
  31641. // vertex alias (for same vertex on different faces)
  31642. 0, 4,
  31643. 3, 3,
  31644. 4, 4,
  31645. 3, 1,
  31646. 4, 2,
  31647. 4, 4,
  31648. 0, 2,
  31649. 1, 1,
  31650. 2, 2,
  31651. 3, 3,
  31652. 1, 3,
  31653. 2, 4 // 23: B + 12
  31654. ];
  31655. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31656. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31657. // First island of uv mapping
  31658. // v = 4h 3+ 2
  31659. // v = 3h 9+ 4
  31660. // v = 2h 9+ 5 B
  31661. // v = 1h 9 1 0
  31662. // v = 0h 3 8 7 A
  31663. // u = 0 1 2 3 4 5 6 *a
  31664. // Second island of uv mapping
  31665. // v = 4h 0+ B+ 4+
  31666. // v = 3h A+ 2+
  31667. // v = 2h 7+ 6 3+
  31668. // v = 1h 8+ 3+
  31669. // v = 0h
  31670. // u = 0 1 2 3 4 5 6 *a
  31671. // Face layout on texture UV mapping
  31672. // ============
  31673. // \ 4 /\ 16 / ======
  31674. // \ / \ / /\ 11 /
  31675. // \/ 7 \/ / \ /
  31676. // ======= / 10 \/
  31677. // /\ 17 /\ =======
  31678. // / \ / \ \ 15 /\
  31679. // / 8 \/ 12 \ \ / \
  31680. // ============ \/ 6 \
  31681. // \ 18 /\ ============
  31682. // \ / \ \ 5 /\ 0 /
  31683. // \/ 13 \ \ / \ /
  31684. // ======= \/ 1 \/
  31685. // =============
  31686. // /\ 19 /\ 2 /\
  31687. // / \ / \ / \
  31688. // / 14 \/ 9 \/ 3 \
  31689. // ===================
  31690. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31691. var ustep = 138 / 1024;
  31692. var vstep = 239 / 1024;
  31693. var uoffset = 60 / 1024;
  31694. var voffset = 26 / 1024;
  31695. // Second island should have margin, not to touch the first island
  31696. // avoid any borderline artefact in pixel rounding
  31697. var island_u_offset = -40 / 1024;
  31698. var island_v_offset = +20 / 1024;
  31699. // face is either island 0 or 1 :
  31700. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31701. var island = [
  31702. 0, 0, 0, 0, 1,
  31703. 0, 0, 1, 1, 0,
  31704. 0, 0, 1, 1, 0,
  31705. 0, 1, 1, 1, 0 // 15 - 19
  31706. ];
  31707. var indices = [];
  31708. var positions = [];
  31709. var normals = [];
  31710. var uvs = [];
  31711. var current_indice = 0;
  31712. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31713. var face_vertex_pos = new Array(3);
  31714. var face_vertex_uv = new Array(3);
  31715. var v012;
  31716. for (v012 = 0; v012 < 3; v012++) {
  31717. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31718. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31719. }
  31720. // create all with normals
  31721. for (var face = 0; face < 20; face++) {
  31722. // 3 vertex per face
  31723. for (v012 = 0; v012 < 3; v012++) {
  31724. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31725. var v_id = ico_indices[3 * face + v012];
  31726. // vertex have 3D position (x,y,z)
  31727. 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]);
  31728. // Normalize to get normal, then scale to radius
  31729. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31730. // uv Coordinates from vertex ID
  31731. 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);
  31732. }
  31733. // Subdivide the face (interpolate pos, norm, uv)
  31734. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31735. // - norm is linear interpolation of vertex corner normal
  31736. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31737. // - uv is linear interpolation
  31738. //
  31739. // Topology is as below for sub-divide by 2
  31740. // vertex shown as v0,v1,v2
  31741. // interp index is i1 to progress in range [v0,v1[
  31742. // interp index is i2 to progress in range [v0,v2[
  31743. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31744. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31745. //
  31746. //
  31747. // i2 v2
  31748. // ^ ^
  31749. // / / \
  31750. // / / \
  31751. // / / \
  31752. // / / (0,1) \
  31753. // / #---------\
  31754. // / / \ (0,0)'/ \
  31755. // / / \ / \
  31756. // / / \ / \
  31757. // / / (0,0) \ / (1,0) \
  31758. // / #---------#---------\
  31759. // v0 v1
  31760. //
  31761. // --------------------> i1
  31762. //
  31763. // interp of (i1,i2):
  31764. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31765. // along i1 : lerp(x0,x1, i1/(S-i2))
  31766. //
  31767. // centroid of triangle is needed to get help normal computation
  31768. // (c1,c2) are used for centroid location
  31769. var interp_vertex = function (i1, i2, c1, c2) {
  31770. // vertex is interpolated from
  31771. // - face_vertex_pos[0..2]
  31772. // - face_vertex_uv[0..2]
  31773. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31774. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31775. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31776. pos_interp.normalize();
  31777. var vertex_normal;
  31778. if (flat) {
  31779. // in flat mode, recalculate normal as face centroid normal
  31780. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31781. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31782. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31783. }
  31784. else {
  31785. // in smooth mode, recalculate normal from each single vertex position
  31786. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31787. }
  31788. // Vertex normal need correction due to X,Y,Z radius scaling
  31789. vertex_normal.x /= radiusX;
  31790. vertex_normal.y /= radiusY;
  31791. vertex_normal.z /= radiusZ;
  31792. vertex_normal.normalize();
  31793. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31794. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31795. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31796. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31797. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31798. uvs.push(uv_interp.x, uv_interp.y);
  31799. // push each vertex has member of a face
  31800. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31801. indices.push(current_indice);
  31802. current_indice++;
  31803. };
  31804. for (var i2 = 0; i2 < subdivisions; i2++) {
  31805. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31806. // face : (i1,i2) for /\ :
  31807. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31808. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31809. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31810. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31811. if (i1 + i2 + 1 < subdivisions) {
  31812. // face : (i1,i2)' for \/ :
  31813. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31814. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31815. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31816. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31817. }
  31818. }
  31819. }
  31820. }
  31821. // Sides
  31822. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31823. // Result
  31824. var vertexData = new VertexData();
  31825. vertexData.indices = indices;
  31826. vertexData.positions = positions;
  31827. vertexData.normals = normals;
  31828. vertexData.uvs = uvs;
  31829. return vertexData;
  31830. };
  31831. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31832. VertexData.CreatePolyhedron = function (options) {
  31833. // provided polyhedron types :
  31834. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31835. // 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)
  31836. var polyhedra = [];
  31837. 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]] };
  31838. 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]] };
  31839. polyhedra[2] = {
  31840. 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]],
  31841. 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]]
  31842. };
  31843. polyhedra[3] = {
  31844. 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]],
  31845. 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]]
  31846. };
  31847. polyhedra[4] = {
  31848. 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]],
  31849. 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]]
  31850. };
  31851. 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]] };
  31852. 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]] };
  31853. 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]] };
  31854. 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]] };
  31855. 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]] };
  31856. 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]] };
  31857. 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]] };
  31858. 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]] };
  31859. 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]] };
  31860. polyhedra[14] = {
  31861. 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]],
  31862. 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]]
  31863. };
  31864. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31865. var size = options.size;
  31866. var sizeX = options.sizeX || size || 1;
  31867. var sizeY = options.sizeY || size || 1;
  31868. var sizeZ = options.sizeZ || size || 1;
  31869. var data = options.custom || polyhedra[type];
  31870. var nbfaces = data.face.length;
  31871. var faceUV = options.faceUV || new Array(nbfaces);
  31872. var faceColors = options.faceColors;
  31873. var flat = (options.flat === undefined) ? true : options.flat;
  31874. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31875. var positions = [];
  31876. var indices = [];
  31877. var normals = [];
  31878. var uvs = [];
  31879. var colors = [];
  31880. var index = 0;
  31881. var faceIdx = 0; // face cursor in the array "indexes"
  31882. var indexes = [];
  31883. var i = 0;
  31884. var f = 0;
  31885. var u, v, ang, x, y, tmp;
  31886. // default face colors and UV if undefined
  31887. if (flat) {
  31888. for (f = 0; f < nbfaces; f++) {
  31889. if (faceColors && faceColors[f] === undefined) {
  31890. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31891. }
  31892. if (faceUV && faceUV[f] === undefined) {
  31893. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31894. }
  31895. }
  31896. }
  31897. if (!flat) {
  31898. for (i = 0; i < data.vertex.length; i++) {
  31899. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31900. uvs.push(0, 0);
  31901. }
  31902. for (f = 0; f < nbfaces; f++) {
  31903. for (i = 0; i < data.face[f].length - 2; i++) {
  31904. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31905. }
  31906. }
  31907. }
  31908. else {
  31909. for (f = 0; f < nbfaces; f++) {
  31910. var fl = data.face[f].length; // number of vertices of the current face
  31911. ang = 2 * Math.PI / fl;
  31912. x = 0.5 * Math.tan(ang / 2);
  31913. y = 0.5;
  31914. // positions, uvs, colors
  31915. for (i = 0; i < fl; i++) {
  31916. // positions
  31917. 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);
  31918. indexes.push(index);
  31919. index++;
  31920. // uvs
  31921. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31922. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31923. uvs.push(u, v);
  31924. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31925. y = x * Math.sin(ang) + y * Math.cos(ang);
  31926. x = tmp;
  31927. // colors
  31928. if (faceColors) {
  31929. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31930. }
  31931. }
  31932. // indices from indexes
  31933. for (i = 0; i < fl - 2; i++) {
  31934. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31935. }
  31936. faceIdx += fl;
  31937. }
  31938. }
  31939. VertexData.ComputeNormals(positions, indices, normals);
  31940. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31941. var vertexData = new VertexData();
  31942. vertexData.positions = positions;
  31943. vertexData.indices = indices;
  31944. vertexData.normals = normals;
  31945. vertexData.uvs = uvs;
  31946. if (faceColors && flat) {
  31947. vertexData.colors = colors;
  31948. }
  31949. return vertexData;
  31950. };
  31951. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31952. VertexData.CreateTorusKnot = function (options) {
  31953. var indices = [];
  31954. var positions = [];
  31955. var normals = [];
  31956. var uvs = [];
  31957. var radius = options.radius || 2;
  31958. var tube = options.tube || 0.5;
  31959. var radialSegments = options.radialSegments || 32;
  31960. var tubularSegments = options.tubularSegments || 32;
  31961. var p = options.p || 2;
  31962. var q = options.q || 3;
  31963. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31964. // Helper
  31965. var getPos = function (angle) {
  31966. var cu = Math.cos(angle);
  31967. var su = Math.sin(angle);
  31968. var quOverP = q / p * angle;
  31969. var cs = Math.cos(quOverP);
  31970. var tx = radius * (2 + cs) * 0.5 * cu;
  31971. var ty = radius * (2 + cs) * su * 0.5;
  31972. var tz = radius * Math.sin(quOverP) * 0.5;
  31973. return new BABYLON.Vector3(tx, ty, tz);
  31974. };
  31975. // Vertices
  31976. var i;
  31977. var j;
  31978. for (i = 0; i <= radialSegments; i++) {
  31979. var modI = i % radialSegments;
  31980. var u = modI / radialSegments * 2 * p * Math.PI;
  31981. var p1 = getPos(u);
  31982. var p2 = getPos(u + 0.01);
  31983. var tang = p2.subtract(p1);
  31984. var n = p2.add(p1);
  31985. var bitan = BABYLON.Vector3.Cross(tang, n);
  31986. n = BABYLON.Vector3.Cross(bitan, tang);
  31987. bitan.normalize();
  31988. n.normalize();
  31989. for (j = 0; j < tubularSegments; j++) {
  31990. var modJ = j % tubularSegments;
  31991. var v = modJ / tubularSegments * 2 * Math.PI;
  31992. var cx = -tube * Math.cos(v);
  31993. var cy = tube * Math.sin(v);
  31994. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31995. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31996. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31997. uvs.push(i / radialSegments);
  31998. uvs.push(j / tubularSegments);
  31999. }
  32000. }
  32001. for (i = 0; i < radialSegments; i++) {
  32002. for (j = 0; j < tubularSegments; j++) {
  32003. var jNext = (j + 1) % tubularSegments;
  32004. var a = i * tubularSegments + j;
  32005. var b = (i + 1) * tubularSegments + j;
  32006. var c = (i + 1) * tubularSegments + jNext;
  32007. var d = i * tubularSegments + jNext;
  32008. indices.push(d);
  32009. indices.push(b);
  32010. indices.push(a);
  32011. indices.push(d);
  32012. indices.push(c);
  32013. indices.push(b);
  32014. }
  32015. }
  32016. // Normals
  32017. VertexData.ComputeNormals(positions, indices, normals);
  32018. // Sides
  32019. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32020. // Result
  32021. var vertexData = new VertexData();
  32022. vertexData.indices = indices;
  32023. vertexData.positions = positions;
  32024. vertexData.normals = normals;
  32025. vertexData.uvs = uvs;
  32026. return vertexData;
  32027. };
  32028. // Tools
  32029. /**
  32030. * @param {any} - positions (number[] or Float32Array)
  32031. * @param {any} - indices (number[] or Uint16Array)
  32032. * @param {any} - normals (number[] or Float32Array)
  32033. */
  32034. VertexData.ComputeNormals = function (positions, indices, normals) {
  32035. var index = 0;
  32036. var p1p2x = 0.0;
  32037. var p1p2y = 0.0;
  32038. var p1p2z = 0.0;
  32039. var p3p2x = 0.0;
  32040. var p3p2y = 0.0;
  32041. var p3p2z = 0.0;
  32042. var faceNormalx = 0.0;
  32043. var faceNormaly = 0.0;
  32044. var faceNormalz = 0.0;
  32045. var length = 0.0;
  32046. var i1 = 0;
  32047. var i2 = 0;
  32048. var i3 = 0;
  32049. for (index = 0; index < positions.length; index++) {
  32050. normals[index] = 0.0;
  32051. }
  32052. // indice triplet = 1 face
  32053. var nbFaces = indices.length / 3;
  32054. for (index = 0; index < nbFaces; index++) {
  32055. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  32056. i2 = indices[index * 3 + 1];
  32057. i3 = indices[index * 3 + 2];
  32058. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  32059. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  32060. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  32061. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  32062. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  32063. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  32064. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  32065. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  32066. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  32067. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32068. length = (length === 0) ? 1.0 : length;
  32069. faceNormalx /= length; // normalize this normal
  32070. faceNormaly /= length;
  32071. faceNormalz /= length;
  32072. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  32073. normals[i1 * 3 + 1] += faceNormaly;
  32074. normals[i1 * 3 + 2] += faceNormalz;
  32075. normals[i2 * 3] += faceNormalx;
  32076. normals[i2 * 3 + 1] += faceNormaly;
  32077. normals[i2 * 3 + 2] += faceNormalz;
  32078. normals[i3 * 3] += faceNormalx;
  32079. normals[i3 * 3 + 1] += faceNormaly;
  32080. normals[i3 * 3 + 2] += faceNormalz;
  32081. }
  32082. // last normalization of each normal
  32083. for (index = 0; index < normals.length / 3; index++) {
  32084. faceNormalx = normals[index * 3];
  32085. faceNormaly = normals[index * 3 + 1];
  32086. faceNormalz = normals[index * 3 + 2];
  32087. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32088. length = (length === 0) ? 1.0 : length;
  32089. faceNormalx /= length;
  32090. faceNormaly /= length;
  32091. faceNormalz /= length;
  32092. normals[index * 3] = faceNormalx;
  32093. normals[index * 3 + 1] = faceNormaly;
  32094. normals[index * 3 + 2] = faceNormalz;
  32095. }
  32096. };
  32097. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  32098. var li = indices.length;
  32099. var ln = normals.length;
  32100. var i;
  32101. var n;
  32102. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32103. switch (sideOrientation) {
  32104. case BABYLON.Mesh.FRONTSIDE:
  32105. // nothing changed
  32106. break;
  32107. case BABYLON.Mesh.BACKSIDE:
  32108. var tmp;
  32109. // indices
  32110. for (i = 0; i < li; i += 3) {
  32111. tmp = indices[i];
  32112. indices[i] = indices[i + 2];
  32113. indices[i + 2] = tmp;
  32114. }
  32115. // normals
  32116. for (n = 0; n < ln; n++) {
  32117. normals[n] = -normals[n];
  32118. }
  32119. break;
  32120. case BABYLON.Mesh.DOUBLESIDE:
  32121. // positions
  32122. var lp = positions.length;
  32123. var l = lp / 3;
  32124. for (var p = 0; p < lp; p++) {
  32125. positions[lp + p] = positions[p];
  32126. }
  32127. // indices
  32128. for (i = 0; i < li; i += 3) {
  32129. indices[i + li] = indices[i + 2] + l;
  32130. indices[i + 1 + li] = indices[i + 1] + l;
  32131. indices[i + 2 + li] = indices[i] + l;
  32132. }
  32133. // normals
  32134. for (n = 0; n < ln; n++) {
  32135. normals[ln + n] = -normals[n];
  32136. }
  32137. // uvs
  32138. var lu = uvs.length;
  32139. for (var u = 0; u < lu; u++) {
  32140. uvs[u + lu] = uvs[u];
  32141. }
  32142. break;
  32143. }
  32144. };
  32145. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32146. var vertexData = new VertexData();
  32147. // positions
  32148. var positions = parsedVertexData.positions;
  32149. if (positions) {
  32150. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32151. }
  32152. // normals
  32153. var normals = parsedVertexData.normals;
  32154. if (normals) {
  32155. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32156. }
  32157. // uvs
  32158. var uvs = parsedVertexData.uvs;
  32159. if (uvs) {
  32160. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32161. }
  32162. // uv2s
  32163. var uv2s = parsedVertexData.uv2s;
  32164. if (uv2s) {
  32165. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32166. }
  32167. // uv3s
  32168. var uv3s = parsedVertexData.uv3s;
  32169. if (uv3s) {
  32170. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32171. }
  32172. // uv4s
  32173. var uv4s = parsedVertexData.uv4s;
  32174. if (uv4s) {
  32175. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32176. }
  32177. // uv5s
  32178. var uv5s = parsedVertexData.uv5s;
  32179. if (uv5s) {
  32180. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32181. }
  32182. // uv6s
  32183. var uv6s = parsedVertexData.uv6s;
  32184. if (uv6s) {
  32185. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32186. }
  32187. // colors
  32188. var colors = parsedVertexData.colors;
  32189. if (colors) {
  32190. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32191. }
  32192. // matricesIndices
  32193. var matricesIndices = parsedVertexData.matricesIndices;
  32194. if (matricesIndices) {
  32195. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32196. }
  32197. // matricesWeights
  32198. var matricesWeights = parsedVertexData.matricesWeights;
  32199. if (matricesWeights) {
  32200. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32201. }
  32202. // indices
  32203. var indices = parsedVertexData.indices;
  32204. if (indices) {
  32205. vertexData.indices = indices;
  32206. }
  32207. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32208. };
  32209. return VertexData;
  32210. })();
  32211. BABYLON.VertexData = VertexData;
  32212. })(BABYLON || (BABYLON = {}));
  32213. var BABYLON;
  32214. (function (BABYLON) {
  32215. var Tags = (function () {
  32216. function Tags() {
  32217. }
  32218. Tags.EnableFor = function (obj) {
  32219. obj._tags = obj._tags || {};
  32220. obj.hasTags = function () {
  32221. return Tags.HasTags(obj);
  32222. };
  32223. obj.addTags = function (tagsString) {
  32224. return Tags.AddTagsTo(obj, tagsString);
  32225. };
  32226. obj.removeTags = function (tagsString) {
  32227. return Tags.RemoveTagsFrom(obj, tagsString);
  32228. };
  32229. obj.matchesTagsQuery = function (tagsQuery) {
  32230. return Tags.MatchesQuery(obj, tagsQuery);
  32231. };
  32232. };
  32233. Tags.DisableFor = function (obj) {
  32234. delete obj._tags;
  32235. delete obj.hasTags;
  32236. delete obj.addTags;
  32237. delete obj.removeTags;
  32238. delete obj.matchesTagsQuery;
  32239. };
  32240. Tags.HasTags = function (obj) {
  32241. if (!obj._tags) {
  32242. return false;
  32243. }
  32244. return !BABYLON.Tools.IsEmpty(obj._tags);
  32245. };
  32246. Tags.GetTags = function (obj, asString) {
  32247. if (asString === void 0) { asString = true; }
  32248. if (!obj._tags) {
  32249. return null;
  32250. }
  32251. if (asString) {
  32252. var tagsArray = [];
  32253. for (var tag in obj._tags) {
  32254. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  32255. tagsArray.push(tag);
  32256. }
  32257. }
  32258. return tagsArray.join(" ");
  32259. }
  32260. else {
  32261. return obj._tags;
  32262. }
  32263. };
  32264. // the tags 'true' and 'false' are reserved and cannot be used as tags
  32265. // a tag cannot start with '||', '&&', and '!'
  32266. // it cannot contain whitespaces
  32267. Tags.AddTagsTo = function (obj, tagsString) {
  32268. if (!tagsString) {
  32269. return;
  32270. }
  32271. if (typeof tagsString !== "string") {
  32272. return;
  32273. }
  32274. var tags = tagsString.split(" ");
  32275. for (var t in tags) {
  32276. Tags._AddTagTo(obj, tags[t]);
  32277. }
  32278. };
  32279. Tags._AddTagTo = function (obj, tag) {
  32280. tag = tag.trim();
  32281. if (tag === "" || tag === "true" || tag === "false") {
  32282. return;
  32283. }
  32284. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  32285. return;
  32286. }
  32287. Tags.EnableFor(obj);
  32288. obj._tags[tag] = true;
  32289. };
  32290. Tags.RemoveTagsFrom = function (obj, tagsString) {
  32291. if (!Tags.HasTags(obj)) {
  32292. return;
  32293. }
  32294. var tags = tagsString.split(" ");
  32295. for (var t in tags) {
  32296. Tags._RemoveTagFrom(obj, tags[t]);
  32297. }
  32298. };
  32299. Tags._RemoveTagFrom = function (obj, tag) {
  32300. delete obj._tags[tag];
  32301. };
  32302. Tags.MatchesQuery = function (obj, tagsQuery) {
  32303. if (tagsQuery === undefined) {
  32304. return true;
  32305. }
  32306. if (tagsQuery === "") {
  32307. return Tags.HasTags(obj);
  32308. }
  32309. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  32310. };
  32311. return Tags;
  32312. })();
  32313. BABYLON.Tags = Tags;
  32314. })(BABYLON || (BABYLON = {}));
  32315. var BABYLON;
  32316. (function (BABYLON) {
  32317. var Internals;
  32318. (function (Internals) {
  32319. var AndOrNotEvaluator = (function () {
  32320. function AndOrNotEvaluator() {
  32321. }
  32322. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  32323. if (!query.match(/\([^\(\)]*\)/g)) {
  32324. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  32325. }
  32326. else {
  32327. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  32328. // remove parenthesis
  32329. r = r.slice(1, r.length - 1);
  32330. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  32331. });
  32332. }
  32333. if (query === "true") {
  32334. return true;
  32335. }
  32336. if (query === "false") {
  32337. return false;
  32338. }
  32339. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  32340. };
  32341. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  32342. evaluateCallback = evaluateCallback || (function (r) {
  32343. return r === "true" ? true : false;
  32344. });
  32345. var result;
  32346. var or = parenthesisContent.split("||");
  32347. for (var i in or) {
  32348. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  32349. var and = ori.split("&&");
  32350. if (and.length > 1) {
  32351. for (var j = 0; j < and.length; ++j) {
  32352. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  32353. if (andj !== "true" && andj !== "false") {
  32354. if (andj[0] === "!") {
  32355. result = !evaluateCallback(andj.substring(1));
  32356. }
  32357. else {
  32358. result = evaluateCallback(andj);
  32359. }
  32360. }
  32361. else {
  32362. result = andj === "true" ? true : false;
  32363. }
  32364. if (!result) {
  32365. ori = "false";
  32366. break;
  32367. }
  32368. }
  32369. }
  32370. if (result || ori === "true") {
  32371. result = true;
  32372. break;
  32373. }
  32374. // result equals false (or undefined)
  32375. if (ori !== "true" && ori !== "false") {
  32376. if (ori[0] === "!") {
  32377. result = !evaluateCallback(ori.substring(1));
  32378. }
  32379. else {
  32380. result = evaluateCallback(ori);
  32381. }
  32382. }
  32383. else {
  32384. result = ori === "true" ? true : false;
  32385. }
  32386. }
  32387. // the whole parenthesis scope is replaced by 'true' or 'false'
  32388. return result ? "true" : "false";
  32389. };
  32390. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  32391. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  32392. // remove whitespaces
  32393. r = r.replace(/[\s]/g, function () { return ""; });
  32394. return r.length % 2 ? "!" : "";
  32395. });
  32396. booleanString = booleanString.trim();
  32397. if (booleanString === "!true") {
  32398. booleanString = "false";
  32399. }
  32400. else if (booleanString === "!false") {
  32401. booleanString = "true";
  32402. }
  32403. return booleanString;
  32404. };
  32405. return AndOrNotEvaluator;
  32406. })();
  32407. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  32408. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32409. })(BABYLON || (BABYLON = {}));
  32410. var BABYLON;
  32411. (function (BABYLON) {
  32412. var PostProcessRenderPass = (function () {
  32413. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  32414. this._enabled = true;
  32415. this._refCount = 0;
  32416. this._name = name;
  32417. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  32418. this.setRenderList(renderList);
  32419. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  32420. this._renderTexture.onAfterRenderObservable.add(afterRender);
  32421. this._scene = scene;
  32422. this._renderList = renderList;
  32423. }
  32424. // private
  32425. PostProcessRenderPass.prototype._incRefCount = function () {
  32426. if (this._refCount === 0) {
  32427. this._scene.customRenderTargets.push(this._renderTexture);
  32428. }
  32429. return ++this._refCount;
  32430. };
  32431. PostProcessRenderPass.prototype._decRefCount = function () {
  32432. this._refCount--;
  32433. if (this._refCount <= 0) {
  32434. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  32435. }
  32436. return this._refCount;
  32437. };
  32438. PostProcessRenderPass.prototype._update = function () {
  32439. this.setRenderList(this._renderList);
  32440. };
  32441. // public
  32442. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  32443. this._renderTexture.renderList = renderList;
  32444. };
  32445. PostProcessRenderPass.prototype.getRenderTexture = function () {
  32446. return this._renderTexture;
  32447. };
  32448. return PostProcessRenderPass;
  32449. })();
  32450. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  32451. })(BABYLON || (BABYLON = {}));
  32452. var BABYLON;
  32453. (function (BABYLON) {
  32454. var PostProcessRenderEffect = (function () {
  32455. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  32456. this._engine = engine;
  32457. this._name = name;
  32458. this._singleInstance = singleInstance || true;
  32459. this._getPostProcess = getPostProcess;
  32460. this._cameras = [];
  32461. this._indicesForCamera = [];
  32462. this._postProcesses = {};
  32463. this._renderPasses = {};
  32464. this._renderEffectAsPasses = {};
  32465. }
  32466. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  32467. get: function () {
  32468. for (var index in this._postProcesses) {
  32469. if (!this._postProcesses[index].isSupported) {
  32470. return false;
  32471. }
  32472. }
  32473. return true;
  32474. },
  32475. enumerable: true,
  32476. configurable: true
  32477. });
  32478. PostProcessRenderEffect.prototype._update = function () {
  32479. for (var renderPassName in this._renderPasses) {
  32480. this._renderPasses[renderPassName]._update();
  32481. }
  32482. };
  32483. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  32484. this._renderPasses[renderPass._name] = renderPass;
  32485. this._linkParameters();
  32486. };
  32487. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  32488. delete this._renderPasses[renderPass._name];
  32489. this._linkParameters();
  32490. };
  32491. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  32492. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  32493. this._linkParameters();
  32494. };
  32495. PostProcessRenderEffect.prototype.getPass = function (passName) {
  32496. for (var renderPassName in this._renderPasses) {
  32497. if (renderPassName === passName) {
  32498. return this._renderPasses[passName];
  32499. }
  32500. }
  32501. };
  32502. PostProcessRenderEffect.prototype.emptyPasses = function () {
  32503. this._renderPasses = {};
  32504. this._linkParameters();
  32505. };
  32506. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  32507. var cameraKey;
  32508. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32509. for (var i = 0; i < _cam.length; i++) {
  32510. var camera = _cam[i];
  32511. var cameraName = camera.name;
  32512. if (this._singleInstance) {
  32513. cameraKey = 0;
  32514. }
  32515. else {
  32516. cameraKey = cameraName;
  32517. }
  32518. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  32519. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  32520. if (!this._indicesForCamera[cameraName]) {
  32521. this._indicesForCamera[cameraName] = [];
  32522. }
  32523. this._indicesForCamera[cameraName].push(index);
  32524. if (this._cameras.indexOf(camera) === -1) {
  32525. this._cameras[cameraName] = camera;
  32526. }
  32527. for (var passName in this._renderPasses) {
  32528. this._renderPasses[passName]._incRefCount();
  32529. }
  32530. }
  32531. this._linkParameters();
  32532. };
  32533. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  32534. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32535. for (var i = 0; i < _cam.length; i++) {
  32536. var camera = _cam[i];
  32537. var cameraName = camera.name;
  32538. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32539. var index = this._cameras.indexOf(cameraName);
  32540. this._indicesForCamera.splice(index, 1);
  32541. this._cameras.splice(index, 1);
  32542. for (var passName in this._renderPasses) {
  32543. this._renderPasses[passName]._decRefCount();
  32544. }
  32545. }
  32546. };
  32547. PostProcessRenderEffect.prototype._enable = function (cameras) {
  32548. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32549. for (var i = 0; i < _cam.length; i++) {
  32550. var camera = _cam[i];
  32551. var cameraName = camera.name;
  32552. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  32553. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  32554. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  32555. }
  32556. }
  32557. for (var passName in this._renderPasses) {
  32558. this._renderPasses[passName]._incRefCount();
  32559. }
  32560. }
  32561. };
  32562. PostProcessRenderEffect.prototype._disable = function (cameras) {
  32563. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32564. for (var i = 0; i < _cam.length; i++) {
  32565. var camera = _cam[i];
  32566. var cameraName = camera.Name;
  32567. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32568. for (var passName in this._renderPasses) {
  32569. this._renderPasses[passName]._decRefCount();
  32570. }
  32571. }
  32572. };
  32573. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  32574. if (this._singleInstance) {
  32575. return this._postProcesses[0];
  32576. }
  32577. else {
  32578. return this._postProcesses[camera.name];
  32579. }
  32580. };
  32581. PostProcessRenderEffect.prototype._linkParameters = function () {
  32582. var _this = this;
  32583. for (var index in this._postProcesses) {
  32584. if (this.applyParameters) {
  32585. this.applyParameters(this._postProcesses[index]);
  32586. }
  32587. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  32588. _this._linkTextures(effect);
  32589. });
  32590. }
  32591. };
  32592. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  32593. for (var renderPassName in this._renderPasses) {
  32594. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  32595. }
  32596. for (var renderEffectName in this._renderEffectAsPasses) {
  32597. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  32598. }
  32599. };
  32600. return PostProcessRenderEffect;
  32601. })();
  32602. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  32603. })(BABYLON || (BABYLON = {}));
  32604. var BABYLON;
  32605. (function (BABYLON) {
  32606. var PostProcessRenderPipeline = (function () {
  32607. function PostProcessRenderPipeline(engine, name) {
  32608. this._engine = engine;
  32609. this._name = name;
  32610. this._renderEffects = {};
  32611. this._renderEffectsForIsolatedPass = {};
  32612. this._cameras = [];
  32613. }
  32614. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  32615. get: function () {
  32616. for (var renderEffectName in this._renderEffects) {
  32617. if (!this._renderEffects[renderEffectName].isSupported) {
  32618. return false;
  32619. }
  32620. }
  32621. return true;
  32622. },
  32623. enumerable: true,
  32624. configurable: true
  32625. });
  32626. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  32627. this._renderEffects[renderEffect._name] = renderEffect;
  32628. };
  32629. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  32630. var renderEffects = this._renderEffects[renderEffectName];
  32631. if (!renderEffects) {
  32632. return;
  32633. }
  32634. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32635. };
  32636. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  32637. var renderEffects = this._renderEffects[renderEffectName];
  32638. if (!renderEffects) {
  32639. return;
  32640. }
  32641. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32642. };
  32643. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  32644. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32645. var indicesToDelete = [];
  32646. var i;
  32647. for (i = 0; i < _cam.length; i++) {
  32648. var camera = _cam[i];
  32649. var cameraName = camera.name;
  32650. if (this._cameras.indexOf(camera) === -1) {
  32651. this._cameras[cameraName] = camera;
  32652. }
  32653. else if (unique) {
  32654. indicesToDelete.push(i);
  32655. }
  32656. }
  32657. for (i = 0; i < indicesToDelete.length; i++) {
  32658. cameras.splice(indicesToDelete[i], 1);
  32659. }
  32660. for (var renderEffectName in this._renderEffects) {
  32661. this._renderEffects[renderEffectName]._attachCameras(_cam);
  32662. }
  32663. };
  32664. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  32665. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32666. for (var renderEffectName in this._renderEffects) {
  32667. this._renderEffects[renderEffectName]._detachCameras(_cam);
  32668. }
  32669. for (var i = 0; i < _cam.length; i++) {
  32670. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  32671. }
  32672. };
  32673. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  32674. var _this = this;
  32675. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32676. var pass = null;
  32677. var renderEffectName;
  32678. for (renderEffectName in this._renderEffects) {
  32679. pass = this._renderEffects[renderEffectName].getPass(passName);
  32680. if (pass != null) {
  32681. break;
  32682. }
  32683. }
  32684. if (pass === null) {
  32685. return;
  32686. }
  32687. for (renderEffectName in this._renderEffects) {
  32688. this._renderEffects[renderEffectName]._disable(_cam);
  32689. }
  32690. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  32691. for (var i = 0; i < _cam.length; i++) {
  32692. var camera = _cam[i];
  32693. var cameraName = camera.name;
  32694. 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); });
  32695. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  32696. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  32697. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  32698. }
  32699. };
  32700. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  32701. var _this = this;
  32702. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32703. for (var i = 0; i < _cam.length; i++) {
  32704. var camera = _cam[i];
  32705. var cameraName = camera.name;
  32706. 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); });
  32707. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  32708. }
  32709. for (var renderEffectName in this._renderEffects) {
  32710. this._renderEffects[renderEffectName]._enable(_cam);
  32711. }
  32712. };
  32713. PostProcessRenderPipeline.prototype._update = function () {
  32714. for (var renderEffectName in this._renderEffects) {
  32715. this._renderEffects[renderEffectName]._update();
  32716. }
  32717. for (var i = 0; i < this._cameras.length; i++) {
  32718. var cameraName = this._cameras[i].name;
  32719. if (this._renderEffectsForIsolatedPass[cameraName]) {
  32720. this._renderEffectsForIsolatedPass[cameraName]._update();
  32721. }
  32722. }
  32723. };
  32724. PostProcessRenderPipeline.prototype.dispose = function () {
  32725. // Must be implemented by children
  32726. };
  32727. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  32728. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  32729. return PostProcessRenderPipeline;
  32730. })();
  32731. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  32732. })(BABYLON || (BABYLON = {}));
  32733. var BABYLON;
  32734. (function (BABYLON) {
  32735. var PostProcessRenderPipelineManager = (function () {
  32736. function PostProcessRenderPipelineManager() {
  32737. this._renderPipelines = {};
  32738. }
  32739. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  32740. this._renderPipelines[renderPipeline._name] = renderPipeline;
  32741. };
  32742. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  32743. var renderPipeline = this._renderPipelines[renderPipelineName];
  32744. if (!renderPipeline) {
  32745. return;
  32746. }
  32747. renderPipeline._attachCameras(cameras, unique);
  32748. };
  32749. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  32750. var renderPipeline = this._renderPipelines[renderPipelineName];
  32751. if (!renderPipeline) {
  32752. return;
  32753. }
  32754. renderPipeline._detachCameras(cameras);
  32755. };
  32756. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32757. var renderPipeline = this._renderPipelines[renderPipelineName];
  32758. if (!renderPipeline) {
  32759. return;
  32760. }
  32761. renderPipeline._enableEffect(renderEffectName, cameras);
  32762. };
  32763. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32764. var renderPipeline = this._renderPipelines[renderPipelineName];
  32765. if (!renderPipeline) {
  32766. return;
  32767. }
  32768. renderPipeline._disableEffect(renderEffectName, cameras);
  32769. };
  32770. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  32771. var renderPipeline = this._renderPipelines[renderPipelineName];
  32772. if (!renderPipeline) {
  32773. return;
  32774. }
  32775. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  32776. };
  32777. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  32778. var renderPipeline = this._renderPipelines[renderPipelineName];
  32779. if (!renderPipeline) {
  32780. return;
  32781. }
  32782. renderPipeline._disableDisplayOnlyPass(cameras);
  32783. };
  32784. PostProcessRenderPipelineManager.prototype.update = function () {
  32785. for (var renderPipelineName in this._renderPipelines) {
  32786. var pipeline = this._renderPipelines[renderPipelineName];
  32787. if (!pipeline.isSupported) {
  32788. pipeline.dispose();
  32789. delete this._renderPipelines[renderPipelineName];
  32790. }
  32791. else {
  32792. pipeline._update();
  32793. }
  32794. }
  32795. };
  32796. return PostProcessRenderPipelineManager;
  32797. })();
  32798. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  32799. })(BABYLON || (BABYLON = {}));
  32800. var BABYLON;
  32801. (function (BABYLON) {
  32802. var BoundingBoxRenderer = (function () {
  32803. function BoundingBoxRenderer(scene) {
  32804. this.frontColor = new BABYLON.Color3(1, 1, 1);
  32805. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  32806. this.showBackLines = true;
  32807. this.renderList = new BABYLON.SmartArray(32);
  32808. this._vertexBuffers = {};
  32809. this._scene = scene;
  32810. }
  32811. BoundingBoxRenderer.prototype._prepareRessources = function () {
  32812. if (this._colorShader) {
  32813. return;
  32814. }
  32815. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  32816. attributes: [BABYLON.VertexBuffer.PositionKind],
  32817. uniforms: ["worldViewProjection", "color"]
  32818. });
  32819. var engine = this._scene.getEngine();
  32820. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  32821. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  32822. 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]);
  32823. };
  32824. BoundingBoxRenderer.prototype.reset = function () {
  32825. this.renderList.reset();
  32826. };
  32827. BoundingBoxRenderer.prototype.render = function () {
  32828. if (this.renderList.length === 0) {
  32829. return;
  32830. }
  32831. this._prepareRessources();
  32832. if (!this._colorShader.isReady()) {
  32833. return;
  32834. }
  32835. var engine = this._scene.getEngine();
  32836. engine.setDepthWrite(false);
  32837. this._colorShader._preBind();
  32838. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  32839. var boundingBox = this.renderList.data[boundingBoxIndex];
  32840. var min = boundingBox.minimum;
  32841. var max = boundingBox.maximum;
  32842. var diff = max.subtract(min);
  32843. var median = min.add(diff.scale(0.5));
  32844. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  32845. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  32846. .multiply(boundingBox.getWorldMatrix());
  32847. // VBOs
  32848. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  32849. if (this.showBackLines) {
  32850. // Back
  32851. engine.setDepthFunctionToGreaterOrEqual();
  32852. this._scene.resetCachedMaterial();
  32853. this._colorShader.setColor4("color", this.backColor.toColor4());
  32854. this._colorShader.bind(worldMatrix);
  32855. // Draw order
  32856. engine.draw(false, 0, 24);
  32857. }
  32858. // Front
  32859. engine.setDepthFunctionToLess();
  32860. this._scene.resetCachedMaterial();
  32861. this._colorShader.setColor4("color", this.frontColor.toColor4());
  32862. this._colorShader.bind(worldMatrix);
  32863. // Draw order
  32864. engine.draw(false, 0, 24);
  32865. }
  32866. this._colorShader.unbind();
  32867. engine.setDepthFunctionToLessOrEqual();
  32868. engine.setDepthWrite(true);
  32869. };
  32870. BoundingBoxRenderer.prototype.dispose = function () {
  32871. if (!this._colorShader) {
  32872. return;
  32873. }
  32874. this._colorShader.dispose();
  32875. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32876. if (buffer) {
  32877. buffer.dispose();
  32878. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32879. }
  32880. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32881. };
  32882. return BoundingBoxRenderer;
  32883. })();
  32884. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  32885. })(BABYLON || (BABYLON = {}));
  32886. var BABYLON;
  32887. (function (BABYLON) {
  32888. var Condition = (function () {
  32889. function Condition(actionManager) {
  32890. this._actionManager = actionManager;
  32891. }
  32892. Condition.prototype.isValid = function () {
  32893. return true;
  32894. };
  32895. Condition.prototype._getProperty = function (propertyPath) {
  32896. return this._actionManager._getProperty(propertyPath);
  32897. };
  32898. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  32899. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32900. };
  32901. Condition.prototype.serialize = function () {
  32902. };
  32903. Condition.prototype._serialize = function (serializedCondition) {
  32904. return {
  32905. type: 2,
  32906. children: [],
  32907. name: serializedCondition.name,
  32908. properties: serializedCondition.properties
  32909. };
  32910. };
  32911. return Condition;
  32912. })();
  32913. BABYLON.Condition = Condition;
  32914. var ValueCondition = (function (_super) {
  32915. __extends(ValueCondition, _super);
  32916. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  32917. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  32918. _super.call(this, actionManager);
  32919. this.propertyPath = propertyPath;
  32920. this.value = value;
  32921. this.operator = operator;
  32922. this._target = target;
  32923. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  32924. this._property = this._getProperty(this.propertyPath);
  32925. }
  32926. Object.defineProperty(ValueCondition, "IsEqual", {
  32927. get: function () {
  32928. return ValueCondition._IsEqual;
  32929. },
  32930. enumerable: true,
  32931. configurable: true
  32932. });
  32933. Object.defineProperty(ValueCondition, "IsDifferent", {
  32934. get: function () {
  32935. return ValueCondition._IsDifferent;
  32936. },
  32937. enumerable: true,
  32938. configurable: true
  32939. });
  32940. Object.defineProperty(ValueCondition, "IsGreater", {
  32941. get: function () {
  32942. return ValueCondition._IsGreater;
  32943. },
  32944. enumerable: true,
  32945. configurable: true
  32946. });
  32947. Object.defineProperty(ValueCondition, "IsLesser", {
  32948. get: function () {
  32949. return ValueCondition._IsLesser;
  32950. },
  32951. enumerable: true,
  32952. configurable: true
  32953. });
  32954. // Methods
  32955. ValueCondition.prototype.isValid = function () {
  32956. switch (this.operator) {
  32957. case ValueCondition.IsGreater:
  32958. return this._effectiveTarget[this._property] > this.value;
  32959. case ValueCondition.IsLesser:
  32960. return this._effectiveTarget[this._property] < this.value;
  32961. case ValueCondition.IsEqual:
  32962. case ValueCondition.IsDifferent:
  32963. var check;
  32964. if (this.value.equals) {
  32965. check = this.value.equals(this._effectiveTarget[this._property]);
  32966. }
  32967. else {
  32968. check = this.value === this._effectiveTarget[this._property];
  32969. }
  32970. return this.operator === ValueCondition.IsEqual ? check : !check;
  32971. }
  32972. return false;
  32973. };
  32974. ValueCondition.prototype.serialize = function () {
  32975. return this._serialize({
  32976. name: "ValueCondition",
  32977. properties: [
  32978. BABYLON.Action._GetTargetProperty(this._target),
  32979. { name: "propertyPath", value: this.propertyPath },
  32980. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32981. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  32982. ]
  32983. });
  32984. };
  32985. ValueCondition.GetOperatorName = function (operator) {
  32986. switch (operator) {
  32987. case ValueCondition._IsEqual: return "IsEqual";
  32988. case ValueCondition._IsDifferent: return "IsDifferent";
  32989. case ValueCondition._IsGreater: return "IsGreater";
  32990. case ValueCondition._IsLesser: return "IsLesser";
  32991. default: return "";
  32992. }
  32993. };
  32994. // Statics
  32995. ValueCondition._IsEqual = 0;
  32996. ValueCondition._IsDifferent = 1;
  32997. ValueCondition._IsGreater = 2;
  32998. ValueCondition._IsLesser = 3;
  32999. return ValueCondition;
  33000. })(Condition);
  33001. BABYLON.ValueCondition = ValueCondition;
  33002. var PredicateCondition = (function (_super) {
  33003. __extends(PredicateCondition, _super);
  33004. function PredicateCondition(actionManager, predicate) {
  33005. _super.call(this, actionManager);
  33006. this.predicate = predicate;
  33007. }
  33008. PredicateCondition.prototype.isValid = function () {
  33009. return this.predicate();
  33010. };
  33011. return PredicateCondition;
  33012. })(Condition);
  33013. BABYLON.PredicateCondition = PredicateCondition;
  33014. var StateCondition = (function (_super) {
  33015. __extends(StateCondition, _super);
  33016. function StateCondition(actionManager, target, value) {
  33017. _super.call(this, actionManager);
  33018. this.value = value;
  33019. this._target = target;
  33020. }
  33021. // Methods
  33022. StateCondition.prototype.isValid = function () {
  33023. return this._target.state === this.value;
  33024. };
  33025. StateCondition.prototype.serialize = function () {
  33026. return this._serialize({
  33027. name: "StateCondition",
  33028. properties: [
  33029. BABYLON.Action._GetTargetProperty(this._target),
  33030. { name: "value", value: this.value }
  33031. ]
  33032. });
  33033. };
  33034. return StateCondition;
  33035. })(Condition);
  33036. BABYLON.StateCondition = StateCondition;
  33037. })(BABYLON || (BABYLON = {}));
  33038. var BABYLON;
  33039. (function (BABYLON) {
  33040. var Action = (function () {
  33041. function Action(triggerOptions, condition) {
  33042. this.triggerOptions = triggerOptions;
  33043. if (triggerOptions.parameter) {
  33044. this.trigger = triggerOptions.trigger;
  33045. this._triggerParameter = triggerOptions.parameter;
  33046. }
  33047. else {
  33048. this.trigger = triggerOptions;
  33049. }
  33050. this._nextActiveAction = this;
  33051. this._condition = condition;
  33052. }
  33053. // Methods
  33054. Action.prototype._prepare = function () {
  33055. };
  33056. Action.prototype.getTriggerParameter = function () {
  33057. return this._triggerParameter;
  33058. };
  33059. Action.prototype._executeCurrent = function (evt) {
  33060. if (this._nextActiveAction._condition) {
  33061. var condition = this._nextActiveAction._condition;
  33062. var currentRenderId = this._actionManager.getScene().getRenderId();
  33063. // We cache the current evaluation for the current frame
  33064. if (condition._evaluationId === currentRenderId) {
  33065. if (!condition._currentResult) {
  33066. return;
  33067. }
  33068. }
  33069. else {
  33070. condition._evaluationId = currentRenderId;
  33071. if (!condition.isValid()) {
  33072. condition._currentResult = false;
  33073. return;
  33074. }
  33075. condition._currentResult = true;
  33076. }
  33077. }
  33078. this._nextActiveAction.execute(evt);
  33079. this.skipToNextActiveAction();
  33080. };
  33081. Action.prototype.execute = function (evt) {
  33082. };
  33083. Action.prototype.skipToNextActiveAction = function () {
  33084. if (this._nextActiveAction._child) {
  33085. if (!this._nextActiveAction._child._actionManager) {
  33086. this._nextActiveAction._child._actionManager = this._actionManager;
  33087. }
  33088. this._nextActiveAction = this._nextActiveAction._child;
  33089. }
  33090. else {
  33091. this._nextActiveAction = this;
  33092. }
  33093. };
  33094. Action.prototype.then = function (action) {
  33095. this._child = action;
  33096. action._actionManager = this._actionManager;
  33097. action._prepare();
  33098. return action;
  33099. };
  33100. Action.prototype._getProperty = function (propertyPath) {
  33101. return this._actionManager._getProperty(propertyPath);
  33102. };
  33103. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  33104. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33105. };
  33106. Action.prototype.serialize = function (parent) {
  33107. };
  33108. // Called by BABYLON.Action objects in serialize(...). Internal use
  33109. Action.prototype._serialize = function (serializedAction, parent) {
  33110. var serializationObject = {
  33111. type: 1,
  33112. children: [],
  33113. name: serializedAction.name,
  33114. properties: serializedAction.properties || []
  33115. };
  33116. // Serialize child
  33117. if (this._child) {
  33118. this._child.serialize(serializationObject);
  33119. }
  33120. // Check if "this" has a condition
  33121. if (this._condition) {
  33122. var serializedCondition = this._condition.serialize();
  33123. serializedCondition.children.push(serializationObject);
  33124. if (parent) {
  33125. parent.children.push(serializedCondition);
  33126. }
  33127. return serializedCondition;
  33128. }
  33129. if (parent) {
  33130. parent.children.push(serializationObject);
  33131. }
  33132. return serializationObject;
  33133. };
  33134. Action._SerializeValueAsString = function (value) {
  33135. if (typeof value === "number") {
  33136. return value.toString();
  33137. }
  33138. if (typeof value === "boolean") {
  33139. return value ? "true" : "false";
  33140. }
  33141. if (value instanceof BABYLON.Vector2) {
  33142. return value.x + ", " + value.y;
  33143. }
  33144. if (value instanceof BABYLON.Vector3) {
  33145. return value.x + ", " + value.y + ", " + value.z;
  33146. }
  33147. if (value instanceof BABYLON.Color3) {
  33148. return value.r + ", " + value.g + ", " + value.b;
  33149. }
  33150. if (value instanceof BABYLON.Color4) {
  33151. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  33152. }
  33153. return value; // string
  33154. };
  33155. Action._GetTargetProperty = function (target) {
  33156. return {
  33157. name: "target",
  33158. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  33159. : target instanceof BABYLON.Light ? "LightProperties"
  33160. : target instanceof BABYLON.Camera ? "CameraProperties"
  33161. : "SceneProperties",
  33162. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  33163. };
  33164. };
  33165. return Action;
  33166. })();
  33167. BABYLON.Action = Action;
  33168. })(BABYLON || (BABYLON = {}));
  33169. var BABYLON;
  33170. (function (BABYLON) {
  33171. /**
  33172. * ActionEvent is the event beint sent when an action is triggered.
  33173. */
  33174. var ActionEvent = (function () {
  33175. /**
  33176. * @constructor
  33177. * @param source The mesh or sprite that triggered the action.
  33178. * @param pointerX The X mouse cursor position at the time of the event
  33179. * @param pointerY The Y mouse cursor position at the time of the event
  33180. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  33181. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  33182. */
  33183. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  33184. this.source = source;
  33185. this.pointerX = pointerX;
  33186. this.pointerY = pointerY;
  33187. this.meshUnderPointer = meshUnderPointer;
  33188. this.sourceEvent = sourceEvent;
  33189. this.additionalData = additionalData;
  33190. }
  33191. /**
  33192. * Helper function to auto-create an ActionEvent from a source mesh.
  33193. * @param source The source mesh that triggered the event
  33194. * @param evt {Event} The original (browser) event
  33195. */
  33196. ActionEvent.CreateNew = function (source, evt, additionalData) {
  33197. var scene = source.getScene();
  33198. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33199. };
  33200. /**
  33201. * Helper function to auto-create an ActionEvent from a source mesh.
  33202. * @param source The source sprite that triggered the event
  33203. * @param scene Scene associated with the sprite
  33204. * @param evt {Event} The original (browser) event
  33205. */
  33206. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  33207. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33208. };
  33209. /**
  33210. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  33211. * @param scene the scene where the event occurred
  33212. * @param evt {Event} The original (browser) event
  33213. */
  33214. ActionEvent.CreateNewFromScene = function (scene, evt) {
  33215. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  33216. };
  33217. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  33218. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  33219. };
  33220. return ActionEvent;
  33221. })();
  33222. BABYLON.ActionEvent = ActionEvent;
  33223. /**
  33224. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  33225. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  33226. */
  33227. var ActionManager = (function () {
  33228. function ActionManager(scene) {
  33229. // Members
  33230. this.actions = new Array();
  33231. this._scene = scene;
  33232. scene._actionManagers.push(this);
  33233. }
  33234. Object.defineProperty(ActionManager, "NothingTrigger", {
  33235. get: function () {
  33236. return ActionManager._NothingTrigger;
  33237. },
  33238. enumerable: true,
  33239. configurable: true
  33240. });
  33241. Object.defineProperty(ActionManager, "OnPickTrigger", {
  33242. get: function () {
  33243. return ActionManager._OnPickTrigger;
  33244. },
  33245. enumerable: true,
  33246. configurable: true
  33247. });
  33248. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  33249. get: function () {
  33250. return ActionManager._OnLeftPickTrigger;
  33251. },
  33252. enumerable: true,
  33253. configurable: true
  33254. });
  33255. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  33256. get: function () {
  33257. return ActionManager._OnRightPickTrigger;
  33258. },
  33259. enumerable: true,
  33260. configurable: true
  33261. });
  33262. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  33263. get: function () {
  33264. return ActionManager._OnCenterPickTrigger;
  33265. },
  33266. enumerable: true,
  33267. configurable: true
  33268. });
  33269. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  33270. get: function () {
  33271. return ActionManager._OnPickDownTrigger;
  33272. },
  33273. enumerable: true,
  33274. configurable: true
  33275. });
  33276. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  33277. get: function () {
  33278. return ActionManager._OnPickUpTrigger;
  33279. },
  33280. enumerable: true,
  33281. configurable: true
  33282. });
  33283. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  33284. /// This trigger will only be raised if you also declared a OnPickDown
  33285. get: function () {
  33286. return ActionManager._OnPickOutTrigger;
  33287. },
  33288. enumerable: true,
  33289. configurable: true
  33290. });
  33291. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  33292. get: function () {
  33293. return ActionManager._OnLongPressTrigger;
  33294. },
  33295. enumerable: true,
  33296. configurable: true
  33297. });
  33298. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  33299. get: function () {
  33300. return ActionManager._OnPointerOverTrigger;
  33301. },
  33302. enumerable: true,
  33303. configurable: true
  33304. });
  33305. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  33306. get: function () {
  33307. return ActionManager._OnPointerOutTrigger;
  33308. },
  33309. enumerable: true,
  33310. configurable: true
  33311. });
  33312. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  33313. get: function () {
  33314. return ActionManager._OnEveryFrameTrigger;
  33315. },
  33316. enumerable: true,
  33317. configurable: true
  33318. });
  33319. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  33320. get: function () {
  33321. return ActionManager._OnIntersectionEnterTrigger;
  33322. },
  33323. enumerable: true,
  33324. configurable: true
  33325. });
  33326. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  33327. get: function () {
  33328. return ActionManager._OnIntersectionExitTrigger;
  33329. },
  33330. enumerable: true,
  33331. configurable: true
  33332. });
  33333. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  33334. get: function () {
  33335. return ActionManager._OnKeyDownTrigger;
  33336. },
  33337. enumerable: true,
  33338. configurable: true
  33339. });
  33340. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  33341. get: function () {
  33342. return ActionManager._OnKeyUpTrigger;
  33343. },
  33344. enumerable: true,
  33345. configurable: true
  33346. });
  33347. // Methods
  33348. ActionManager.prototype.dispose = function () {
  33349. var index = this._scene._actionManagers.indexOf(this);
  33350. if (index > -1) {
  33351. this._scene._actionManagers.splice(index, 1);
  33352. }
  33353. };
  33354. ActionManager.prototype.getScene = function () {
  33355. return this._scene;
  33356. };
  33357. /**
  33358. * Does this action manager handles actions of any of the given triggers
  33359. * @param {number[]} triggers - the triggers to be tested
  33360. * @return {boolean} whether one (or more) of the triggers is handeled
  33361. */
  33362. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  33363. for (var index = 0; index < this.actions.length; index++) {
  33364. var action = this.actions[index];
  33365. if (triggers.indexOf(action.trigger) > -1) {
  33366. return true;
  33367. }
  33368. }
  33369. return false;
  33370. };
  33371. /**
  33372. * Does this action manager handles actions of a given trigger
  33373. * @param {number} trigger - the trigger to be tested
  33374. * @return {boolean} whether the trigger is handeled
  33375. */
  33376. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  33377. for (var index = 0; index < this.actions.length; index++) {
  33378. var action = this.actions[index];
  33379. if (action.trigger === trigger) {
  33380. return true;
  33381. }
  33382. }
  33383. return false;
  33384. };
  33385. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  33386. /**
  33387. * Does this action manager has pointer triggers
  33388. * @return {boolean} whether or not it has pointer triggers
  33389. */
  33390. get: function () {
  33391. for (var index = 0; index < this.actions.length; index++) {
  33392. var action = this.actions[index];
  33393. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  33394. return true;
  33395. }
  33396. }
  33397. return false;
  33398. },
  33399. enumerable: true,
  33400. configurable: true
  33401. });
  33402. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33403. /**
  33404. * Does this action manager has pick triggers
  33405. * @return {boolean} whether or not it has pick triggers
  33406. */
  33407. get: function () {
  33408. for (var index = 0; index < this.actions.length; index++) {
  33409. var action = this.actions[index];
  33410. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33411. return true;
  33412. }
  33413. }
  33414. return false;
  33415. },
  33416. enumerable: true,
  33417. configurable: true
  33418. });
  33419. /**
  33420. * Registers an action to this action manager
  33421. * @param {BABYLON.Action} action - the action to be registered
  33422. * @return {BABYLON.Action} the action amended (prepared) after registration
  33423. */
  33424. ActionManager.prototype.registerAction = function (action) {
  33425. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33426. if (this.getScene().actionManager !== this) {
  33427. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33428. return null;
  33429. }
  33430. }
  33431. this.actions.push(action);
  33432. action._actionManager = this;
  33433. action._prepare();
  33434. return action;
  33435. };
  33436. /**
  33437. * Process a specific trigger
  33438. * @param {number} trigger - the trigger to process
  33439. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33440. */
  33441. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33442. for (var index = 0; index < this.actions.length; index++) {
  33443. var action = this.actions[index];
  33444. if (action.trigger === trigger) {
  33445. if (trigger === ActionManager.OnKeyUpTrigger
  33446. || trigger === ActionManager.OnKeyDownTrigger) {
  33447. var parameter = action.getTriggerParameter();
  33448. if (parameter) {
  33449. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33450. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33451. if (actualkey !== parameter.toLowerCase()) {
  33452. continue;
  33453. }
  33454. }
  33455. }
  33456. action._executeCurrent(evt);
  33457. }
  33458. }
  33459. };
  33460. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33461. var properties = propertyPath.split(".");
  33462. for (var index = 0; index < properties.length - 1; index++) {
  33463. target = target[properties[index]];
  33464. }
  33465. return target;
  33466. };
  33467. ActionManager.prototype._getProperty = function (propertyPath) {
  33468. var properties = propertyPath.split(".");
  33469. return properties[properties.length - 1];
  33470. };
  33471. ActionManager.prototype.serialize = function (name) {
  33472. var root = {
  33473. children: [],
  33474. name: name,
  33475. type: 3,
  33476. properties: [] // Empty for root but required
  33477. };
  33478. for (var i = 0; i < this.actions.length; i++) {
  33479. var triggerObject = {
  33480. type: 0,
  33481. children: [],
  33482. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  33483. properties: []
  33484. };
  33485. var triggerOptions = this.actions[i].triggerOptions;
  33486. if (triggerOptions && typeof triggerOptions !== "number") {
  33487. if (triggerOptions.parameter instanceof BABYLON.Node) {
  33488. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  33489. }
  33490. else {
  33491. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  33492. }
  33493. }
  33494. // Serialize child action, recursively
  33495. this.actions[i].serialize(triggerObject);
  33496. // Add serialized trigger
  33497. root.children.push(triggerObject);
  33498. }
  33499. return root;
  33500. };
  33501. ActionManager.Parse = function (parsedActions, object, scene) {
  33502. var actionManager = new BABYLON.ActionManager(scene);
  33503. if (object === null)
  33504. scene.actionManager = actionManager;
  33505. else
  33506. object.actionManager = actionManager;
  33507. // instanciate a new object
  33508. var instanciate = function (name, params) {
  33509. var newInstance = Object.create(BABYLON[name].prototype);
  33510. newInstance.constructor.apply(newInstance, params);
  33511. return newInstance;
  33512. };
  33513. var parseParameter = function (name, value, target, propertyPath) {
  33514. if (propertyPath === null) {
  33515. // String, boolean or float
  33516. var floatValue = parseFloat(value);
  33517. if (value === "true" || value === "false")
  33518. return value === "true";
  33519. else
  33520. return isNaN(floatValue) ? value : floatValue;
  33521. }
  33522. var effectiveTarget = propertyPath.split(".");
  33523. var values = value.split(",");
  33524. // Get effective Target
  33525. for (var i = 0; i < effectiveTarget.length; i++) {
  33526. target = target[effectiveTarget[i]];
  33527. }
  33528. // Return appropriate value with its type
  33529. if (typeof (target) === "boolean")
  33530. return values[0] === "true";
  33531. if (typeof (target) === "string")
  33532. return values[0];
  33533. // Parameters with multiple values such as Vector3 etc.
  33534. var split = new Array();
  33535. for (var i = 0; i < values.length; i++)
  33536. split.push(parseFloat(values[i]));
  33537. if (target instanceof BABYLON.Vector3)
  33538. return BABYLON.Vector3.FromArray(split);
  33539. if (target instanceof BABYLON.Vector4)
  33540. return BABYLON.Vector4.FromArray(split);
  33541. if (target instanceof BABYLON.Color3)
  33542. return BABYLON.Color3.FromArray(split);
  33543. if (target instanceof BABYLON.Color4)
  33544. return BABYLON.Color4.FromArray(split);
  33545. return parseFloat(values[0]);
  33546. };
  33547. // traverse graph per trigger
  33548. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  33549. if (combineArray === void 0) { combineArray = null; }
  33550. if (parsedAction.detached)
  33551. return;
  33552. var parameters = new Array();
  33553. var target = null;
  33554. var propertyPath = null;
  33555. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  33556. // Parameters
  33557. if (parsedAction.type === 2)
  33558. parameters.push(actionManager);
  33559. else
  33560. parameters.push(trigger);
  33561. if (combine) {
  33562. var actions = new Array();
  33563. for (var j = 0; j < parsedAction.combine.length; j++) {
  33564. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  33565. }
  33566. parameters.push(actions);
  33567. }
  33568. else {
  33569. for (var i = 0; i < parsedAction.properties.length; i++) {
  33570. var value = parsedAction.properties[i].value;
  33571. var name = parsedAction.properties[i].name;
  33572. var targetType = parsedAction.properties[i].targetType;
  33573. if (name === "target")
  33574. if (targetType !== null && targetType === "SceneProperties")
  33575. value = target = scene;
  33576. else
  33577. value = target = scene.getNodeByName(value);
  33578. else if (name === "parent")
  33579. value = scene.getNodeByName(value);
  33580. else if (name === "sound")
  33581. value = scene.getSoundByName(value);
  33582. else if (name !== "propertyPath") {
  33583. if (parsedAction.type === 2 && name === "operator")
  33584. value = BABYLON.ValueCondition[value];
  33585. else
  33586. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  33587. }
  33588. else {
  33589. propertyPath = value;
  33590. }
  33591. parameters.push(value);
  33592. }
  33593. }
  33594. if (combineArray === null) {
  33595. parameters.push(condition);
  33596. }
  33597. else {
  33598. parameters.push(null);
  33599. }
  33600. // If interpolate value action
  33601. if (parsedAction.name === "InterpolateValueAction") {
  33602. var param = parameters[parameters.length - 2];
  33603. parameters[parameters.length - 1] = param;
  33604. parameters[parameters.length - 2] = condition;
  33605. }
  33606. // Action or condition(s) and not CombineAction
  33607. var newAction = instanciate(parsedAction.name, parameters);
  33608. if (newAction instanceof BABYLON.Condition && condition !== null) {
  33609. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  33610. if (action)
  33611. action.then(nothing);
  33612. else
  33613. actionManager.registerAction(nothing);
  33614. action = nothing;
  33615. }
  33616. if (combineArray === null) {
  33617. if (newAction instanceof BABYLON.Condition) {
  33618. condition = newAction;
  33619. newAction = action;
  33620. }
  33621. else {
  33622. condition = null;
  33623. if (action)
  33624. action.then(newAction);
  33625. else
  33626. actionManager.registerAction(newAction);
  33627. }
  33628. }
  33629. else {
  33630. combineArray.push(newAction);
  33631. }
  33632. for (var i = 0; i < parsedAction.children.length; i++)
  33633. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  33634. };
  33635. // triggers
  33636. for (var i = 0; i < parsedActions.children.length; i++) {
  33637. var triggerParams;
  33638. var trigger = parsedActions.children[i];
  33639. if (trigger.properties.length > 0) {
  33640. var param = trigger.properties[0].value;
  33641. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  33642. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  33643. }
  33644. else
  33645. triggerParams = BABYLON.ActionManager[trigger.name];
  33646. for (var j = 0; j < trigger.children.length; j++) {
  33647. if (!trigger.detached)
  33648. traverse(trigger.children[j], triggerParams, null, null);
  33649. }
  33650. }
  33651. };
  33652. ActionManager.GetTriggerName = function (trigger) {
  33653. switch (trigger) {
  33654. case 0: return "NothingTrigger";
  33655. case 1: return "OnPickTrigger";
  33656. case 2: return "OnLeftPickTrigger";
  33657. case 3: return "OnRightPickTrigger";
  33658. case 4: return "OnCenterPickTrigger";
  33659. case 5: return "OnPickDownTrigger";
  33660. case 6: return "OnPickUpTrigger";
  33661. case 7: return "OnLongPressTrigger";
  33662. case 8: return "OnPointerOverTrigger";
  33663. case 9: return "OnPointerOutTrigger";
  33664. case 10: return "OnEveryFrameTrigger";
  33665. case 11: return "OnIntersectionEnterTrigger";
  33666. case 12: return "OnIntersectionExitTrigger";
  33667. case 13: return "OnKeyDownTrigger";
  33668. case 14: return "OnKeyUpTrigger";
  33669. case 15: return "OnPickOutTrigger";
  33670. default: return "";
  33671. }
  33672. };
  33673. // Statics
  33674. ActionManager._NothingTrigger = 0;
  33675. ActionManager._OnPickTrigger = 1;
  33676. ActionManager._OnLeftPickTrigger = 2;
  33677. ActionManager._OnRightPickTrigger = 3;
  33678. ActionManager._OnCenterPickTrigger = 4;
  33679. ActionManager._OnPickDownTrigger = 5;
  33680. ActionManager._OnPickUpTrigger = 6;
  33681. ActionManager._OnLongPressTrigger = 7;
  33682. ActionManager._OnPointerOverTrigger = 8;
  33683. ActionManager._OnPointerOutTrigger = 9;
  33684. ActionManager._OnEveryFrameTrigger = 10;
  33685. ActionManager._OnIntersectionEnterTrigger = 11;
  33686. ActionManager._OnIntersectionExitTrigger = 12;
  33687. ActionManager._OnKeyDownTrigger = 13;
  33688. ActionManager._OnKeyUpTrigger = 14;
  33689. ActionManager._OnPickOutTrigger = 15;
  33690. ActionManager.DragMovementThreshold = 10; // in pixels
  33691. ActionManager.LongPressDelay = 500; // in milliseconds
  33692. return ActionManager;
  33693. })();
  33694. BABYLON.ActionManager = ActionManager;
  33695. })(BABYLON || (BABYLON = {}));
  33696. var BABYLON;
  33697. (function (BABYLON) {
  33698. var InterpolateValueAction = (function (_super) {
  33699. __extends(InterpolateValueAction, _super);
  33700. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  33701. if (duration === void 0) { duration = 1000; }
  33702. _super.call(this, triggerOptions, condition);
  33703. this.propertyPath = propertyPath;
  33704. this.value = value;
  33705. this.duration = duration;
  33706. this.stopOtherAnimations = stopOtherAnimations;
  33707. this.onInterpolationDone = onInterpolationDone;
  33708. this._target = this._effectiveTarget = target;
  33709. }
  33710. InterpolateValueAction.prototype._prepare = function () {
  33711. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33712. this._property = this._getProperty(this.propertyPath);
  33713. };
  33714. InterpolateValueAction.prototype.execute = function () {
  33715. var scene = this._actionManager.getScene();
  33716. var keys = [
  33717. {
  33718. frame: 0,
  33719. value: this._effectiveTarget[this._property]
  33720. }, {
  33721. frame: 100,
  33722. value: this.value
  33723. }
  33724. ];
  33725. var dataType;
  33726. if (typeof this.value === "number") {
  33727. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  33728. }
  33729. else if (this.value instanceof BABYLON.Color3) {
  33730. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  33731. }
  33732. else if (this.value instanceof BABYLON.Vector3) {
  33733. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  33734. }
  33735. else if (this.value instanceof BABYLON.Matrix) {
  33736. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  33737. }
  33738. else if (this.value instanceof BABYLON.Quaternion) {
  33739. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  33740. }
  33741. else {
  33742. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  33743. return;
  33744. }
  33745. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  33746. animation.setKeys(keys);
  33747. if (this.stopOtherAnimations) {
  33748. scene.stopAnimation(this._effectiveTarget);
  33749. }
  33750. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  33751. };
  33752. InterpolateValueAction.prototype.serialize = function (parent) {
  33753. return _super.prototype._serialize.call(this, {
  33754. name: "InterpolateValueAction",
  33755. properties: [
  33756. BABYLON.Action._GetTargetProperty(this._target),
  33757. { name: "propertyPath", value: this.propertyPath },
  33758. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33759. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  33760. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  33761. ]
  33762. }, parent);
  33763. };
  33764. return InterpolateValueAction;
  33765. })(BABYLON.Action);
  33766. BABYLON.InterpolateValueAction = InterpolateValueAction;
  33767. })(BABYLON || (BABYLON = {}));
  33768. var BABYLON;
  33769. (function (BABYLON) {
  33770. var SwitchBooleanAction = (function (_super) {
  33771. __extends(SwitchBooleanAction, _super);
  33772. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  33773. _super.call(this, triggerOptions, condition);
  33774. this.propertyPath = propertyPath;
  33775. this._target = this._effectiveTarget = target;
  33776. }
  33777. SwitchBooleanAction.prototype._prepare = function () {
  33778. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33779. this._property = this._getProperty(this.propertyPath);
  33780. };
  33781. SwitchBooleanAction.prototype.execute = function () {
  33782. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  33783. };
  33784. SwitchBooleanAction.prototype.serialize = function (parent) {
  33785. return _super.prototype._serialize.call(this, {
  33786. name: "SwitchBooleanAction",
  33787. properties: [
  33788. BABYLON.Action._GetTargetProperty(this._target),
  33789. { name: "propertyPath", value: this.propertyPath }
  33790. ]
  33791. }, parent);
  33792. };
  33793. return SwitchBooleanAction;
  33794. })(BABYLON.Action);
  33795. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  33796. var SetStateAction = (function (_super) {
  33797. __extends(SetStateAction, _super);
  33798. function SetStateAction(triggerOptions, target, value, condition) {
  33799. _super.call(this, triggerOptions, condition);
  33800. this.value = value;
  33801. this._target = target;
  33802. }
  33803. SetStateAction.prototype.execute = function () {
  33804. this._target.state = this.value;
  33805. };
  33806. SetStateAction.prototype.serialize = function (parent) {
  33807. return _super.prototype._serialize.call(this, {
  33808. name: "SetStateAction",
  33809. properties: [
  33810. BABYLON.Action._GetTargetProperty(this._target),
  33811. { name: "value", value: this.value }
  33812. ]
  33813. }, parent);
  33814. };
  33815. return SetStateAction;
  33816. })(BABYLON.Action);
  33817. BABYLON.SetStateAction = SetStateAction;
  33818. var SetValueAction = (function (_super) {
  33819. __extends(SetValueAction, _super);
  33820. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  33821. _super.call(this, triggerOptions, condition);
  33822. this.propertyPath = propertyPath;
  33823. this.value = value;
  33824. this._target = this._effectiveTarget = target;
  33825. }
  33826. SetValueAction.prototype._prepare = function () {
  33827. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33828. this._property = this._getProperty(this.propertyPath);
  33829. };
  33830. SetValueAction.prototype.execute = function () {
  33831. this._effectiveTarget[this._property] = this.value;
  33832. if (this._target.markAsDirty) {
  33833. this._target.markAsDirty(this._property);
  33834. }
  33835. };
  33836. SetValueAction.prototype.serialize = function (parent) {
  33837. return _super.prototype._serialize.call(this, {
  33838. name: "SetValueAction",
  33839. properties: [
  33840. BABYLON.Action._GetTargetProperty(this._target),
  33841. { name: "propertyPath", value: this.propertyPath },
  33842. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33843. ]
  33844. }, parent);
  33845. };
  33846. return SetValueAction;
  33847. })(BABYLON.Action);
  33848. BABYLON.SetValueAction = SetValueAction;
  33849. var IncrementValueAction = (function (_super) {
  33850. __extends(IncrementValueAction, _super);
  33851. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  33852. _super.call(this, triggerOptions, condition);
  33853. this.propertyPath = propertyPath;
  33854. this.value = value;
  33855. this._target = this._effectiveTarget = target;
  33856. }
  33857. IncrementValueAction.prototype._prepare = function () {
  33858. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33859. this._property = this._getProperty(this.propertyPath);
  33860. if (typeof this._effectiveTarget[this._property] !== "number") {
  33861. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  33862. }
  33863. };
  33864. IncrementValueAction.prototype.execute = function () {
  33865. this._effectiveTarget[this._property] += this.value;
  33866. if (this._target.markAsDirty) {
  33867. this._target.markAsDirty(this._property);
  33868. }
  33869. };
  33870. IncrementValueAction.prototype.serialize = function (parent) {
  33871. return _super.prototype._serialize.call(this, {
  33872. name: "IncrementValueAction",
  33873. properties: [
  33874. BABYLON.Action._GetTargetProperty(this._target),
  33875. { name: "propertyPath", value: this.propertyPath },
  33876. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33877. ]
  33878. }, parent);
  33879. };
  33880. return IncrementValueAction;
  33881. })(BABYLON.Action);
  33882. BABYLON.IncrementValueAction = IncrementValueAction;
  33883. var PlayAnimationAction = (function (_super) {
  33884. __extends(PlayAnimationAction, _super);
  33885. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  33886. _super.call(this, triggerOptions, condition);
  33887. this.from = from;
  33888. this.to = to;
  33889. this.loop = loop;
  33890. this._target = target;
  33891. }
  33892. PlayAnimationAction.prototype._prepare = function () {
  33893. };
  33894. PlayAnimationAction.prototype.execute = function () {
  33895. var scene = this._actionManager.getScene();
  33896. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  33897. };
  33898. PlayAnimationAction.prototype.serialize = function (parent) {
  33899. return _super.prototype._serialize.call(this, {
  33900. name: "PlayAnimationAction",
  33901. properties: [
  33902. BABYLON.Action._GetTargetProperty(this._target),
  33903. { name: "from", value: String(this.from) },
  33904. { name: "to", value: String(this.to) },
  33905. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  33906. ]
  33907. }, parent);
  33908. };
  33909. return PlayAnimationAction;
  33910. })(BABYLON.Action);
  33911. BABYLON.PlayAnimationAction = PlayAnimationAction;
  33912. var StopAnimationAction = (function (_super) {
  33913. __extends(StopAnimationAction, _super);
  33914. function StopAnimationAction(triggerOptions, target, condition) {
  33915. _super.call(this, triggerOptions, condition);
  33916. this._target = target;
  33917. }
  33918. StopAnimationAction.prototype._prepare = function () {
  33919. };
  33920. StopAnimationAction.prototype.execute = function () {
  33921. var scene = this._actionManager.getScene();
  33922. scene.stopAnimation(this._target);
  33923. };
  33924. StopAnimationAction.prototype.serialize = function (parent) {
  33925. return _super.prototype._serialize.call(this, {
  33926. name: "StopAnimationAction",
  33927. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  33928. }, parent);
  33929. };
  33930. return StopAnimationAction;
  33931. })(BABYLON.Action);
  33932. BABYLON.StopAnimationAction = StopAnimationAction;
  33933. var DoNothingAction = (function (_super) {
  33934. __extends(DoNothingAction, _super);
  33935. function DoNothingAction(triggerOptions, condition) {
  33936. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  33937. _super.call(this, triggerOptions, condition);
  33938. }
  33939. DoNothingAction.prototype.execute = function () {
  33940. };
  33941. DoNothingAction.prototype.serialize = function (parent) {
  33942. return _super.prototype._serialize.call(this, {
  33943. name: "DoNothingAction",
  33944. properties: []
  33945. }, parent);
  33946. };
  33947. return DoNothingAction;
  33948. })(BABYLON.Action);
  33949. BABYLON.DoNothingAction = DoNothingAction;
  33950. var CombineAction = (function (_super) {
  33951. __extends(CombineAction, _super);
  33952. function CombineAction(triggerOptions, children, condition) {
  33953. _super.call(this, triggerOptions, condition);
  33954. this.children = children;
  33955. }
  33956. CombineAction.prototype._prepare = function () {
  33957. for (var index = 0; index < this.children.length; index++) {
  33958. this.children[index]._actionManager = this._actionManager;
  33959. this.children[index]._prepare();
  33960. }
  33961. };
  33962. CombineAction.prototype.execute = function (evt) {
  33963. for (var index = 0; index < this.children.length; index++) {
  33964. this.children[index].execute(evt);
  33965. }
  33966. };
  33967. CombineAction.prototype.serialize = function (parent) {
  33968. var serializationObject = _super.prototype._serialize.call(this, {
  33969. name: "CombineAction",
  33970. properties: [],
  33971. combine: []
  33972. }, parent);
  33973. for (var i = 0; i < this.children.length; i++) {
  33974. serializationObject.combine.push(this.children[i].serialize(null));
  33975. }
  33976. return serializationObject;
  33977. };
  33978. return CombineAction;
  33979. })(BABYLON.Action);
  33980. BABYLON.CombineAction = CombineAction;
  33981. var ExecuteCodeAction = (function (_super) {
  33982. __extends(ExecuteCodeAction, _super);
  33983. function ExecuteCodeAction(triggerOptions, func, condition) {
  33984. _super.call(this, triggerOptions, condition);
  33985. this.func = func;
  33986. }
  33987. ExecuteCodeAction.prototype.execute = function (evt) {
  33988. this.func(evt);
  33989. };
  33990. return ExecuteCodeAction;
  33991. })(BABYLON.Action);
  33992. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  33993. var SetParentAction = (function (_super) {
  33994. __extends(SetParentAction, _super);
  33995. function SetParentAction(triggerOptions, target, parent, condition) {
  33996. _super.call(this, triggerOptions, condition);
  33997. this._target = target;
  33998. this._parent = parent;
  33999. }
  34000. SetParentAction.prototype._prepare = function () {
  34001. };
  34002. SetParentAction.prototype.execute = function () {
  34003. if (this._target.parent === this._parent) {
  34004. return;
  34005. }
  34006. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34007. invertParentWorldMatrix.invert();
  34008. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34009. this._target.parent = this._parent;
  34010. };
  34011. SetParentAction.prototype.serialize = function (parent) {
  34012. return _super.prototype._serialize.call(this, {
  34013. name: "SetParentAction",
  34014. properties: [
  34015. BABYLON.Action._GetTargetProperty(this._target),
  34016. BABYLON.Action._GetTargetProperty(this._parent),
  34017. ]
  34018. }, parent);
  34019. };
  34020. return SetParentAction;
  34021. })(BABYLON.Action);
  34022. BABYLON.SetParentAction = SetParentAction;
  34023. var PlaySoundAction = (function (_super) {
  34024. __extends(PlaySoundAction, _super);
  34025. function PlaySoundAction(triggerOptions, sound, condition) {
  34026. _super.call(this, triggerOptions, condition);
  34027. this._sound = sound;
  34028. }
  34029. PlaySoundAction.prototype._prepare = function () {
  34030. };
  34031. PlaySoundAction.prototype.execute = function () {
  34032. if (this._sound !== undefined)
  34033. this._sound.play();
  34034. };
  34035. PlaySoundAction.prototype.serialize = function (parent) {
  34036. return _super.prototype._serialize.call(this, {
  34037. name: "PlaySoundAction",
  34038. properties: [{ name: "sound", value: this._sound.name }]
  34039. }, parent);
  34040. };
  34041. return PlaySoundAction;
  34042. })(BABYLON.Action);
  34043. BABYLON.PlaySoundAction = PlaySoundAction;
  34044. var StopSoundAction = (function (_super) {
  34045. __extends(StopSoundAction, _super);
  34046. function StopSoundAction(triggerOptions, sound, condition) {
  34047. _super.call(this, triggerOptions, condition);
  34048. this._sound = sound;
  34049. }
  34050. StopSoundAction.prototype._prepare = function () {
  34051. };
  34052. StopSoundAction.prototype.execute = function () {
  34053. if (this._sound !== undefined)
  34054. this._sound.stop();
  34055. };
  34056. StopSoundAction.prototype.serialize = function (parent) {
  34057. return _super.prototype._serialize.call(this, {
  34058. name: "StopSoundAction",
  34059. properties: [{ name: "sound", value: this._sound.name }]
  34060. }, parent);
  34061. };
  34062. return StopSoundAction;
  34063. })(BABYLON.Action);
  34064. BABYLON.StopSoundAction = StopSoundAction;
  34065. })(BABYLON || (BABYLON = {}));
  34066. var BABYLON;
  34067. (function (BABYLON) {
  34068. var Geometry = (function () {
  34069. function Geometry(id, scene, vertexData, updatable, mesh) {
  34070. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34071. this._totalVertices = 0;
  34072. this._isDisposed = false;
  34073. this.id = id;
  34074. this._engine = scene.getEngine();
  34075. this._meshes = [];
  34076. this._scene = scene;
  34077. //Init vertex buffer cache
  34078. this._vertexBuffers = {};
  34079. this._indices = [];
  34080. // vertexData
  34081. if (vertexData) {
  34082. this.setAllVerticesData(vertexData, updatable);
  34083. }
  34084. else {
  34085. this._totalVertices = 0;
  34086. this._indices = [];
  34087. }
  34088. // applyToMesh
  34089. if (mesh) {
  34090. if (mesh instanceof BABYLON.LinesMesh) {
  34091. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34092. this.updateExtend();
  34093. }
  34094. this.applyToMesh(mesh);
  34095. mesh.computeWorldMatrix(true);
  34096. }
  34097. }
  34098. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34099. /**
  34100. * 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
  34101. * @returns The Bias Vector
  34102. */
  34103. get: function () {
  34104. return this._boundingBias;
  34105. },
  34106. set: function (value) {
  34107. if (this._boundingBias && this._boundingBias.equals(value)) {
  34108. return;
  34109. }
  34110. this._boundingBias = value.clone();
  34111. this.updateBoundingInfo(true, null);
  34112. },
  34113. enumerable: true,
  34114. configurable: true
  34115. });
  34116. Object.defineProperty(Geometry.prototype, "extend", {
  34117. get: function () {
  34118. return this._extend;
  34119. },
  34120. enumerable: true,
  34121. configurable: true
  34122. });
  34123. Geometry.prototype.getScene = function () {
  34124. return this._scene;
  34125. };
  34126. Geometry.prototype.getEngine = function () {
  34127. return this._engine;
  34128. };
  34129. Geometry.prototype.isReady = function () {
  34130. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34131. };
  34132. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34133. vertexData.applyToGeometry(this, updatable);
  34134. this.notifyUpdate();
  34135. };
  34136. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34137. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34138. this.setVerticesBuffer(buffer);
  34139. };
  34140. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34141. var kind = buffer.getKind();
  34142. if (this._vertexBuffers[kind]) {
  34143. this._vertexBuffers[kind].dispose();
  34144. }
  34145. this._vertexBuffers[kind] = buffer;
  34146. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34147. var data = buffer.getData();
  34148. var stride = buffer.getStrideSize();
  34149. this._totalVertices = data.length / stride;
  34150. this.updateExtend(data, stride);
  34151. var meshes = this._meshes;
  34152. var numOfMeshes = meshes.length;
  34153. for (var index = 0; index < numOfMeshes; index++) {
  34154. var mesh = meshes[index];
  34155. mesh._resetPointsArrayCache();
  34156. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34157. mesh._createGlobalSubMesh();
  34158. mesh.computeWorldMatrix(true);
  34159. }
  34160. }
  34161. this.notifyUpdate(kind);
  34162. };
  34163. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34164. var vertexBuffer = this.getVertexBuffer(kind);
  34165. if (!vertexBuffer) {
  34166. return;
  34167. }
  34168. vertexBuffer.updateDirectly(data, offset);
  34169. this.notifyUpdate(kind);
  34170. };
  34171. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34172. var vertexBuffer = this.getVertexBuffer(kind);
  34173. if (!vertexBuffer) {
  34174. return;
  34175. }
  34176. vertexBuffer.update(data);
  34177. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34178. var stride = vertexBuffer.getStrideSize();
  34179. this._totalVertices = data.length / stride;
  34180. this.updateBoundingInfo(updateExtends, data);
  34181. }
  34182. this.notifyUpdate(kind);
  34183. };
  34184. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34185. if (updateExtends) {
  34186. this.updateExtend(data);
  34187. }
  34188. var meshes = this._meshes;
  34189. var numOfMeshes = meshes.length;
  34190. for (var index = 0; index < numOfMeshes; index++) {
  34191. var mesh = meshes[index];
  34192. mesh._resetPointsArrayCache();
  34193. if (updateExtends) {
  34194. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34195. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34196. var subMesh = mesh.subMeshes[subIndex];
  34197. subMesh.refreshBoundingInfo();
  34198. }
  34199. }
  34200. }
  34201. };
  34202. Geometry.prototype.getTotalVertices = function () {
  34203. if (!this.isReady()) {
  34204. return 0;
  34205. }
  34206. return this._totalVertices;
  34207. };
  34208. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  34209. var vertexBuffer = this.getVertexBuffer(kind);
  34210. if (!vertexBuffer) {
  34211. return null;
  34212. }
  34213. var orig = vertexBuffer.getData();
  34214. if (!copyWhenShared || this._meshes.length === 1) {
  34215. return orig;
  34216. }
  34217. else {
  34218. var len = orig.length;
  34219. var copy = [];
  34220. for (var i = 0; i < len; i++) {
  34221. copy.push(orig[i]);
  34222. }
  34223. return copy;
  34224. }
  34225. };
  34226. Geometry.prototype.getVertexBuffer = function (kind) {
  34227. if (!this.isReady()) {
  34228. return null;
  34229. }
  34230. return this._vertexBuffers[kind];
  34231. };
  34232. Geometry.prototype.getVertexBuffers = function () {
  34233. if (!this.isReady()) {
  34234. return null;
  34235. }
  34236. return this._vertexBuffers;
  34237. };
  34238. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34239. if (!this._vertexBuffers) {
  34240. if (this._delayInfo) {
  34241. return this._delayInfo.indexOf(kind) !== -1;
  34242. }
  34243. return false;
  34244. }
  34245. return this._vertexBuffers[kind] !== undefined;
  34246. };
  34247. Geometry.prototype.getVerticesDataKinds = function () {
  34248. var result = [];
  34249. var kind;
  34250. if (!this._vertexBuffers && this._delayInfo) {
  34251. for (kind in this._delayInfo) {
  34252. result.push(kind);
  34253. }
  34254. }
  34255. else {
  34256. for (kind in this._vertexBuffers) {
  34257. result.push(kind);
  34258. }
  34259. }
  34260. return result;
  34261. };
  34262. Geometry.prototype.setIndices = function (indices, totalVertices) {
  34263. if (this._indexBuffer) {
  34264. this._engine._releaseBuffer(this._indexBuffer);
  34265. }
  34266. this._indices = indices;
  34267. if (this._meshes.length !== 0 && this._indices) {
  34268. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34269. }
  34270. if (totalVertices !== undefined) {
  34271. this._totalVertices = totalVertices;
  34272. }
  34273. var meshes = this._meshes;
  34274. var numOfMeshes = meshes.length;
  34275. for (var index = 0; index < numOfMeshes; index++) {
  34276. meshes[index]._createGlobalSubMesh();
  34277. }
  34278. this.notifyUpdate();
  34279. };
  34280. Geometry.prototype.getTotalIndices = function () {
  34281. if (!this.isReady()) {
  34282. return 0;
  34283. }
  34284. return this._indices.length;
  34285. };
  34286. Geometry.prototype.getIndices = function (copyWhenShared) {
  34287. if (!this.isReady()) {
  34288. return null;
  34289. }
  34290. var orig = this._indices;
  34291. if (!copyWhenShared || this._meshes.length === 1) {
  34292. return orig;
  34293. }
  34294. else {
  34295. var len = orig.length;
  34296. var copy = [];
  34297. for (var i = 0; i < len; i++) {
  34298. copy.push(orig[i]);
  34299. }
  34300. return copy;
  34301. }
  34302. };
  34303. Geometry.prototype.getIndexBuffer = function () {
  34304. if (!this.isReady()) {
  34305. return null;
  34306. }
  34307. return this._indexBuffer;
  34308. };
  34309. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34310. var meshes = this._meshes;
  34311. var index = meshes.indexOf(mesh);
  34312. if (index === -1) {
  34313. return;
  34314. }
  34315. for (var kind in this._vertexBuffers) {
  34316. this._vertexBuffers[kind].dispose();
  34317. }
  34318. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  34319. this._indexBuffer = null;
  34320. }
  34321. meshes.splice(index, 1);
  34322. mesh._geometry = null;
  34323. if (meshes.length === 0 && shouldDispose) {
  34324. this.dispose();
  34325. }
  34326. };
  34327. Geometry.prototype.applyToMesh = function (mesh) {
  34328. if (mesh._geometry === this) {
  34329. return;
  34330. }
  34331. var previousGeometry = mesh._geometry;
  34332. if (previousGeometry) {
  34333. previousGeometry.releaseForMesh(mesh);
  34334. }
  34335. var meshes = this._meshes;
  34336. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34337. mesh._geometry = this;
  34338. this._scene.pushGeometry(this);
  34339. meshes.push(mesh);
  34340. if (this.isReady()) {
  34341. this._applyToMesh(mesh);
  34342. }
  34343. else {
  34344. mesh._boundingInfo = this._boundingInfo;
  34345. }
  34346. };
  34347. Geometry.prototype.updateExtend = function (data, stride) {
  34348. if (data === void 0) { data = null; }
  34349. if (!data) {
  34350. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34351. }
  34352. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34353. };
  34354. Geometry.prototype._applyToMesh = function (mesh) {
  34355. var numOfMeshes = this._meshes.length;
  34356. // vertexBuffers
  34357. for (var kind in this._vertexBuffers) {
  34358. if (numOfMeshes === 1) {
  34359. this._vertexBuffers[kind].create();
  34360. }
  34361. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  34362. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34363. mesh._resetPointsArrayCache();
  34364. if (!this._extend) {
  34365. this.updateExtend(this._vertexBuffers[kind].getData());
  34366. }
  34367. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34368. mesh._createGlobalSubMesh();
  34369. //bounding info was just created again, world matrix should be applied again.
  34370. mesh._updateBoundingInfo();
  34371. }
  34372. }
  34373. // indexBuffer
  34374. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34375. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34376. }
  34377. if (this._indexBuffer) {
  34378. this._indexBuffer.references = numOfMeshes;
  34379. }
  34380. };
  34381. Geometry.prototype.notifyUpdate = function (kind) {
  34382. if (this.onGeometryUpdated) {
  34383. this.onGeometryUpdated(this, kind);
  34384. }
  34385. };
  34386. Geometry.prototype.load = function (scene, onLoaded) {
  34387. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34388. return;
  34389. }
  34390. if (this.isReady()) {
  34391. if (onLoaded) {
  34392. onLoaded();
  34393. }
  34394. return;
  34395. }
  34396. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34397. this._queueLoad(scene, onLoaded);
  34398. };
  34399. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34400. var _this = this;
  34401. scene._addPendingData(this);
  34402. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  34403. _this._delayLoadingFunction(JSON.parse(data), _this);
  34404. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34405. _this._delayInfo = [];
  34406. scene._removePendingData(_this);
  34407. var meshes = _this._meshes;
  34408. var numOfMeshes = meshes.length;
  34409. for (var index = 0; index < numOfMeshes; index++) {
  34410. _this._applyToMesh(meshes[index]);
  34411. }
  34412. if (onLoaded) {
  34413. onLoaded();
  34414. }
  34415. }, function () { }, scene.database);
  34416. };
  34417. /**
  34418. * Invert the geometry to move from a right handed system to a left handed one.
  34419. */
  34420. Geometry.prototype.toLeftHanded = function () {
  34421. // Flip faces
  34422. var tIndices = this.getIndices(false);
  34423. if (tIndices != null && tIndices.length > 0) {
  34424. for (var i = 0; i < tIndices.length; i += 3) {
  34425. var tTemp = tIndices[i + 0];
  34426. tIndices[i + 0] = tIndices[i + 2];
  34427. tIndices[i + 2] = tTemp;
  34428. }
  34429. this.setIndices(tIndices);
  34430. }
  34431. // Negate position.z
  34432. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34433. if (tPositions != null && tPositions.length > 0) {
  34434. for (var i = 0; i < tPositions.length; i += 3) {
  34435. tPositions[i + 2] = -tPositions[i + 2];
  34436. }
  34437. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34438. }
  34439. // Negate normal.z
  34440. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34441. if (tNormals != null && tNormals.length > 0) {
  34442. for (var i = 0; i < tNormals.length; i += 3) {
  34443. tNormals[i + 2] = -tNormals[i + 2];
  34444. }
  34445. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34446. }
  34447. };
  34448. Geometry.prototype.isDisposed = function () {
  34449. return this._isDisposed;
  34450. };
  34451. Geometry.prototype.dispose = function () {
  34452. var meshes = this._meshes;
  34453. var numOfMeshes = meshes.length;
  34454. var index;
  34455. for (index = 0; index < numOfMeshes; index++) {
  34456. this.releaseForMesh(meshes[index]);
  34457. }
  34458. this._meshes = [];
  34459. for (var kind in this._vertexBuffers) {
  34460. this._vertexBuffers[kind].dispose();
  34461. }
  34462. this._vertexBuffers = {};
  34463. this._totalVertices = 0;
  34464. if (this._indexBuffer) {
  34465. this._engine._releaseBuffer(this._indexBuffer);
  34466. }
  34467. this._indexBuffer = null;
  34468. this._indices = [];
  34469. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34470. this.delayLoadingFile = null;
  34471. this._delayLoadingFunction = null;
  34472. this._delayInfo = [];
  34473. this._boundingInfo = null;
  34474. this._scene.removeGeometry(this);
  34475. this._isDisposed = true;
  34476. };
  34477. Geometry.prototype.copy = function (id) {
  34478. var vertexData = new BABYLON.VertexData();
  34479. vertexData.indices = [];
  34480. var indices = this.getIndices();
  34481. for (var index = 0; index < indices.length; index++) {
  34482. vertexData.indices.push(indices[index]);
  34483. }
  34484. var updatable = false;
  34485. var stopChecking = false;
  34486. var kind;
  34487. for (kind in this._vertexBuffers) {
  34488. // using slice() to make a copy of the array and not just reference it
  34489. var data = this.getVerticesData(kind);
  34490. if (data instanceof Float32Array) {
  34491. vertexData.set(new Float32Array(data), kind);
  34492. }
  34493. else {
  34494. vertexData.set(data.slice(0), kind);
  34495. }
  34496. if (!stopChecking) {
  34497. updatable = this.getVertexBuffer(kind).isUpdatable();
  34498. stopChecking = !updatable;
  34499. }
  34500. }
  34501. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  34502. geometry.delayLoadState = this.delayLoadState;
  34503. geometry.delayLoadingFile = this.delayLoadingFile;
  34504. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34505. for (kind in this._delayInfo) {
  34506. geometry._delayInfo = geometry._delayInfo || [];
  34507. geometry._delayInfo.push(kind);
  34508. }
  34509. // Bounding info
  34510. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34511. return geometry;
  34512. };
  34513. Geometry.prototype.serialize = function () {
  34514. var serializationObject = {};
  34515. serializationObject.id = this.id;
  34516. if (BABYLON.Tags.HasTags(this)) {
  34517. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34518. }
  34519. return serializationObject;
  34520. };
  34521. Geometry.prototype.serializeVerticeData = function () {
  34522. var serializationObject = this.serialize();
  34523. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34524. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34525. }
  34526. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34527. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34528. }
  34529. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34530. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34531. }
  34532. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34533. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  34534. }
  34535. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34536. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  34537. }
  34538. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34539. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  34540. }
  34541. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34542. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  34543. }
  34544. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34545. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  34546. }
  34547. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34548. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34549. }
  34550. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34551. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34552. serializationObject.matricesIndices._isExpanded = true;
  34553. }
  34554. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34555. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34556. }
  34557. serializationObject.indices = this.getIndices();
  34558. return serializationObject;
  34559. };
  34560. // Statics
  34561. Geometry.ExtractFromMesh = function (mesh, id) {
  34562. var geometry = mesh._geometry;
  34563. if (!geometry) {
  34564. return null;
  34565. }
  34566. return geometry.copy(id);
  34567. };
  34568. /**
  34569. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34570. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34571. * Be aware Math.random() could cause collisions, but:
  34572. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  34573. */
  34574. Geometry.RandomId = function () {
  34575. return BABYLON.Tools.RandomId();
  34576. };
  34577. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  34578. var scene = mesh.getScene();
  34579. // Geometry
  34580. var geometryId = parsedGeometry.geometryId;
  34581. if (geometryId) {
  34582. var geometry = scene.getGeometryByID(geometryId);
  34583. if (geometry) {
  34584. geometry.applyToMesh(mesh);
  34585. }
  34586. }
  34587. else if (parsedGeometry instanceof ArrayBuffer) {
  34588. var binaryInfo = mesh._binaryInfo;
  34589. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34590. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34591. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34592. }
  34593. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34594. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34595. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34596. }
  34597. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34598. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34599. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34600. }
  34601. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34602. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34603. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34604. }
  34605. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34606. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34607. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34608. }
  34609. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34610. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34611. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34612. }
  34613. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34614. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34615. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34616. }
  34617. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34618. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34619. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34620. }
  34621. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34622. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34623. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34624. }
  34625. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34626. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34627. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34628. }
  34629. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34630. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34631. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34632. }
  34633. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34634. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34635. mesh.setIndices(indicesData);
  34636. }
  34637. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34638. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34639. mesh.subMeshes = [];
  34640. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34641. var materialIndex = subMeshesData[(i * 5) + 0];
  34642. var verticesStart = subMeshesData[(i * 5) + 1];
  34643. var verticesCount = subMeshesData[(i * 5) + 2];
  34644. var indexStart = subMeshesData[(i * 5) + 3];
  34645. var indexCount = subMeshesData[(i * 5) + 4];
  34646. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34647. }
  34648. }
  34649. }
  34650. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34651. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  34652. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  34653. if (parsedGeometry.uvs) {
  34654. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  34655. }
  34656. if (parsedGeometry.uvs2) {
  34657. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  34658. }
  34659. if (parsedGeometry.uvs3) {
  34660. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  34661. }
  34662. if (parsedGeometry.uvs4) {
  34663. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  34664. }
  34665. if (parsedGeometry.uvs5) {
  34666. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  34667. }
  34668. if (parsedGeometry.uvs6) {
  34669. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  34670. }
  34671. if (parsedGeometry.colors) {
  34672. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  34673. }
  34674. if (parsedGeometry.matricesIndices) {
  34675. if (!parsedGeometry.matricesIndices._isExpanded) {
  34676. var floatIndices = [];
  34677. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34678. var matricesIndex = parsedGeometry.matricesIndices[i];
  34679. floatIndices.push(matricesIndex & 0x000000FF);
  34680. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34681. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34682. floatIndices.push(matricesIndex >> 24);
  34683. }
  34684. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  34685. }
  34686. else {
  34687. delete parsedGeometry.matricesIndices._isExpanded;
  34688. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  34689. }
  34690. }
  34691. if (parsedGeometry.matricesIndicesExtra) {
  34692. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34693. var floatIndices = [];
  34694. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34695. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34696. floatIndices.push(matricesIndex & 0x000000FF);
  34697. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34698. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34699. floatIndices.push(matricesIndex >> 24);
  34700. }
  34701. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  34702. }
  34703. else {
  34704. delete parsedGeometry.matricesIndices._isExpanded;
  34705. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  34706. }
  34707. }
  34708. if (parsedGeometry.matricesWeights) {
  34709. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  34710. }
  34711. if (parsedGeometry.matricesWeightsExtra) {
  34712. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  34713. }
  34714. mesh.setIndices(parsedGeometry.indices);
  34715. }
  34716. // SubMeshes
  34717. if (parsedGeometry.subMeshes) {
  34718. mesh.subMeshes = [];
  34719. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34720. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34721. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34722. }
  34723. }
  34724. // Flat shading
  34725. if (mesh._shouldGenerateFlatShading) {
  34726. mesh.convertToFlatShadedMesh();
  34727. delete mesh._shouldGenerateFlatShading;
  34728. }
  34729. // Update
  34730. mesh.computeWorldMatrix(true);
  34731. // Octree
  34732. if (scene['_selectionOctree']) {
  34733. scene['_selectionOctree'].addMesh(mesh);
  34734. }
  34735. };
  34736. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  34737. if (scene.getGeometryByID(parsedVertexData.id)) {
  34738. return null; // null since geometry could be something else than a box...
  34739. }
  34740. var geometry = new Geometry(parsedVertexData.id, scene);
  34741. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  34742. if (parsedVertexData.delayLoadingFile) {
  34743. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34744. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  34745. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  34746. geometry._delayInfo = [];
  34747. if (parsedVertexData.hasUVs) {
  34748. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34749. }
  34750. if (parsedVertexData.hasUVs2) {
  34751. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34752. }
  34753. if (parsedVertexData.hasUVs3) {
  34754. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34755. }
  34756. if (parsedVertexData.hasUVs4) {
  34757. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34758. }
  34759. if (parsedVertexData.hasUVs5) {
  34760. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34761. }
  34762. if (parsedVertexData.hasUVs6) {
  34763. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34764. }
  34765. if (parsedVertexData.hasColors) {
  34766. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34767. }
  34768. if (parsedVertexData.hasMatricesIndices) {
  34769. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34770. }
  34771. if (parsedVertexData.hasMatricesWeights) {
  34772. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34773. }
  34774. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  34775. }
  34776. else {
  34777. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  34778. }
  34779. scene.pushGeometry(geometry, true);
  34780. return geometry;
  34781. };
  34782. return Geometry;
  34783. })();
  34784. BABYLON.Geometry = Geometry;
  34785. /////// Primitives //////////////////////////////////////////////
  34786. var Geometry;
  34787. (function (Geometry) {
  34788. var Primitives;
  34789. (function (Primitives) {
  34790. /// Abstract class
  34791. var _Primitive = (function (_super) {
  34792. __extends(_Primitive, _super);
  34793. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  34794. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  34795. this._canBeRegenerated = _canBeRegenerated;
  34796. this._beingRegenerated = true;
  34797. this.regenerate();
  34798. this._beingRegenerated = false;
  34799. }
  34800. _Primitive.prototype.canBeRegenerated = function () {
  34801. return this._canBeRegenerated;
  34802. };
  34803. _Primitive.prototype.regenerate = function () {
  34804. if (!this._canBeRegenerated) {
  34805. return;
  34806. }
  34807. this._beingRegenerated = true;
  34808. this.setAllVerticesData(this._regenerateVertexData(), false);
  34809. this._beingRegenerated = false;
  34810. };
  34811. _Primitive.prototype.asNewGeometry = function (id) {
  34812. return _super.prototype.copy.call(this, id);
  34813. };
  34814. // overrides
  34815. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  34816. if (!this._beingRegenerated) {
  34817. return;
  34818. }
  34819. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  34820. };
  34821. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  34822. if (!this._beingRegenerated) {
  34823. return;
  34824. }
  34825. _super.prototype.setVerticesData.call(this, kind, data, false);
  34826. };
  34827. // to override
  34828. // protected
  34829. _Primitive.prototype._regenerateVertexData = function () {
  34830. throw new Error("Abstract method");
  34831. };
  34832. _Primitive.prototype.copy = function (id) {
  34833. throw new Error("Must be overriden in sub-classes.");
  34834. };
  34835. _Primitive.prototype.serialize = function () {
  34836. var serializationObject = _super.prototype.serialize.call(this);
  34837. serializationObject.canBeRegenerated = this.canBeRegenerated();
  34838. return serializationObject;
  34839. };
  34840. return _Primitive;
  34841. })(Geometry);
  34842. Primitives._Primitive = _Primitive;
  34843. var Ribbon = (function (_super) {
  34844. __extends(Ribbon, _super);
  34845. // Members
  34846. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  34847. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34848. _super.call(this, id, scene, canBeRegenerated, mesh);
  34849. this.pathArray = pathArray;
  34850. this.closeArray = closeArray;
  34851. this.closePath = closePath;
  34852. this.offset = offset;
  34853. this.side = side;
  34854. }
  34855. Ribbon.prototype._regenerateVertexData = function () {
  34856. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  34857. };
  34858. Ribbon.prototype.copy = function (id) {
  34859. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  34860. };
  34861. return Ribbon;
  34862. })(_Primitive);
  34863. Primitives.Ribbon = Ribbon;
  34864. var Box = (function (_super) {
  34865. __extends(Box, _super);
  34866. // Members
  34867. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  34868. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34869. _super.call(this, id, scene, canBeRegenerated, mesh);
  34870. this.size = size;
  34871. this.side = side;
  34872. }
  34873. Box.prototype._regenerateVertexData = function () {
  34874. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  34875. };
  34876. Box.prototype.copy = function (id) {
  34877. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34878. };
  34879. Box.prototype.serialize = function () {
  34880. var serializationObject = _super.prototype.serialize.call(this);
  34881. serializationObject.size = this.size;
  34882. return serializationObject;
  34883. };
  34884. Box.Parse = function (parsedBox, scene) {
  34885. if (scene.getGeometryByID(parsedBox.id)) {
  34886. return null; // null since geometry could be something else than a box...
  34887. }
  34888. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  34889. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  34890. scene.pushGeometry(box, true);
  34891. return box;
  34892. };
  34893. return Box;
  34894. })(_Primitive);
  34895. Primitives.Box = Box;
  34896. var Sphere = (function (_super) {
  34897. __extends(Sphere, _super);
  34898. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  34899. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34900. _super.call(this, id, scene, canBeRegenerated, mesh);
  34901. this.segments = segments;
  34902. this.diameter = diameter;
  34903. this.side = side;
  34904. }
  34905. Sphere.prototype._regenerateVertexData = function () {
  34906. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  34907. };
  34908. Sphere.prototype.copy = function (id) {
  34909. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  34910. };
  34911. Sphere.prototype.serialize = function () {
  34912. var serializationObject = _super.prototype.serialize.call(this);
  34913. serializationObject.segments = this.segments;
  34914. serializationObject.diameter = this.diameter;
  34915. return serializationObject;
  34916. };
  34917. Sphere.Parse = function (parsedSphere, scene) {
  34918. if (scene.getGeometryByID(parsedSphere.id)) {
  34919. return null; // null since geometry could be something else than a sphere...
  34920. }
  34921. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34922. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34923. scene.pushGeometry(sphere, true);
  34924. return sphere;
  34925. };
  34926. return Sphere;
  34927. })(_Primitive);
  34928. Primitives.Sphere = Sphere;
  34929. var Disc = (function (_super) {
  34930. __extends(Disc, _super);
  34931. // Members
  34932. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  34933. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34934. _super.call(this, id, scene, canBeRegenerated, mesh);
  34935. this.radius = radius;
  34936. this.tessellation = tessellation;
  34937. this.side = side;
  34938. }
  34939. Disc.prototype._regenerateVertexData = function () {
  34940. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34941. };
  34942. Disc.prototype.copy = function (id) {
  34943. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34944. };
  34945. return Disc;
  34946. })(_Primitive);
  34947. Primitives.Disc = Disc;
  34948. var Cylinder = (function (_super) {
  34949. __extends(Cylinder, _super);
  34950. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  34951. if (subdivisions === void 0) { subdivisions = 1; }
  34952. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34953. _super.call(this, id, scene, canBeRegenerated, mesh);
  34954. this.height = height;
  34955. this.diameterTop = diameterTop;
  34956. this.diameterBottom = diameterBottom;
  34957. this.tessellation = tessellation;
  34958. this.subdivisions = subdivisions;
  34959. this.side = side;
  34960. }
  34961. Cylinder.prototype._regenerateVertexData = function () {
  34962. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34963. };
  34964. Cylinder.prototype.copy = function (id) {
  34965. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34966. };
  34967. Cylinder.prototype.serialize = function () {
  34968. var serializationObject = _super.prototype.serialize.call(this);
  34969. serializationObject.height = this.height;
  34970. serializationObject.diameterTop = this.diameterTop;
  34971. serializationObject.diameterBottom = this.diameterBottom;
  34972. serializationObject.tessellation = this.tessellation;
  34973. return serializationObject;
  34974. };
  34975. Cylinder.Parse = function (parsedCylinder, scene) {
  34976. if (scene.getGeometryByID(parsedCylinder.id)) {
  34977. return null; // null since geometry could be something else than a cylinder...
  34978. }
  34979. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34980. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34981. scene.pushGeometry(cylinder, true);
  34982. return cylinder;
  34983. };
  34984. return Cylinder;
  34985. })(_Primitive);
  34986. Primitives.Cylinder = Cylinder;
  34987. var Torus = (function (_super) {
  34988. __extends(Torus, _super);
  34989. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  34990. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34991. _super.call(this, id, scene, canBeRegenerated, mesh);
  34992. this.diameter = diameter;
  34993. this.thickness = thickness;
  34994. this.tessellation = tessellation;
  34995. this.side = side;
  34996. }
  34997. Torus.prototype._regenerateVertexData = function () {
  34998. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34999. };
  35000. Torus.prototype.copy = function (id) {
  35001. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35002. };
  35003. Torus.prototype.serialize = function () {
  35004. var serializationObject = _super.prototype.serialize.call(this);
  35005. serializationObject.diameter = this.diameter;
  35006. serializationObject.thickness = this.thickness;
  35007. serializationObject.tessellation = this.tessellation;
  35008. return serializationObject;
  35009. };
  35010. Torus.Parse = function (parsedTorus, scene) {
  35011. if (scene.getGeometryByID(parsedTorus.id)) {
  35012. return null; // null since geometry could be something else than a torus...
  35013. }
  35014. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35015. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35016. scene.pushGeometry(torus, true);
  35017. return torus;
  35018. };
  35019. return Torus;
  35020. })(_Primitive);
  35021. Primitives.Torus = Torus;
  35022. var Ground = (function (_super) {
  35023. __extends(Ground, _super);
  35024. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  35025. _super.call(this, id, scene, canBeRegenerated, mesh);
  35026. this.width = width;
  35027. this.height = height;
  35028. this.subdivisions = subdivisions;
  35029. }
  35030. Ground.prototype._regenerateVertexData = function () {
  35031. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35032. };
  35033. Ground.prototype.copy = function (id) {
  35034. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35035. };
  35036. Ground.prototype.serialize = function () {
  35037. var serializationObject = _super.prototype.serialize.call(this);
  35038. serializationObject.width = this.width;
  35039. serializationObject.height = this.height;
  35040. serializationObject.subdivisions = this.subdivisions;
  35041. return serializationObject;
  35042. };
  35043. Ground.Parse = function (parsedGround, scene) {
  35044. if (scene.getGeometryByID(parsedGround.id)) {
  35045. return null; // null since geometry could be something else than a ground...
  35046. }
  35047. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35048. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35049. scene.pushGeometry(ground, true);
  35050. return ground;
  35051. };
  35052. return Ground;
  35053. })(_Primitive);
  35054. Primitives.Ground = Ground;
  35055. var TiledGround = (function (_super) {
  35056. __extends(TiledGround, _super);
  35057. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  35058. _super.call(this, id, scene, canBeRegenerated, mesh);
  35059. this.xmin = xmin;
  35060. this.zmin = zmin;
  35061. this.xmax = xmax;
  35062. this.zmax = zmax;
  35063. this.subdivisions = subdivisions;
  35064. this.precision = precision;
  35065. }
  35066. TiledGround.prototype._regenerateVertexData = function () {
  35067. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35068. };
  35069. TiledGround.prototype.copy = function (id) {
  35070. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35071. };
  35072. return TiledGround;
  35073. })(_Primitive);
  35074. Primitives.TiledGround = TiledGround;
  35075. var Plane = (function (_super) {
  35076. __extends(Plane, _super);
  35077. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  35078. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35079. _super.call(this, id, scene, canBeRegenerated, mesh);
  35080. this.size = size;
  35081. this.side = side;
  35082. }
  35083. Plane.prototype._regenerateVertexData = function () {
  35084. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35085. };
  35086. Plane.prototype.copy = function (id) {
  35087. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35088. };
  35089. Plane.prototype.serialize = function () {
  35090. var serializationObject = _super.prototype.serialize.call(this);
  35091. serializationObject.size = this.size;
  35092. return serializationObject;
  35093. };
  35094. Plane.Parse = function (parsedPlane, scene) {
  35095. if (scene.getGeometryByID(parsedPlane.id)) {
  35096. return null; // null since geometry could be something else than a ground...
  35097. }
  35098. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35099. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35100. scene.pushGeometry(plane, true);
  35101. return plane;
  35102. };
  35103. return Plane;
  35104. })(_Primitive);
  35105. Primitives.Plane = Plane;
  35106. var TorusKnot = (function (_super) {
  35107. __extends(TorusKnot, _super);
  35108. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  35109. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35110. _super.call(this, id, scene, canBeRegenerated, mesh);
  35111. this.radius = radius;
  35112. this.tube = tube;
  35113. this.radialSegments = radialSegments;
  35114. this.tubularSegments = tubularSegments;
  35115. this.p = p;
  35116. this.q = q;
  35117. this.side = side;
  35118. }
  35119. TorusKnot.prototype._regenerateVertexData = function () {
  35120. 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 });
  35121. };
  35122. TorusKnot.prototype.copy = function (id) {
  35123. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35124. };
  35125. TorusKnot.prototype.serialize = function () {
  35126. var serializationObject = _super.prototype.serialize.call(this);
  35127. serializationObject.radius = this.radius;
  35128. serializationObject.tube = this.tube;
  35129. serializationObject.radialSegments = this.radialSegments;
  35130. serializationObject.tubularSegments = this.tubularSegments;
  35131. serializationObject.p = this.p;
  35132. serializationObject.q = this.q;
  35133. return serializationObject;
  35134. };
  35135. ;
  35136. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  35137. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35138. return null; // null since geometry could be something else than a ground...
  35139. }
  35140. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35141. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35142. scene.pushGeometry(torusKnot, true);
  35143. return torusKnot;
  35144. };
  35145. return TorusKnot;
  35146. })(_Primitive);
  35147. Primitives.TorusKnot = TorusKnot;
  35148. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  35149. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  35150. })(BABYLON || (BABYLON = {}));
  35151. var BABYLON;
  35152. (function (BABYLON) {
  35153. var GroundMesh = (function (_super) {
  35154. __extends(GroundMesh, _super);
  35155. function GroundMesh(name, scene) {
  35156. _super.call(this, name, scene);
  35157. this.generateOctree = false;
  35158. this._worldInverse = new BABYLON.Matrix();
  35159. }
  35160. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  35161. get: function () {
  35162. return Math.min(this._subdivisionsX, this._subdivisionsY);
  35163. },
  35164. enumerable: true,
  35165. configurable: true
  35166. });
  35167. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  35168. get: function () {
  35169. return this._subdivisionsX;
  35170. },
  35171. enumerable: true,
  35172. configurable: true
  35173. });
  35174. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  35175. get: function () {
  35176. return this._subdivisionsY;
  35177. },
  35178. enumerable: true,
  35179. configurable: true
  35180. });
  35181. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  35182. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  35183. this._subdivisionsX = chunksCount;
  35184. this._subdivisionsY = chunksCount;
  35185. this.subdivide(chunksCount);
  35186. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  35187. };
  35188. /**
  35189. * Returns a height (y) value in the Worl system :
  35190. * the ground altitude at the coordinates (x, z) expressed in the World system.
  35191. * Returns the ground y position if (x, z) are outside the ground surface.
  35192. * Not pertinent if the ground is rotated.
  35193. */
  35194. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  35195. // express x and y in the ground local system
  35196. x -= this.position.x;
  35197. z -= this.position.z;
  35198. x /= this.scaling.x;
  35199. z /= this.scaling.z;
  35200. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  35201. return this.position.y;
  35202. }
  35203. if (!this._heightQuads || this._heightQuads.length == 0) {
  35204. this._initHeightQuads();
  35205. this._computeHeightQuads();
  35206. }
  35207. var facet = this._getFacetAt(x, z);
  35208. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  35209. // return y in the World system
  35210. return y * this.scaling.y + this.position.y;
  35211. };
  35212. /**
  35213. * Returns a normalized vector (Vector3) orthogonal to the ground
  35214. * at the ground coordinates (x, z) expressed in the World system.
  35215. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  35216. * Not pertinent if the ground is rotated.
  35217. */
  35218. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  35219. var normal = new BABYLON.Vector3(0, 1, 0);
  35220. this.getNormalAtCoordinatesToRef(x, z, normal);
  35221. return normal;
  35222. };
  35223. /**
  35224. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  35225. * at the ground coordinates (x, z) expressed in the World system.
  35226. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  35227. * Not pertinent if the ground is rotated.
  35228. */
  35229. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  35230. // express x and y in the ground local system
  35231. x -= this.position.x;
  35232. z -= this.position.z;
  35233. x /= this.scaling.x;
  35234. z /= this.scaling.z;
  35235. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  35236. return;
  35237. }
  35238. if (!this._heightQuads || this._heightQuads.length == 0) {
  35239. this._initHeightQuads();
  35240. this._computeHeightQuads();
  35241. }
  35242. var facet = this._getFacetAt(x, z);
  35243. ref.x = facet.x;
  35244. ref.y = facet.y;
  35245. ref.z = facet.z;
  35246. };
  35247. /**
  35248. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  35249. * if the ground has been updated.
  35250. * This can be used in the render loop
  35251. */
  35252. GroundMesh.prototype.updateCoordinateHeights = function () {
  35253. if (!this._heightQuads || this._heightQuads.length == 0) {
  35254. this._initHeightQuads();
  35255. }
  35256. this._computeHeightQuads();
  35257. };
  35258. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  35259. GroundMesh.prototype._getFacetAt = function (x, z) {
  35260. // retrieve col and row from x, z coordinates in the ground local system
  35261. var subdivisionsX = this._subdivisionsX;
  35262. var subdivisionsY = this._subdivisionsY;
  35263. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  35264. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  35265. var quad = this._heightQuads[row * this._subdivisionsX + col];
  35266. var facet;
  35267. if (z < quad.slope.x * x + quad.slope.y) {
  35268. facet = quad.facet1;
  35269. }
  35270. else {
  35271. facet = quad.facet2;
  35272. }
  35273. return facet;
  35274. };
  35275. // Creates and populates the heightMap array with "facet" elements :
  35276. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  35277. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  35278. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  35279. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  35280. GroundMesh.prototype._initHeightQuads = function () {
  35281. var subdivisionsX = this._subdivisionsX;
  35282. var subdivisionsY = this._subdivisionsY;
  35283. this._heightQuads = new Array();
  35284. for (var row = 0; row < subdivisionsY; row++) {
  35285. for (var col = 0; col < subdivisionsX; col++) {
  35286. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  35287. this._heightQuads[row * subdivisionsX + col] = quad;
  35288. }
  35289. }
  35290. };
  35291. // Compute each quad element values and update the the heightMap array :
  35292. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  35293. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  35294. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  35295. GroundMesh.prototype._computeHeightQuads = function () {
  35296. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35297. var v1 = BABYLON.Tmp.Vector3[3];
  35298. var v2 = BABYLON.Tmp.Vector3[2];
  35299. var v3 = BABYLON.Tmp.Vector3[1];
  35300. var v4 = BABYLON.Tmp.Vector3[0];
  35301. var v1v2 = BABYLON.Tmp.Vector3[4];
  35302. var v1v3 = BABYLON.Tmp.Vector3[5];
  35303. var v1v4 = BABYLON.Tmp.Vector3[6];
  35304. var norm1 = BABYLON.Tmp.Vector3[7];
  35305. var norm2 = BABYLON.Tmp.Vector3[8];
  35306. var i = 0;
  35307. var j = 0;
  35308. var k = 0;
  35309. var cd = 0; // 2D slope coefficient : z = cd * x + h
  35310. var h = 0;
  35311. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  35312. var d2 = 0;
  35313. var subdivisionsX = this._subdivisionsX;
  35314. var subdivisionsY = this._subdivisionsY;
  35315. for (var row = 0; row < subdivisionsY; row++) {
  35316. for (var col = 0; col < subdivisionsX; col++) {
  35317. i = col * 3;
  35318. j = row * (subdivisionsX + 1) * 3;
  35319. k = (row + 1) * (subdivisionsX + 1) * 3;
  35320. v1.x = positions[j + i];
  35321. v1.y = positions[j + i + 1];
  35322. v1.z = positions[j + i + 2];
  35323. v2.x = positions[j + i + 3];
  35324. v2.y = positions[j + i + 4];
  35325. v2.z = positions[j + i + 5];
  35326. v3.x = positions[k + i];
  35327. v3.y = positions[k + i + 1];
  35328. v3.z = positions[k + i + 2];
  35329. v4.x = positions[k + i + 3];
  35330. v4.y = positions[k + i + 4];
  35331. v4.z = positions[k + i + 5];
  35332. // 2D slope V1V4
  35333. cd = (v4.z - v1.z) / (v4.x - v1.x);
  35334. h = v1.z - cd * v1.x; // v1 belongs to the slope
  35335. // facet equations :
  35336. // we compute each facet normal vector
  35337. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  35338. // we compute the value d by applying the equation to v1 which belongs to the plane
  35339. // then we store the facet equation in a Vector4
  35340. v2.subtractToRef(v1, v1v2);
  35341. v3.subtractToRef(v1, v1v3);
  35342. v4.subtractToRef(v1, v1v4);
  35343. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  35344. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  35345. norm1.normalize();
  35346. norm2.normalize();
  35347. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  35348. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  35349. var quad = this._heightQuads[row * subdivisionsX + col];
  35350. quad.slope.copyFromFloats(cd, h);
  35351. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  35352. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  35353. }
  35354. }
  35355. };
  35356. return GroundMesh;
  35357. })(BABYLON.Mesh);
  35358. BABYLON.GroundMesh = GroundMesh;
  35359. })(BABYLON || (BABYLON = {}));
  35360. var BABYLON;
  35361. (function (BABYLON) {
  35362. var LinesMesh = (function (_super) {
  35363. __extends(LinesMesh, _super);
  35364. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  35365. if (parent === void 0) { parent = null; }
  35366. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  35367. this.color = new BABYLON.Color3(1, 1, 1);
  35368. this.alpha = 1;
  35369. this._positionBuffer = {};
  35370. if (source) {
  35371. this.color = source.color.clone();
  35372. this.alpha = source.alpha;
  35373. }
  35374. this._intersectionThreshold = 0.1;
  35375. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  35376. attributes: [BABYLON.VertexBuffer.PositionKind],
  35377. uniforms: ["worldViewProjection", "color"],
  35378. needAlphaBlending: true
  35379. });
  35380. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  35381. }
  35382. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  35383. /**
  35384. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35385. * This margin is expressed in world space coordinates, so its value may vary.
  35386. * Default value is 0.1
  35387. * @returns the intersection Threshold value.
  35388. */
  35389. get: function () {
  35390. return this._intersectionThreshold;
  35391. },
  35392. /**
  35393. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35394. * This margin is expressed in world space coordinates, so its value may vary.
  35395. * @param value the new threshold to apply
  35396. */
  35397. set: function (value) {
  35398. if (this._intersectionThreshold === value) {
  35399. return;
  35400. }
  35401. this._intersectionThreshold = value;
  35402. if (this.geometry) {
  35403. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  35404. }
  35405. },
  35406. enumerable: true,
  35407. configurable: true
  35408. });
  35409. Object.defineProperty(LinesMesh.prototype, "material", {
  35410. get: function () {
  35411. return this._colorShader;
  35412. },
  35413. enumerable: true,
  35414. configurable: true
  35415. });
  35416. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  35417. get: function () {
  35418. return false;
  35419. },
  35420. enumerable: true,
  35421. configurable: true
  35422. });
  35423. LinesMesh.prototype.createInstance = function (name) {
  35424. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  35425. return null;
  35426. };
  35427. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  35428. var engine = this.getScene().getEngine();
  35429. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  35430. // VBOs
  35431. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  35432. // Color
  35433. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  35434. };
  35435. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  35436. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  35437. return;
  35438. }
  35439. var engine = this.getScene().getEngine();
  35440. // Draw order
  35441. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  35442. };
  35443. LinesMesh.prototype.dispose = function (doNotRecurse) {
  35444. this._colorShader.dispose();
  35445. _super.prototype.dispose.call(this, doNotRecurse);
  35446. };
  35447. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  35448. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  35449. };
  35450. return LinesMesh;
  35451. })(BABYLON.Mesh);
  35452. BABYLON.LinesMesh = LinesMesh;
  35453. })(BABYLON || (BABYLON = {}));
  35454. var BABYLON;
  35455. (function (BABYLON) {
  35456. var DefaultLoadingScreen = (function () {
  35457. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  35458. var _this = this;
  35459. if (_loadingText === void 0) { _loadingText = ""; }
  35460. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  35461. this._renderingCanvas = _renderingCanvas;
  35462. this._loadingText = _loadingText;
  35463. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  35464. // Resize
  35465. this._resizeLoadingUI = function () {
  35466. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  35467. _this._loadingDiv.style.position = "absolute";
  35468. _this._loadingDiv.style.left = canvasRect.left + "px";
  35469. _this._loadingDiv.style.top = canvasRect.top + "px";
  35470. _this._loadingDiv.style.width = canvasRect.width + "px";
  35471. _this._loadingDiv.style.height = canvasRect.height + "px";
  35472. };
  35473. }
  35474. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  35475. var _this = this;
  35476. if (this._loadingDiv) {
  35477. // Do not add a loading screen if there is already one
  35478. return;
  35479. }
  35480. this._loadingDiv = document.createElement("div");
  35481. this._loadingDiv.id = "babylonjsLoadingDiv";
  35482. this._loadingDiv.style.opacity = "0";
  35483. this._loadingDiv.style.transition = "opacity 1.5s ease";
  35484. // Loading text
  35485. this._loadingTextDiv = document.createElement("div");
  35486. this._loadingTextDiv.style.position = "absolute";
  35487. this._loadingTextDiv.style.left = "0";
  35488. this._loadingTextDiv.style.top = "50%";
  35489. this._loadingTextDiv.style.marginTop = "80px";
  35490. this._loadingTextDiv.style.width = "100%";
  35491. this._loadingTextDiv.style.height = "20px";
  35492. this._loadingTextDiv.style.fontFamily = "Arial";
  35493. this._loadingTextDiv.style.fontSize = "14px";
  35494. this._loadingTextDiv.style.color = "white";
  35495. this._loadingTextDiv.style.textAlign = "center";
  35496. this._loadingTextDiv.innerHTML = "Loading";
  35497. this._loadingDiv.appendChild(this._loadingTextDiv);
  35498. //set the predefined text
  35499. this._loadingTextDiv.innerHTML = this._loadingText;
  35500. // Loading img
  35501. var imgBack = new Image();
  35502. 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==";
  35503. imgBack.style.position = "absolute";
  35504. imgBack.style.left = "50%";
  35505. imgBack.style.top = "50%";
  35506. imgBack.style.marginLeft = "-50px";
  35507. imgBack.style.marginTop = "-50px";
  35508. imgBack.style.transition = "transform 1.0s ease";
  35509. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  35510. var deg = 360;
  35511. var onTransitionEnd = function () {
  35512. deg += 360;
  35513. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  35514. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  35515. };
  35516. imgBack.addEventListener("transitionend", onTransitionEnd);
  35517. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  35518. this._loadingDiv.appendChild(imgBack);
  35519. // front image
  35520. var imgFront = new Image();
  35521. 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=";
  35522. imgFront.style.position = "absolute";
  35523. imgFront.style.left = "50%";
  35524. imgFront.style.top = "50%";
  35525. imgFront.style.marginLeft = "-50px";
  35526. imgFront.style.marginTop = "-50px";
  35527. this._loadingDiv.appendChild(imgFront);
  35528. this._resizeLoadingUI();
  35529. window.addEventListener("resize", this._resizeLoadingUI);
  35530. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35531. document.body.appendChild(this._loadingDiv);
  35532. setTimeout(function () {
  35533. _this._loadingDiv.style.opacity = "1";
  35534. imgBack.style.transform = "rotateZ(360deg)";
  35535. imgBack.style.webkitTransform = "rotateZ(360deg)";
  35536. }, 0);
  35537. };
  35538. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  35539. var _this = this;
  35540. if (!this._loadingDiv) {
  35541. return;
  35542. }
  35543. var onTransitionEnd = function () {
  35544. if (!_this._loadingDiv) {
  35545. return;
  35546. }
  35547. document.body.removeChild(_this._loadingDiv);
  35548. window.removeEventListener("resize", _this._resizeLoadingUI);
  35549. _this._loadingDiv = null;
  35550. };
  35551. this._loadingDiv.style.opacity = "0";
  35552. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  35553. };
  35554. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  35555. set: function (text) {
  35556. this._loadingText = text;
  35557. if (this._loadingTextDiv) {
  35558. this._loadingTextDiv.innerHTML = this._loadingText;
  35559. }
  35560. },
  35561. enumerable: true,
  35562. configurable: true
  35563. });
  35564. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  35565. get: function () {
  35566. return this._loadingDivBackgroundColor;
  35567. },
  35568. set: function (color) {
  35569. this._loadingDivBackgroundColor = color;
  35570. if (!this._loadingDiv) {
  35571. return;
  35572. }
  35573. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35574. },
  35575. enumerable: true,
  35576. configurable: true
  35577. });
  35578. return DefaultLoadingScreen;
  35579. })();
  35580. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  35581. })(BABYLON || (BABYLON = {}));
  35582. var BABYLON;
  35583. (function (BABYLON) {
  35584. var AudioEngine = (function () {
  35585. function AudioEngine() {
  35586. this._audioContext = null;
  35587. this._audioContextInitialized = false;
  35588. this.canUseWebAudio = false;
  35589. this.WarnedWebAudioUnsupported = false;
  35590. this.unlocked = false;
  35591. this.isMP3supported = false;
  35592. this.isOGGsupported = false;
  35593. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35594. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35595. this.canUseWebAudio = true;
  35596. }
  35597. var audioElem = document.createElement('audio');
  35598. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  35599. this.isMP3supported = true;
  35600. }
  35601. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  35602. this.isOGGsupported = true;
  35603. }
  35604. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35605. this._unlockiOSaudio();
  35606. }
  35607. else {
  35608. this.unlocked = true;
  35609. }
  35610. }
  35611. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35612. get: function () {
  35613. if (!this._audioContextInitialized) {
  35614. this._initializeAudioContext();
  35615. }
  35616. return this._audioContext;
  35617. },
  35618. enumerable: true,
  35619. configurable: true
  35620. });
  35621. AudioEngine.prototype._unlockiOSaudio = function () {
  35622. var _this = this;
  35623. var unlockaudio = function () {
  35624. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35625. var source = _this.audioContext.createBufferSource();
  35626. source.buffer = buffer;
  35627. source.connect(_this.audioContext.destination);
  35628. source.start(0);
  35629. setTimeout(function () {
  35630. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35631. _this.unlocked = true;
  35632. window.removeEventListener('touchend', unlockaudio, false);
  35633. if (_this.onAudioUnlocked) {
  35634. _this.onAudioUnlocked();
  35635. }
  35636. }
  35637. }, 0);
  35638. };
  35639. window.addEventListener('touchend', unlockaudio, false);
  35640. };
  35641. AudioEngine.prototype._initializeAudioContext = function () {
  35642. try {
  35643. if (this.canUseWebAudio) {
  35644. this._audioContext = new AudioContext();
  35645. // create a global volume gain node
  35646. this.masterGain = this._audioContext.createGain();
  35647. this.masterGain.gain.value = 1;
  35648. this.masterGain.connect(this._audioContext.destination);
  35649. this._audioContextInitialized = true;
  35650. }
  35651. }
  35652. catch (e) {
  35653. this.canUseWebAudio = false;
  35654. BABYLON.Tools.Error("Web Audio: " + e.message);
  35655. }
  35656. };
  35657. AudioEngine.prototype.dispose = function () {
  35658. if (this.canUseWebAudio && this._audioContextInitialized) {
  35659. if (this._connectedAnalyser) {
  35660. this._connectedAnalyser.stopDebugCanvas();
  35661. this._connectedAnalyser.dispose();
  35662. this.masterGain.disconnect();
  35663. this.masterGain.connect(this._audioContext.destination);
  35664. this._connectedAnalyser = null;
  35665. }
  35666. this.masterGain.gain.value = 1;
  35667. }
  35668. this.WarnedWebAudioUnsupported = false;
  35669. };
  35670. AudioEngine.prototype.getGlobalVolume = function () {
  35671. if (this.canUseWebAudio && this._audioContextInitialized) {
  35672. return this.masterGain.gain.value;
  35673. }
  35674. else {
  35675. return -1;
  35676. }
  35677. };
  35678. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35679. if (this.canUseWebAudio && this._audioContextInitialized) {
  35680. this.masterGain.gain.value = newVolume;
  35681. }
  35682. };
  35683. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35684. if (this._connectedAnalyser) {
  35685. this._connectedAnalyser.stopDebugCanvas();
  35686. }
  35687. if (this.canUseWebAudio && this._audioContextInitialized) {
  35688. this._connectedAnalyser = analyser;
  35689. this.masterGain.disconnect();
  35690. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35691. }
  35692. };
  35693. return AudioEngine;
  35694. })();
  35695. BABYLON.AudioEngine = AudioEngine;
  35696. })(BABYLON || (BABYLON = {}));
  35697. var BABYLON;
  35698. (function (BABYLON) {
  35699. var Sound = (function () {
  35700. /**
  35701. * Create a sound and attach it to a scene
  35702. * @param name Name of your sound
  35703. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35704. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35705. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35706. */
  35707. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35708. var _this = this;
  35709. this.autoplay = false;
  35710. this.loop = false;
  35711. this.useCustomAttenuation = false;
  35712. this.spatialSound = false;
  35713. this.refDistance = 1;
  35714. this.rolloffFactor = 1;
  35715. this.maxDistance = 100;
  35716. this.distanceModel = "linear";
  35717. this._panningModel = "equalpower";
  35718. this._playbackRate = 1;
  35719. this._streaming = false;
  35720. this._startTime = 0;
  35721. this._startOffset = 0;
  35722. this._position = BABYLON.Vector3.Zero();
  35723. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35724. this._volume = 1;
  35725. this._isLoaded = false;
  35726. this._isReadyToPlay = false;
  35727. this.isPlaying = false;
  35728. this.isPaused = false;
  35729. this._isDirectional = false;
  35730. // Used if you'd like to create a directional sound.
  35731. // If not set, the sound will be omnidirectional
  35732. this._coneInnerAngle = 360;
  35733. this._coneOuterAngle = 360;
  35734. this._coneOuterGain = 0;
  35735. this._isOutputConnected = false;
  35736. this._urlType = "Unknown";
  35737. this.name = name;
  35738. this._scene = scene;
  35739. this._readyToPlayCallback = readyToPlayCallback;
  35740. // Default custom attenuation function is a linear attenuation
  35741. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  35742. if (currentDistance < maxDistance) {
  35743. return currentVolume * (1 - currentDistance / maxDistance);
  35744. }
  35745. else {
  35746. return 0;
  35747. }
  35748. };
  35749. if (options) {
  35750. this.autoplay = options.autoplay || false;
  35751. this.loop = options.loop || false;
  35752. // if volume === 0, we need another way to check this option
  35753. if (options.volume !== undefined) {
  35754. this._volume = options.volume;
  35755. }
  35756. this.spatialSound = options.spatialSound || false;
  35757. this.maxDistance = options.maxDistance || 100;
  35758. this.useCustomAttenuation = options.useCustomAttenuation || false;
  35759. this.rolloffFactor = options.rolloffFactor || 1;
  35760. this.refDistance = options.refDistance || 1;
  35761. this.distanceModel = options.distanceModel || "linear";
  35762. this._playbackRate = options.playbackRate || 1;
  35763. this._streaming = options.streaming || false;
  35764. }
  35765. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35766. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  35767. this._soundGain.gain.value = this._volume;
  35768. this._inputAudioNode = this._soundGain;
  35769. this._ouputAudioNode = this._soundGain;
  35770. if (this.spatialSound) {
  35771. this._createSpatialParameters();
  35772. }
  35773. this._scene.mainSoundTrack.AddSound(this);
  35774. var validParameter = true;
  35775. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  35776. if (urlOrArrayBuffer) {
  35777. if (typeof (urlOrArrayBuffer) === "string")
  35778. this._urlType = "String";
  35779. if (Array.isArray(urlOrArrayBuffer))
  35780. this._urlType = "Array";
  35781. if (urlOrArrayBuffer instanceof ArrayBuffer)
  35782. this._urlType = "ArrayBuffer";
  35783. var urls = [];
  35784. var codecSupportedFound = false;
  35785. switch (this._urlType) {
  35786. case "ArrayBuffer":
  35787. if (urlOrArrayBuffer.byteLength > 0) {
  35788. codecSupportedFound = true;
  35789. this._soundLoaded(urlOrArrayBuffer);
  35790. }
  35791. break;
  35792. case "String":
  35793. urls.push(urlOrArrayBuffer);
  35794. case "Array":
  35795. if (urls.length === 0)
  35796. urls = urlOrArrayBuffer;
  35797. // If we found a supported format, we load it immediately and stop the loop
  35798. for (var i = 0; i < urls.length; i++) {
  35799. var url = urls[i];
  35800. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  35801. codecSupportedFound = true;
  35802. }
  35803. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  35804. codecSupportedFound = true;
  35805. }
  35806. if (url.indexOf(".wav", url.length - 4) !== -1) {
  35807. codecSupportedFound = true;
  35808. }
  35809. if (codecSupportedFound) {
  35810. // Loading sound using XHR2
  35811. if (!this._streaming) {
  35812. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  35813. }
  35814. else {
  35815. this._htmlAudioElement = new Audio(url);
  35816. this._htmlAudioElement.controls = false;
  35817. this._htmlAudioElement.loop = this.loop;
  35818. this._htmlAudioElement.crossOrigin = "anonymous";
  35819. this._htmlAudioElement.preload = "auto";
  35820. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  35821. _this._isReadyToPlay = true;
  35822. if (_this.autoplay) {
  35823. _this.play();
  35824. }
  35825. if (_this._readyToPlayCallback) {
  35826. _this._readyToPlayCallback();
  35827. }
  35828. });
  35829. document.body.appendChild(this._htmlAudioElement);
  35830. }
  35831. break;
  35832. }
  35833. }
  35834. break;
  35835. default:
  35836. validParameter = false;
  35837. break;
  35838. }
  35839. if (!validParameter) {
  35840. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  35841. }
  35842. else {
  35843. if (!codecSupportedFound) {
  35844. // Simulating a ready to play event to avoid breaking code path
  35845. if (this._readyToPlayCallback) {
  35846. window.setTimeout(function () {
  35847. _this._readyToPlayCallback();
  35848. }, 1000);
  35849. }
  35850. }
  35851. }
  35852. }
  35853. }
  35854. else {
  35855. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  35856. this._scene.mainSoundTrack.AddSound(this);
  35857. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  35858. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  35859. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  35860. }
  35861. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  35862. if (this._readyToPlayCallback) {
  35863. window.setTimeout(function () {
  35864. _this._readyToPlayCallback();
  35865. }, 1000);
  35866. }
  35867. }
  35868. }
  35869. Sound.prototype.dispose = function () {
  35870. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  35871. if (this.isPlaying) {
  35872. this.stop();
  35873. }
  35874. this._isReadyToPlay = false;
  35875. if (this.soundTrackId === -1) {
  35876. this._scene.mainSoundTrack.RemoveSound(this);
  35877. }
  35878. else {
  35879. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  35880. }
  35881. if (this._soundGain) {
  35882. this._soundGain.disconnect();
  35883. this._soundGain = null;
  35884. }
  35885. if (this._soundPanner) {
  35886. this._soundPanner.disconnect();
  35887. this._soundPanner = null;
  35888. }
  35889. if (this._soundSource) {
  35890. this._soundSource.disconnect();
  35891. this._soundSource = null;
  35892. }
  35893. this._audioBuffer = null;
  35894. if (this._htmlAudioElement) {
  35895. this._htmlAudioElement.pause();
  35896. this._htmlAudioElement.src = "";
  35897. document.body.removeChild(this._htmlAudioElement);
  35898. }
  35899. if (this._connectedMesh) {
  35900. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35901. this._connectedMesh = null;
  35902. }
  35903. }
  35904. };
  35905. Sound.prototype._soundLoaded = function (audioData) {
  35906. var _this = this;
  35907. this._isLoaded = true;
  35908. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  35909. _this._audioBuffer = buffer;
  35910. _this._isReadyToPlay = true;
  35911. if (_this.autoplay) {
  35912. _this.play();
  35913. }
  35914. if (_this._readyToPlayCallback) {
  35915. _this._readyToPlayCallback();
  35916. }
  35917. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  35918. };
  35919. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  35920. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35921. this._audioBuffer = audioBuffer;
  35922. this._isReadyToPlay = true;
  35923. }
  35924. };
  35925. Sound.prototype.updateOptions = function (options) {
  35926. if (options) {
  35927. this.loop = options.loop || this.loop;
  35928. this.maxDistance = options.maxDistance || this.maxDistance;
  35929. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  35930. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  35931. this.refDistance = options.refDistance || this.refDistance;
  35932. this.distanceModel = options.distanceModel || this.distanceModel;
  35933. this._playbackRate = options.playbackRate || this._playbackRate;
  35934. this._updateSpatialParameters();
  35935. if (this.isPlaying) {
  35936. if (this._streaming) {
  35937. this._htmlAudioElement.playbackRate = this._playbackRate;
  35938. }
  35939. else {
  35940. this._soundSource.playbackRate.value = this._playbackRate;
  35941. }
  35942. }
  35943. }
  35944. };
  35945. Sound.prototype._createSpatialParameters = function () {
  35946. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35947. if (this._scene.headphone) {
  35948. this._panningModel = "HRTF";
  35949. }
  35950. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  35951. this._updateSpatialParameters();
  35952. this._soundPanner.connect(this._ouputAudioNode);
  35953. this._inputAudioNode = this._soundPanner;
  35954. }
  35955. };
  35956. Sound.prototype._updateSpatialParameters = function () {
  35957. if (this.spatialSound) {
  35958. if (this.useCustomAttenuation) {
  35959. // Tricks to disable in a way embedded Web Audio attenuation
  35960. this._soundPanner.distanceModel = "linear";
  35961. this._soundPanner.maxDistance = Number.MAX_VALUE;
  35962. this._soundPanner.refDistance = 1;
  35963. this._soundPanner.rolloffFactor = 1;
  35964. this._soundPanner.panningModel = this._panningModel;
  35965. }
  35966. else {
  35967. this._soundPanner.distanceModel = this.distanceModel;
  35968. this._soundPanner.maxDistance = this.maxDistance;
  35969. this._soundPanner.refDistance = this.refDistance;
  35970. this._soundPanner.rolloffFactor = this.rolloffFactor;
  35971. this._soundPanner.panningModel = this._panningModel;
  35972. }
  35973. }
  35974. };
  35975. Sound.prototype.switchPanningModelToHRTF = function () {
  35976. this._panningModel = "HRTF";
  35977. this._switchPanningModel();
  35978. };
  35979. Sound.prototype.switchPanningModelToEqualPower = function () {
  35980. this._panningModel = "equalpower";
  35981. this._switchPanningModel();
  35982. };
  35983. Sound.prototype._switchPanningModel = function () {
  35984. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35985. this._soundPanner.panningModel = this._panningModel;
  35986. }
  35987. };
  35988. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35989. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35990. if (this._isOutputConnected) {
  35991. this._ouputAudioNode.disconnect();
  35992. }
  35993. this._ouputAudioNode.connect(soundTrackAudioNode);
  35994. this._isOutputConnected = true;
  35995. }
  35996. };
  35997. /**
  35998. * Transform this sound into a directional source
  35999. * @param coneInnerAngle Size of the inner cone in degree
  36000. * @param coneOuterAngle Size of the outer cone in degree
  36001. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  36002. */
  36003. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  36004. if (coneOuterAngle < coneInnerAngle) {
  36005. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  36006. return;
  36007. }
  36008. this._coneInnerAngle = coneInnerAngle;
  36009. this._coneOuterAngle = coneOuterAngle;
  36010. this._coneOuterGain = coneOuterGain;
  36011. this._isDirectional = true;
  36012. if (this.isPlaying && this.loop) {
  36013. this.stop();
  36014. this.play();
  36015. }
  36016. };
  36017. Sound.prototype.setPosition = function (newPosition) {
  36018. this._position = newPosition;
  36019. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36020. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36021. }
  36022. };
  36023. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  36024. this._localDirection = newLocalDirection;
  36025. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  36026. this._updateDirection();
  36027. }
  36028. };
  36029. Sound.prototype._updateDirection = function () {
  36030. var mat = this._connectedMesh.getWorldMatrix();
  36031. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  36032. direction.normalize();
  36033. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  36034. };
  36035. Sound.prototype.updateDistanceFromListener = function () {
  36036. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  36037. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  36038. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  36039. }
  36040. };
  36041. Sound.prototype.setAttenuationFunction = function (callback) {
  36042. this._customAttenuationFunction = callback;
  36043. };
  36044. /**
  36045. * Play the sound
  36046. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  36047. * @param offset (optional) Start the sound setting it at a specific time
  36048. */
  36049. Sound.prototype.play = function (time, offset) {
  36050. var _this = this;
  36051. if (this._isReadyToPlay && this._scene.audioEnabled) {
  36052. try {
  36053. if (this._startOffset < 0) {
  36054. time = -this._startOffset;
  36055. this._startOffset = 0;
  36056. }
  36057. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36058. if (!this._soundSource || !this._streamingSource) {
  36059. if (this.spatialSound) {
  36060. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36061. if (this._isDirectional) {
  36062. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  36063. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  36064. this._soundPanner.coneOuterGain = this._coneOuterGain;
  36065. if (this._connectedMesh) {
  36066. this._updateDirection();
  36067. }
  36068. else {
  36069. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  36070. }
  36071. }
  36072. }
  36073. }
  36074. if (this._streaming) {
  36075. if (!this._streamingSource) {
  36076. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  36077. this._htmlAudioElement.onended = function () { _this._onended(); };
  36078. this._htmlAudioElement.playbackRate = this._playbackRate;
  36079. }
  36080. this._streamingSource.disconnect();
  36081. this._streamingSource.connect(this._inputAudioNode);
  36082. this._htmlAudioElement.play();
  36083. }
  36084. else {
  36085. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  36086. this._soundSource.buffer = this._audioBuffer;
  36087. this._soundSource.connect(this._inputAudioNode);
  36088. this._soundSource.loop = this.loop;
  36089. this._soundSource.playbackRate.value = this._playbackRate;
  36090. this._soundSource.onended = function () { _this._onended(); };
  36091. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  36092. }
  36093. this._startTime = startTime;
  36094. this.isPlaying = true;
  36095. this.isPaused = false;
  36096. }
  36097. catch (ex) {
  36098. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  36099. }
  36100. }
  36101. };
  36102. Sound.prototype._onended = function () {
  36103. this.isPlaying = false;
  36104. if (this.onended) {
  36105. this.onended();
  36106. }
  36107. };
  36108. /**
  36109. * Stop the sound
  36110. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  36111. */
  36112. Sound.prototype.stop = function (time) {
  36113. if (this.isPlaying) {
  36114. if (this._streaming) {
  36115. this._htmlAudioElement.pause();
  36116. // Test needed for Firefox or it will generate an Invalid State Error
  36117. if (this._htmlAudioElement.currentTime > 0) {
  36118. this._htmlAudioElement.currentTime = 0;
  36119. }
  36120. }
  36121. else {
  36122. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36123. this._soundSource.stop(stopTime);
  36124. this._soundSource.onended = null;
  36125. if (!this.isPaused) {
  36126. this._startOffset = 0;
  36127. }
  36128. }
  36129. this.isPlaying = false;
  36130. }
  36131. };
  36132. Sound.prototype.pause = function () {
  36133. if (this.isPlaying) {
  36134. this.isPaused = true;
  36135. if (this._streaming) {
  36136. this._htmlAudioElement.pause();
  36137. }
  36138. else {
  36139. this.stop(0);
  36140. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  36141. }
  36142. }
  36143. };
  36144. Sound.prototype.setVolume = function (newVolume, time) {
  36145. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36146. if (time) {
  36147. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  36148. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  36149. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  36150. }
  36151. else {
  36152. this._soundGain.gain.value = newVolume;
  36153. }
  36154. }
  36155. this._volume = newVolume;
  36156. };
  36157. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  36158. this._playbackRate = newPlaybackRate;
  36159. if (this.isPlaying) {
  36160. if (this._streaming) {
  36161. this._htmlAudioElement.playbackRate = this._playbackRate;
  36162. }
  36163. else {
  36164. this._soundSource.playbackRate.value = this._playbackRate;
  36165. }
  36166. }
  36167. };
  36168. Sound.prototype.getVolume = function () {
  36169. return this._volume;
  36170. };
  36171. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  36172. var _this = this;
  36173. if (this._connectedMesh) {
  36174. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36175. this._registerFunc = null;
  36176. }
  36177. this._connectedMesh = meshToConnectTo;
  36178. if (!this.spatialSound) {
  36179. this.spatialSound = true;
  36180. this._createSpatialParameters();
  36181. if (this.isPlaying && this.loop) {
  36182. this.stop();
  36183. this.play();
  36184. }
  36185. }
  36186. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  36187. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  36188. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  36189. };
  36190. Sound.prototype.detachFromMesh = function () {
  36191. if (this._connectedMesh) {
  36192. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36193. this._registerFunc = null;
  36194. this._connectedMesh = null;
  36195. }
  36196. };
  36197. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  36198. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  36199. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  36200. this._updateDirection();
  36201. }
  36202. };
  36203. Sound.prototype.clone = function () {
  36204. var _this = this;
  36205. if (!this._streaming) {
  36206. var setBufferAndRun = function () {
  36207. if (_this._isReadyToPlay) {
  36208. clonedSound._audioBuffer = _this.getAudioBuffer();
  36209. clonedSound._isReadyToPlay = true;
  36210. if (clonedSound.autoplay) {
  36211. clonedSound.play();
  36212. }
  36213. }
  36214. else {
  36215. window.setTimeout(setBufferAndRun, 300);
  36216. }
  36217. };
  36218. var currentOptions = {
  36219. autoplay: this.autoplay, loop: this.loop,
  36220. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  36221. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  36222. refDistance: this.refDistance, distanceModel: this.distanceModel
  36223. };
  36224. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  36225. if (this.useCustomAttenuation) {
  36226. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  36227. }
  36228. clonedSound.setPosition(this._position);
  36229. clonedSound.setPlaybackRate(this._playbackRate);
  36230. setBufferAndRun();
  36231. return clonedSound;
  36232. }
  36233. else {
  36234. return null;
  36235. }
  36236. };
  36237. Sound.prototype.getAudioBuffer = function () {
  36238. return this._audioBuffer;
  36239. };
  36240. Sound.prototype.serialize = function () {
  36241. var serializationObject = {
  36242. name: this.name,
  36243. url: this.name,
  36244. autoplay: this.autoplay,
  36245. loop: this.loop,
  36246. volume: this._volume,
  36247. spatialSound: this.spatialSound,
  36248. maxDistance: this.maxDistance,
  36249. rolloffFactor: this.rolloffFactor,
  36250. refDistance: this.refDistance,
  36251. distanceModel: this.distanceModel,
  36252. playbackRate: this._playbackRate,
  36253. panningModel: this._panningModel,
  36254. soundTrackId: this.soundTrackId
  36255. };
  36256. if (this.spatialSound) {
  36257. if (this._connectedMesh)
  36258. serializationObject.connectedMeshId = this._connectedMesh.id;
  36259. serializationObject.position = this._position.asArray();
  36260. serializationObject.refDistance = this.refDistance;
  36261. serializationObject.distanceModel = this.distanceModel;
  36262. serializationObject.isDirectional = this._isDirectional;
  36263. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  36264. serializationObject.coneInnerAngle = this._coneInnerAngle;
  36265. serializationObject.coneOuterAngle = this._coneOuterAngle;
  36266. serializationObject.coneOuterGain = this._coneOuterGain;
  36267. }
  36268. return serializationObject;
  36269. };
  36270. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  36271. var soundName = parsedSound.name;
  36272. var soundUrl;
  36273. if (parsedSound.url) {
  36274. soundUrl = rootUrl + parsedSound.url;
  36275. }
  36276. else {
  36277. soundUrl = rootUrl + soundName;
  36278. }
  36279. var options = {
  36280. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  36281. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  36282. rolloffFactor: parsedSound.rolloffFactor,
  36283. refDistance: parsedSound.refDistance,
  36284. distanceModel: parsedSound.distanceModel,
  36285. playbackRate: parsedSound.playbackRate
  36286. };
  36287. var newSound;
  36288. if (!sourceSound) {
  36289. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  36290. scene._addPendingData(newSound);
  36291. }
  36292. else {
  36293. var setBufferAndRun = function () {
  36294. if (sourceSound._isReadyToPlay) {
  36295. newSound._audioBuffer = sourceSound.getAudioBuffer();
  36296. newSound._isReadyToPlay = true;
  36297. if (newSound.autoplay) {
  36298. newSound.play();
  36299. }
  36300. }
  36301. else {
  36302. window.setTimeout(setBufferAndRun, 300);
  36303. }
  36304. };
  36305. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  36306. setBufferAndRun();
  36307. }
  36308. if (parsedSound.position) {
  36309. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  36310. newSound.setPosition(soundPosition);
  36311. }
  36312. if (parsedSound.isDirectional) {
  36313. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  36314. if (parsedSound.localDirectionToMesh) {
  36315. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  36316. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  36317. }
  36318. }
  36319. if (parsedSound.connectedMeshId) {
  36320. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  36321. if (connectedMesh) {
  36322. newSound.attachToMesh(connectedMesh);
  36323. }
  36324. }
  36325. return newSound;
  36326. };
  36327. return Sound;
  36328. })();
  36329. BABYLON.Sound = Sound;
  36330. })(BABYLON || (BABYLON = {}));
  36331. var BABYLON;
  36332. (function (BABYLON) {
  36333. var SoundTrack = (function () {
  36334. function SoundTrack(scene, options) {
  36335. this.id = -1;
  36336. this._isMainTrack = false;
  36337. this._isInitialized = false;
  36338. this._scene = scene;
  36339. this.soundCollection = new Array();
  36340. this._options = options;
  36341. if (!this._isMainTrack) {
  36342. this._scene.soundTracks.push(this);
  36343. this.id = this._scene.soundTracks.length - 1;
  36344. }
  36345. }
  36346. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  36347. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36348. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  36349. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  36350. if (this._options) {
  36351. if (this._options.volume) {
  36352. this._outputAudioNode.gain.value = this._options.volume;
  36353. }
  36354. if (this._options.mainTrack) {
  36355. this._isMainTrack = this._options.mainTrack;
  36356. }
  36357. }
  36358. this._isInitialized = true;
  36359. }
  36360. };
  36361. SoundTrack.prototype.dispose = function () {
  36362. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36363. if (this._connectedAnalyser) {
  36364. this._connectedAnalyser.stopDebugCanvas();
  36365. }
  36366. while (this.soundCollection.length) {
  36367. this.soundCollection[0].dispose();
  36368. }
  36369. if (this._outputAudioNode) {
  36370. this._outputAudioNode.disconnect();
  36371. }
  36372. this._outputAudioNode = null;
  36373. }
  36374. };
  36375. SoundTrack.prototype.AddSound = function (sound) {
  36376. if (!this._isInitialized) {
  36377. this._initializeSoundTrackAudioGraph();
  36378. }
  36379. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36380. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  36381. }
  36382. if (sound.soundTrackId) {
  36383. if (sound.soundTrackId === -1) {
  36384. this._scene.mainSoundTrack.RemoveSound(sound);
  36385. }
  36386. else {
  36387. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  36388. }
  36389. }
  36390. this.soundCollection.push(sound);
  36391. sound.soundTrackId = this.id;
  36392. };
  36393. SoundTrack.prototype.RemoveSound = function (sound) {
  36394. var index = this.soundCollection.indexOf(sound);
  36395. if (index !== -1) {
  36396. this.soundCollection.splice(index, 1);
  36397. }
  36398. };
  36399. SoundTrack.prototype.setVolume = function (newVolume) {
  36400. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36401. this._outputAudioNode.gain.value = newVolume;
  36402. }
  36403. };
  36404. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  36405. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36406. for (var i = 0; i < this.soundCollection.length; i++) {
  36407. this.soundCollection[i].switchPanningModelToHRTF();
  36408. }
  36409. }
  36410. };
  36411. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  36412. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36413. for (var i = 0; i < this.soundCollection.length; i++) {
  36414. this.soundCollection[i].switchPanningModelToEqualPower();
  36415. }
  36416. }
  36417. };
  36418. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  36419. if (this._connectedAnalyser) {
  36420. this._connectedAnalyser.stopDebugCanvas();
  36421. }
  36422. this._connectedAnalyser = analyser;
  36423. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36424. this._outputAudioNode.disconnect();
  36425. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  36426. }
  36427. };
  36428. return SoundTrack;
  36429. })();
  36430. BABYLON.SoundTrack = SoundTrack;
  36431. })(BABYLON || (BABYLON = {}));
  36432. var BABYLON;
  36433. (function (BABYLON) {
  36434. var DebugLayer = (function () {
  36435. function DebugLayer(scene) {
  36436. var _this = this;
  36437. this._transformationMatrix = BABYLON.Matrix.Identity();
  36438. this._enabled = false;
  36439. this._labelsEnabled = false;
  36440. this._displayStatistics = true;
  36441. this._displayTree = false;
  36442. this._displayLogs = false;
  36443. this._skeletonViewers = new Array();
  36444. this._identityMatrix = BABYLON.Matrix.Identity();
  36445. this.axisRatio = 0.02;
  36446. this.accentColor = "orange";
  36447. this._scene = scene;
  36448. this._syncPositions = function () {
  36449. var engine = _this._scene.getEngine();
  36450. var canvasRect = engine.getRenderingCanvasClientRect();
  36451. if (_this._showUI) {
  36452. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  36453. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  36454. _this._statsDiv.style.width = "400px";
  36455. _this._statsDiv.style.height = "auto";
  36456. _this._statsSubsetDiv.style.maxHeight = "240px";
  36457. _this._optionsDiv.style.left = "0px";
  36458. _this._optionsDiv.style.top = "10px";
  36459. _this._optionsDiv.style.width = "200px";
  36460. _this._optionsDiv.style.height = "auto";
  36461. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  36462. _this._logDiv.style.left = "0px";
  36463. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  36464. _this._logDiv.style.width = "600px";
  36465. _this._logDiv.style.height = "160px";
  36466. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  36467. _this._treeDiv.style.top = "10px";
  36468. _this._treeDiv.style.width = "300px";
  36469. _this._treeDiv.style.height = "auto";
  36470. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  36471. }
  36472. _this._globalDiv.style.left = canvasRect.left + "px";
  36473. _this._globalDiv.style.top = canvasRect.top + "px";
  36474. _this._drawingCanvas.style.left = "0px";
  36475. _this._drawingCanvas.style.top = "0px";
  36476. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  36477. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  36478. var devicePixelRatio = window.devicePixelRatio || 1;
  36479. var context = _this._drawingContext;
  36480. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  36481. context.mozBackingStorePixelRatio ||
  36482. context.msBackingStorePixelRatio ||
  36483. context.oBackingStorePixelRatio ||
  36484. context.backingStorePixelRatio || 1;
  36485. _this._ratio = devicePixelRatio / backingStoreRatio;
  36486. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  36487. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  36488. };
  36489. this._onCanvasClick = function (evt) {
  36490. _this._clickPosition = {
  36491. x: evt.clientX * _this._ratio,
  36492. y: evt.clientY * _this._ratio
  36493. };
  36494. };
  36495. this._syncUI = function () {
  36496. if (_this._showUI) {
  36497. if (_this._displayStatistics) {
  36498. _this._displayStats();
  36499. _this._statsDiv.style.display = "";
  36500. }
  36501. else {
  36502. _this._statsDiv.style.display = "none";
  36503. }
  36504. if (_this._displayLogs) {
  36505. _this._logDiv.style.display = "";
  36506. }
  36507. else {
  36508. _this._logDiv.style.display = "none";
  36509. }
  36510. if (_this._displayTree) {
  36511. _this._treeDiv.style.display = "";
  36512. if (_this._needToRefreshMeshesTree) {
  36513. _this._needToRefreshMeshesTree = false;
  36514. _this._refreshMeshesTreeContent();
  36515. }
  36516. }
  36517. else {
  36518. _this._treeDiv.style.display = "none";
  36519. }
  36520. }
  36521. };
  36522. this._syncData = function () {
  36523. if (_this._labelsEnabled || !_this._showUI) {
  36524. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  36525. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  36526. var engine = _this._scene.getEngine();
  36527. var viewport = _this._camera.viewport;
  36528. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  36529. // Meshes
  36530. var meshes = _this._camera.getActiveMeshes();
  36531. var index;
  36532. var projectedPosition;
  36533. for (index = 0; index < meshes.length; index++) {
  36534. var mesh = meshes.data[index];
  36535. var position = mesh.getBoundingInfo().boundingSphere.center;
  36536. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36537. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  36538. _this._renderAxis(projectedPosition, mesh, globalViewport);
  36539. }
  36540. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  36541. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  36542. }
  36543. }
  36544. // Cameras
  36545. var cameras = _this._scene.cameras;
  36546. for (index = 0; index < cameras.length; index++) {
  36547. var camera = cameras[index];
  36548. if (camera === _this._camera) {
  36549. continue;
  36550. }
  36551. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36552. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  36553. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  36554. _this._camera.detachControl(engine.getRenderingCanvas());
  36555. _this._camera = camera;
  36556. _this._camera.attachControl(engine.getRenderingCanvas());
  36557. }, function () { return "purple"; });
  36558. }
  36559. }
  36560. // Lights
  36561. var lights = _this._scene.lights;
  36562. for (index = 0; index < lights.length; index++) {
  36563. var light = lights[index];
  36564. if (light.position) {
  36565. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  36566. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  36567. _this._renderLabel(light.name, projectedPosition, -20, function () {
  36568. light.setEnabled(!light.isEnabled());
  36569. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  36570. }
  36571. }
  36572. }
  36573. }
  36574. _this._clickPosition = undefined;
  36575. };
  36576. }
  36577. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  36578. while (this._treeSubsetDiv.hasChildNodes()) {
  36579. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  36580. }
  36581. // Add meshes
  36582. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  36583. sortedArray.sort(function (a, b) {
  36584. if (a.name === b.name) {
  36585. return 0;
  36586. }
  36587. return (a.name > b.name) ? 1 : -1;
  36588. });
  36589. for (var index = 0; index < sortedArray.length; index++) {
  36590. var mesh = sortedArray[index];
  36591. if (!mesh.isEnabled()) {
  36592. continue;
  36593. }
  36594. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  36595. m.isVisible = element.checked;
  36596. }, mesh);
  36597. }
  36598. };
  36599. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  36600. this._drawingContext.beginPath();
  36601. this._drawingContext.moveTo(zero.x, zero.y);
  36602. this._drawingContext.lineTo(unit.x, unit.y);
  36603. this._drawingContext.strokeStyle = color;
  36604. this._drawingContext.lineWidth = 4;
  36605. this._drawingContext.stroke();
  36606. this._drawingContext.font = "normal 14px Segoe UI";
  36607. this._drawingContext.fillStyle = color;
  36608. this._drawingContext.fillText(label, unitText.x, unitText.y);
  36609. };
  36610. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  36611. var position = mesh.getBoundingInfo().boundingSphere.center;
  36612. var worldMatrix = mesh.getWorldMatrix();
  36613. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  36614. var unit = (unprojectedVector.subtract(position)).length();
  36615. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36616. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36617. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  36618. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36619. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36620. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  36621. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  36622. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  36623. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  36624. };
  36625. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  36626. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  36627. this._drawingContext.font = "normal 12px Segoe UI";
  36628. var textMetrics = this._drawingContext.measureText(text);
  36629. var centerX = projectedPosition.x - textMetrics.width / 2;
  36630. var centerY = projectedPosition.y;
  36631. var clientRect = this._drawingCanvas.getBoundingClientRect();
  36632. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  36633. onClick();
  36634. }
  36635. this._drawingContext.beginPath();
  36636. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  36637. this._drawingContext.fillStyle = getFillStyle();
  36638. this._drawingContext.globalAlpha = 0.5;
  36639. this._drawingContext.fill();
  36640. this._drawingContext.globalAlpha = 1.0;
  36641. this._drawingContext.strokeStyle = '#FFFFFF';
  36642. this._drawingContext.lineWidth = 1;
  36643. this._drawingContext.stroke();
  36644. this._drawingContext.fillStyle = "#FFFFFF";
  36645. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  36646. this._drawingContext.beginPath();
  36647. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  36648. this._drawingContext.fill();
  36649. }
  36650. };
  36651. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  36652. if (!this._clickPosition) {
  36653. return false;
  36654. }
  36655. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  36656. return false;
  36657. }
  36658. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  36659. return false;
  36660. }
  36661. return true;
  36662. };
  36663. DebugLayer.prototype.isVisible = function () {
  36664. return this._enabled;
  36665. };
  36666. DebugLayer.prototype.hide = function () {
  36667. if (!this._enabled) {
  36668. return;
  36669. }
  36670. this._enabled = false;
  36671. var engine = this._scene.getEngine();
  36672. this._scene.unregisterBeforeRender(this._syncData);
  36673. this._scene.unregisterAfterRender(this._syncUI);
  36674. this._rootElement.removeChild(this._globalDiv);
  36675. this._scene.forceShowBoundingBoxes = false;
  36676. this._scene.forceWireframe = false;
  36677. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  36678. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  36679. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  36680. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  36681. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  36682. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  36683. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  36684. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  36685. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  36686. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  36687. this._scene.shadowsEnabled = true;
  36688. this._scene.particlesEnabled = true;
  36689. this._scene.postProcessesEnabled = true;
  36690. this._scene.collisionsEnabled = true;
  36691. this._scene.lightsEnabled = true;
  36692. this._scene.texturesEnabled = true;
  36693. this._scene.lensFlaresEnabled = true;
  36694. this._scene.proceduralTexturesEnabled = true;
  36695. this._scene.renderTargetsEnabled = true;
  36696. this._scene.probesEnabled = true;
  36697. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  36698. this._clearSkeletonViewers();
  36699. };
  36700. DebugLayer.prototype._clearSkeletonViewers = function () {
  36701. for (var index = 0; index < this._skeletonViewers.length; index++) {
  36702. this._skeletonViewers[index].dispose();
  36703. }
  36704. this._skeletonViewers = [];
  36705. };
  36706. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  36707. if (showUI === void 0) { showUI = true; }
  36708. if (camera === void 0) { camera = null; }
  36709. if (rootElement === void 0) { rootElement = null; }
  36710. if (this._enabled) {
  36711. return;
  36712. }
  36713. this._enabled = true;
  36714. if (camera) {
  36715. this._camera = camera;
  36716. }
  36717. else {
  36718. this._camera = this._scene.activeCamera;
  36719. }
  36720. this._showUI = showUI;
  36721. var engine = this._scene.getEngine();
  36722. this._globalDiv = document.createElement("div");
  36723. this._rootElement = rootElement || document.body;
  36724. this._rootElement.appendChild(this._globalDiv);
  36725. this._generateDOMelements();
  36726. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  36727. this._syncPositions();
  36728. this._scene.registerBeforeRender(this._syncData);
  36729. this._scene.registerAfterRender(this._syncUI);
  36730. };
  36731. DebugLayer.prototype._clearLabels = function () {
  36732. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  36733. for (var index = 0; index < this._scene.meshes.length; index++) {
  36734. var mesh = this._scene.meshes[index];
  36735. mesh.renderOverlay = false;
  36736. }
  36737. };
  36738. DebugLayer.prototype._generateheader = function (root, text) {
  36739. var header = document.createElement("div");
  36740. header.innerHTML = text + "&nbsp;";
  36741. header.style.textAlign = "right";
  36742. header.style.width = "100%";
  36743. header.style.color = "white";
  36744. header.style.backgroundColor = "Black";
  36745. header.style.padding = "5px 5px 4px 0px";
  36746. header.style.marginLeft = "-5px";
  36747. header.style.fontWeight = "bold";
  36748. root.appendChild(header);
  36749. };
  36750. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  36751. var label = document.createElement("label");
  36752. label.style.display = "inline";
  36753. label.innerHTML = title;
  36754. label.style.color = color;
  36755. root.appendChild(label);
  36756. root.appendChild(document.createElement("br"));
  36757. };
  36758. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  36759. if (tag === void 0) { tag = null; }
  36760. var label = document.createElement("label");
  36761. label.style.display = "inline";
  36762. var boundingBoxesCheckbox = document.createElement("input");
  36763. boundingBoxesCheckbox.type = "checkbox";
  36764. boundingBoxesCheckbox.checked = initialState;
  36765. boundingBoxesCheckbox.style.display = "inline";
  36766. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  36767. boundingBoxesCheckbox.style.verticalAlign = "sub";
  36768. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  36769. task(evt.target, tag);
  36770. });
  36771. label.appendChild(boundingBoxesCheckbox);
  36772. var container = document.createElement("span");
  36773. var leftPart = document.createElement("span");
  36774. var rightPart = document.createElement("span");
  36775. rightPart.style.cssFloat = "right";
  36776. leftPart.innerHTML = leftTitle;
  36777. rightPart.innerHTML = rightTitle;
  36778. rightPart.style.fontSize = "12px";
  36779. rightPart.style.maxWidth = "200px";
  36780. container.appendChild(leftPart);
  36781. container.appendChild(rightPart);
  36782. label.appendChild(container);
  36783. root.appendChild(label);
  36784. root.appendChild(document.createElement("br"));
  36785. };
  36786. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  36787. if (tag === void 0) { tag = null; }
  36788. var label = document.createElement("label");
  36789. label.style.display = "inline";
  36790. var checkBox = document.createElement("input");
  36791. checkBox.type = "checkbox";
  36792. checkBox.checked = initialState;
  36793. checkBox.style.display = "inline";
  36794. checkBox.style.margin = "0px 5px 0px 0px";
  36795. checkBox.style.verticalAlign = "sub";
  36796. checkBox.addEventListener("change", function (evt) {
  36797. task(evt.target, tag);
  36798. });
  36799. label.appendChild(checkBox);
  36800. label.appendChild(document.createTextNode(title));
  36801. root.appendChild(label);
  36802. root.appendChild(document.createElement("br"));
  36803. };
  36804. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  36805. if (tag === void 0) { tag = null; }
  36806. var button = document.createElement("button");
  36807. button.innerHTML = title;
  36808. button.style.height = "24px";
  36809. button.style.width = "150px";
  36810. button.style.marginBottom = "5px";
  36811. button.style.color = "#444444";
  36812. button.style.border = "1px solid white";
  36813. button.className = "debugLayerButton";
  36814. button.addEventListener("click", function (evt) {
  36815. task(evt.target, tag);
  36816. });
  36817. root.appendChild(button);
  36818. root.appendChild(document.createElement("br"));
  36819. };
  36820. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  36821. if (tag === void 0) { tag = null; }
  36822. var label = document.createElement("label");
  36823. label.style.display = "inline";
  36824. var boundingBoxesRadio = document.createElement("input");
  36825. boundingBoxesRadio.type = "radio";
  36826. boundingBoxesRadio.name = name;
  36827. boundingBoxesRadio.checked = initialState;
  36828. boundingBoxesRadio.style.display = "inline";
  36829. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  36830. boundingBoxesRadio.style.verticalAlign = "sub";
  36831. boundingBoxesRadio.addEventListener("change", function (evt) {
  36832. task(evt.target, tag);
  36833. });
  36834. label.appendChild(boundingBoxesRadio);
  36835. label.appendChild(document.createTextNode(title));
  36836. root.appendChild(label);
  36837. root.appendChild(document.createElement("br"));
  36838. };
  36839. DebugLayer.prototype._generateDOMelements = function () {
  36840. var _this = this;
  36841. this._globalDiv.id = "DebugLayer";
  36842. this._globalDiv.style.position = "absolute";
  36843. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  36844. this._globalDiv.style.fontSize = "14px";
  36845. this._globalDiv.style.color = "white";
  36846. // Drawing canvas
  36847. this._drawingCanvas = document.createElement("canvas");
  36848. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  36849. this._drawingCanvas.style.position = "absolute";
  36850. this._drawingCanvas.style.pointerEvents = "none";
  36851. this._drawingCanvas.style.backgroundColor = "transparent";
  36852. this._drawingContext = this._drawingCanvas.getContext("2d");
  36853. this._globalDiv.appendChild(this._drawingCanvas);
  36854. if (this._showUI) {
  36855. var background = "rgba(128, 128, 128, 0.4)";
  36856. var border = "rgb(180, 180, 180) solid 1px";
  36857. // Stats
  36858. this._statsDiv = document.createElement("div");
  36859. this._statsDiv.id = "DebugLayerStats";
  36860. this._statsDiv.style.border = border;
  36861. this._statsDiv.style.position = "absolute";
  36862. this._statsDiv.style.background = background;
  36863. this._statsDiv.style.padding = "0px 0px 0px 5px";
  36864. this._generateheader(this._statsDiv, "STATISTICS");
  36865. this._statsSubsetDiv = document.createElement("div");
  36866. this._statsSubsetDiv.style.paddingTop = "5px";
  36867. this._statsSubsetDiv.style.paddingBottom = "5px";
  36868. this._statsSubsetDiv.style.overflowY = "auto";
  36869. this._statsDiv.appendChild(this._statsSubsetDiv);
  36870. // Tree
  36871. this._treeDiv = document.createElement("div");
  36872. this._treeDiv.id = "DebugLayerTree";
  36873. this._treeDiv.style.border = border;
  36874. this._treeDiv.style.position = "absolute";
  36875. this._treeDiv.style.background = background;
  36876. this._treeDiv.style.padding = "0px 0px 0px 5px";
  36877. this._treeDiv.style.display = "none";
  36878. this._generateheader(this._treeDiv, "MESHES TREE");
  36879. this._treeSubsetDiv = document.createElement("div");
  36880. this._treeSubsetDiv.style.paddingTop = "5px";
  36881. this._treeSubsetDiv.style.paddingRight = "5px";
  36882. this._treeSubsetDiv.style.overflowY = "auto";
  36883. this._treeSubsetDiv.style.maxHeight = "300px";
  36884. this._treeDiv.appendChild(this._treeSubsetDiv);
  36885. this._needToRefreshMeshesTree = true;
  36886. // Logs
  36887. this._logDiv = document.createElement("div");
  36888. this._logDiv.style.border = border;
  36889. this._logDiv.id = "DebugLayerLogs";
  36890. this._logDiv.style.position = "absolute";
  36891. this._logDiv.style.background = background;
  36892. this._logDiv.style.padding = "0px 0px 0px 5px";
  36893. this._logDiv.style.display = "none";
  36894. this._generateheader(this._logDiv, "LOGS");
  36895. this._logSubsetDiv = document.createElement("div");
  36896. this._logSubsetDiv.style.height = "127px";
  36897. this._logSubsetDiv.style.paddingTop = "5px";
  36898. this._logSubsetDiv.style.overflowY = "auto";
  36899. this._logSubsetDiv.style.fontSize = "12px";
  36900. this._logSubsetDiv.style.fontFamily = "consolas";
  36901. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  36902. this._logDiv.appendChild(this._logSubsetDiv);
  36903. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  36904. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  36905. };
  36906. // Options
  36907. this._optionsDiv = document.createElement("div");
  36908. this._optionsDiv.id = "DebugLayerOptions";
  36909. this._optionsDiv.style.border = border;
  36910. this._optionsDiv.style.position = "absolute";
  36911. this._optionsDiv.style.background = background;
  36912. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  36913. this._optionsDiv.style.overflowY = "auto";
  36914. this._generateheader(this._optionsDiv, "OPTIONS");
  36915. this._optionsSubsetDiv = document.createElement("div");
  36916. this._optionsSubsetDiv.style.paddingTop = "5px";
  36917. this._optionsSubsetDiv.style.paddingBottom = "5px";
  36918. this._optionsSubsetDiv.style.overflowY = "auto";
  36919. this._optionsSubsetDiv.style.maxHeight = "200px";
  36920. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  36921. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  36922. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  36923. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  36924. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  36925. _this._displayTree = element.checked;
  36926. _this._needToRefreshMeshesTree = true;
  36927. });
  36928. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36929. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  36930. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  36931. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  36932. _this._labelsEnabled = element.checked;
  36933. if (!_this._labelsEnabled) {
  36934. _this._clearLabels();
  36935. }
  36936. });
  36937. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  36938. if (element.checked) {
  36939. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  36940. }
  36941. else {
  36942. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  36943. }
  36944. });
  36945. ;
  36946. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36947. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  36948. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  36949. if (element.checked) {
  36950. _this._scene.forceWireframe = false;
  36951. _this._scene.forcePointsCloud = false;
  36952. }
  36953. });
  36954. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  36955. if (element.checked) {
  36956. _this._scene.forceWireframe = true;
  36957. _this._scene.forcePointsCloud = false;
  36958. }
  36959. });
  36960. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  36961. if (element.checked) {
  36962. _this._scene.forceWireframe = false;
  36963. _this._scene.forcePointsCloud = true;
  36964. }
  36965. });
  36966. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36967. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  36968. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  36969. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  36970. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  36971. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  36972. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  36973. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  36974. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  36975. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  36976. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  36977. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  36978. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  36979. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36980. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  36981. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  36982. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  36983. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  36984. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  36985. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  36986. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  36987. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  36988. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  36989. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  36990. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  36991. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  36992. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  36993. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  36994. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  36995. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  36996. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36997. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  36998. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  36999. if (element.checked) {
  37000. _this._scene.headphone = true;
  37001. }
  37002. });
  37003. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  37004. if (element.checked) {
  37005. _this._scene.headphone = false;
  37006. }
  37007. });
  37008. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  37009. _this._scene.audioEnabled = !element.checked;
  37010. });
  37011. }
  37012. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  37013. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  37014. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  37015. if (!element.checked) {
  37016. _this._clearSkeletonViewers();
  37017. return;
  37018. }
  37019. for (var index = 0; index < _this._scene.meshes.length; index++) {
  37020. var mesh = _this._scene.meshes[index];
  37021. if (mesh.skeleton) {
  37022. var found = false;
  37023. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  37024. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  37025. found = true;
  37026. break;
  37027. }
  37028. }
  37029. if (found) {
  37030. continue;
  37031. }
  37032. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  37033. viewer.isEnabled = true;
  37034. _this._skeletonViewers.push(viewer);
  37035. }
  37036. }
  37037. });
  37038. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  37039. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  37040. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  37041. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  37042. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  37043. if (_this._camera) {
  37044. console.log(_this._camera);
  37045. }
  37046. else {
  37047. console.warn("No camera defined, or debug layer created before camera creation!");
  37048. }
  37049. });
  37050. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  37051. this._globalDiv.appendChild(this._statsDiv);
  37052. this._globalDiv.appendChild(this._logDiv);
  37053. this._globalDiv.appendChild(this._optionsDiv);
  37054. this._globalDiv.appendChild(this._treeDiv);
  37055. }
  37056. };
  37057. DebugLayer.prototype._displayStats = function () {
  37058. var scene = this._scene;
  37059. var engine = scene.getEngine();
  37060. var glInfo = engine.getGlInfo();
  37061. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  37062. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  37063. + "<b>Count</b><br>"
  37064. + "Total meshes: " + scene.meshes.length + "<br>"
  37065. + "Total lights: " + scene.lights.length + "<br>"
  37066. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  37067. + "Total materials: " + scene.materials.length + "<br>"
  37068. + "Total textures: " + scene.textures.length + "<br>"
  37069. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  37070. + "Active indices: " + scene.getActiveIndices() + "<br>"
  37071. + "Active bones: " + scene.getActiveBones() + "<br>"
  37072. + "Active particles: " + scene.getActiveParticles() + "<br>"
  37073. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  37074. + "<b>Duration</b><br>"
  37075. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  37076. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  37077. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  37078. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  37079. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  37080. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  37081. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  37082. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  37083. + "</div>"
  37084. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  37085. + "<b>Extensions</b><br>"
  37086. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  37087. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  37088. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  37089. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  37090. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  37091. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  37092. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  37093. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  37094. + "</div><br>"
  37095. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  37096. + "<b>Caps.</b><br>"
  37097. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  37098. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  37099. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  37100. + "<b>Info</b><br>"
  37101. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  37102. + glInfo.version + "<br>"
  37103. + "</div><br>"
  37104. + glInfo.renderer + "<br>";
  37105. if (this.customStatsFunction) {
  37106. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  37107. }
  37108. };
  37109. return DebugLayer;
  37110. })();
  37111. BABYLON.DebugLayer = DebugLayer;
  37112. })(BABYLON || (BABYLON = {}));
  37113. var BABYLON;
  37114. (function (BABYLON) {
  37115. var SIMDVector3 = (function () {
  37116. function SIMDVector3() {
  37117. }
  37118. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  37119. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  37120. };
  37121. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  37122. var m = transformation.m;
  37123. var m0 = SIMD.Float32x4.load(m, 0);
  37124. var m1 = SIMD.Float32x4.load(m, 4);
  37125. var m2 = SIMD.Float32x4.load(m, 8);
  37126. var m3 = SIMD.Float32x4.load(m, 12);
  37127. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  37128. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  37129. result.x = SIMD.Float32x4.extractLane(r, 0);
  37130. result.y = SIMD.Float32x4.extractLane(r, 1);
  37131. result.z = SIMD.Float32x4.extractLane(r, 2);
  37132. };
  37133. return SIMDVector3;
  37134. })();
  37135. var SIMDMatrix = (function () {
  37136. function SIMDMatrix() {
  37137. }
  37138. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  37139. var tm = this.m;
  37140. var om = other.m;
  37141. var m0 = SIMD.Float32x4.load(om, 0);
  37142. var m1 = SIMD.Float32x4.load(om, 4);
  37143. var m2 = SIMD.Float32x4.load(om, 8);
  37144. var m3 = SIMD.Float32x4.load(om, 12);
  37145. for (var i = 0; i < 16; i += 4) {
  37146. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  37147. }
  37148. return this;
  37149. };
  37150. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  37151. var src = this.m;
  37152. var dest = other.m;
  37153. // Load the 4 rows
  37154. var src0 = SIMD.Float32x4.load(src, 0);
  37155. var src1 = SIMD.Float32x4.load(src, 4);
  37156. var src2 = SIMD.Float32x4.load(src, 8);
  37157. var src3 = SIMD.Float32x4.load(src, 12);
  37158. // Transpose the source matrix. Sort of. Not a true transpose operation
  37159. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  37160. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  37161. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  37162. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  37163. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  37164. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  37165. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  37166. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  37167. // This is a true transposition, but it will lead to an incorrect result
  37168. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  37169. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  37170. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37171. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37172. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  37173. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  37174. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37175. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37176. // ----
  37177. tmp1 = SIMD.Float32x4.mul(row2, row3);
  37178. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37179. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  37180. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  37181. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37182. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  37183. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  37184. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  37185. // ----
  37186. tmp1 = SIMD.Float32x4.mul(row1, row2);
  37187. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37188. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  37189. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  37190. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37191. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  37192. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  37193. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  37194. // ----
  37195. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  37196. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37197. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  37198. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  37199. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  37200. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37201. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  37202. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  37203. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  37204. // ----
  37205. tmp1 = SIMD.Float32x4.mul(row0, row1);
  37206. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37207. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37208. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  37209. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37210. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37211. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  37212. // ----
  37213. tmp1 = SIMD.Float32x4.mul(row0, row3);
  37214. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37215. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  37216. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  37217. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37218. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  37219. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  37220. // ----
  37221. tmp1 = SIMD.Float32x4.mul(row0, row2);
  37222. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37223. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  37224. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  37225. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37226. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  37227. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  37228. // Compute determinant
  37229. var det = SIMD.Float32x4.mul(row0, minor0);
  37230. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  37231. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  37232. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  37233. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  37234. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  37235. // These shuffles aren't necessary if the faulty transposition is done
  37236. // up at the top of this function.
  37237. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  37238. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  37239. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  37240. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  37241. // Compute final values by multiplying with 1/det
  37242. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  37243. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  37244. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  37245. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  37246. return this;
  37247. };
  37248. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  37249. var out = result.m;
  37250. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  37251. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  37252. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  37253. // cc.kmVec3Subtract(f, pCenter, pEye);
  37254. var f = SIMD.Float32x4.sub(center, eye);
  37255. // cc.kmVec3Normalize(f, f);
  37256. var tmp = SIMD.Float32x4.mul(f, f);
  37257. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37258. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37259. // cc.kmVec3Assign(up, pUp);
  37260. // cc.kmVec3Normalize(up, up);
  37261. tmp = SIMD.Float32x4.mul(up, up);
  37262. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37263. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37264. // cc.kmVec3Cross(s, f, up);
  37265. 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)));
  37266. // cc.kmVec3Normalize(s, s);
  37267. tmp = SIMD.Float32x4.mul(s, s);
  37268. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37269. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37270. // cc.kmVec3Cross(u, s, f);
  37271. 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)));
  37272. // cc.kmVec3Normalize(s, s);
  37273. tmp = SIMD.Float32x4.mul(s, s);
  37274. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37275. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37276. var zero = SIMD.Float32x4.splat(0.0);
  37277. s = SIMD.Float32x4.neg(s);
  37278. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  37279. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  37280. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  37281. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  37282. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  37283. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  37284. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  37285. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37286. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  37287. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37288. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  37289. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37290. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  37291. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  37292. };
  37293. return SIMDMatrix;
  37294. })();
  37295. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  37296. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  37297. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  37298. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  37299. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  37300. var SIMDHelper = (function () {
  37301. function SIMDHelper() {
  37302. }
  37303. Object.defineProperty(SIMDHelper, "IsEnabled", {
  37304. get: function () {
  37305. return SIMDHelper._isEnabled;
  37306. },
  37307. enumerable: true,
  37308. configurable: true
  37309. });
  37310. SIMDHelper.DisableSIMD = function () {
  37311. // Replace functions
  37312. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  37313. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  37314. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  37315. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  37316. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  37317. SIMDHelper._isEnabled = false;
  37318. };
  37319. SIMDHelper.EnableSIMD = function () {
  37320. if (self.SIMD === undefined) {
  37321. return;
  37322. }
  37323. // check if polyfills needed
  37324. if (!self.Math.fround) {
  37325. self.Math.fround = (function (array) { return function (x) {
  37326. return array[0] = x, array[0];
  37327. }; })(new Float32Array(1));
  37328. }
  37329. if (!self.Math.imul) {
  37330. self.Math.imul = function (a, b) {
  37331. var ah = (a >>> 16) & 0xffff;
  37332. var al = a & 0xffff;
  37333. var bh = (b >>> 16) & 0xffff;
  37334. var bl = b & 0xffff;
  37335. // the shift by 0 fixes the sign on the high part
  37336. // the final |0 converts the unsigned value into a signed value
  37337. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  37338. };
  37339. }
  37340. // Replace functions
  37341. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  37342. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  37343. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  37344. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  37345. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  37346. SIMDHelper._isEnabled = true;
  37347. };
  37348. SIMDHelper._isEnabled = false;
  37349. return SIMDHelper;
  37350. })();
  37351. BABYLON.SIMDHelper = SIMDHelper;
  37352. })(BABYLON || (BABYLON = {}));
  37353. var BABYLON;
  37354. (function (BABYLON) {
  37355. /**
  37356. * This class describe a rectangle that were added to the map.
  37357. * You have access to its coordinates either in pixel or normalized (UV)
  37358. */
  37359. var PackedRect = (function () {
  37360. function PackedRect(root, parent, pos, size) {
  37361. this._pos = pos;
  37362. this._size = size;
  37363. this._root = root;
  37364. this._parent = parent;
  37365. }
  37366. Object.defineProperty(PackedRect.prototype, "pos", {
  37367. /**
  37368. * @returns the position of this node into the map
  37369. */
  37370. get: function () {
  37371. return this._pos;
  37372. },
  37373. enumerable: true,
  37374. configurable: true
  37375. });
  37376. Object.defineProperty(PackedRect.prototype, "contentSize", {
  37377. /**
  37378. * @returns the size of the rectangle this node handles
  37379. */
  37380. get: function () {
  37381. return this._contentSize;
  37382. },
  37383. enumerable: true,
  37384. configurable: true
  37385. });
  37386. Object.defineProperty(PackedRect.prototype, "UVs", {
  37387. /**
  37388. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  37389. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  37390. */
  37391. get: function () {
  37392. return this.getUVsForCustomSize(this._root._size);
  37393. },
  37394. enumerable: true,
  37395. configurable: true
  37396. });
  37397. /**
  37398. * 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.
  37399. * This method will return the UVs for this part by given the custom size of what you really use
  37400. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  37401. */
  37402. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  37403. var mainWidth = this._root._size.width;
  37404. var mainHeight = this._root._size.height;
  37405. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  37406. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  37407. var uvs = new Array();
  37408. uvs.push(topLeft);
  37409. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  37410. uvs.push(rightBottom);
  37411. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  37412. return uvs;
  37413. };
  37414. /**
  37415. * Free this rectangle from the map.
  37416. * Call this method when you no longer need the rectangle to be in the map.
  37417. */
  37418. PackedRect.prototype.freeContent = function () {
  37419. if (!this.contentSize) {
  37420. return;
  37421. }
  37422. this._contentSize = null;
  37423. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  37424. this.attemptDefrag();
  37425. };
  37426. Object.defineProperty(PackedRect.prototype, "isUsed", {
  37427. get: function () {
  37428. return this._contentSize != null || this._leftNode != null;
  37429. },
  37430. enumerable: true,
  37431. configurable: true
  37432. });
  37433. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  37434. var node = this.findNode(contentSize);
  37435. // Not enough space...
  37436. if (!node) {
  37437. return null;
  37438. }
  37439. node.splitNode(contentSize);
  37440. return node;
  37441. };
  37442. PackedRect.prototype.findNode = function (size) {
  37443. var resNode = null;
  37444. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  37445. if (this.isUsed) {
  37446. if (this._leftNode) {
  37447. resNode = this._leftNode.findNode(size);
  37448. }
  37449. if (!resNode && this._rightNode) {
  37450. resNode = this._rightNode.findNode(size);
  37451. }
  37452. if (!resNode && this._bottomNode) {
  37453. resNode = this._bottomNode.findNode(size);
  37454. }
  37455. }
  37456. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  37457. resNode = this;
  37458. }
  37459. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  37460. resNode = this;
  37461. }
  37462. return resNode;
  37463. };
  37464. PackedRect.prototype.splitNode = function (contentSize) {
  37465. // 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)
  37466. if (!this._contentSize && this._initialSize) {
  37467. 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));
  37468. return this._leftNode.splitNode(contentSize);
  37469. }
  37470. else {
  37471. this._contentSize = contentSize.clone();
  37472. this._initialSize = contentSize.clone();
  37473. if (contentSize.width !== this._size.width) {
  37474. 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));
  37475. }
  37476. if (contentSize.height !== this._size.height) {
  37477. 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));
  37478. }
  37479. return this;
  37480. }
  37481. };
  37482. PackedRect.prototype.attemptDefrag = function () {
  37483. if (!this.isUsed && this.isRecursiveFree) {
  37484. this.clearNode();
  37485. if (this._parent) {
  37486. this._parent.attemptDefrag();
  37487. }
  37488. }
  37489. };
  37490. PackedRect.prototype.clearNode = function () {
  37491. this._initialSize = null;
  37492. this._rightNode = null;
  37493. this._bottomNode = null;
  37494. };
  37495. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  37496. get: function () {
  37497. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  37498. },
  37499. enumerable: true,
  37500. configurable: true
  37501. });
  37502. PackedRect.prototype.evalFreeSize = function (size) {
  37503. var levelSize = 0;
  37504. if (!this.isUsed) {
  37505. if (this._initialSize) {
  37506. levelSize = this._initialSize.surface;
  37507. }
  37508. else {
  37509. levelSize = this._size.surface;
  37510. }
  37511. }
  37512. if (this._rightNode) {
  37513. levelSize += this._rightNode.evalFreeSize(0);
  37514. }
  37515. if (this._bottomNode) {
  37516. levelSize += this._bottomNode.evalFreeSize(0);
  37517. }
  37518. return levelSize + size;
  37519. };
  37520. return PackedRect;
  37521. })();
  37522. BABYLON.PackedRect = PackedRect;
  37523. /**
  37524. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  37525. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  37526. * 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.
  37527. */
  37528. var RectPackingMap = (function (_super) {
  37529. __extends(RectPackingMap, _super);
  37530. /**
  37531. * Create an instance of the object with a dimension using the given size
  37532. * @param size The dimension of the rectangle that will contain all the sub ones.
  37533. */
  37534. function RectPackingMap(size) {
  37535. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  37536. this._root = this;
  37537. }
  37538. /**
  37539. * Add a rectangle, finding the best location to store it into the map
  37540. * @param size the dimension of the rectangle to store
  37541. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  37542. */
  37543. RectPackingMap.prototype.addRect = function (size) {
  37544. var node = this.findAndSplitNode(size);
  37545. return node;
  37546. };
  37547. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  37548. /**
  37549. * Return the current space free normalized between [0;1]
  37550. * @returns {}
  37551. */
  37552. get: function () {
  37553. var freeSize = 0;
  37554. freeSize = this.evalFreeSize(freeSize);
  37555. return freeSize / (this._size.width * this._size.height);
  37556. },
  37557. enumerable: true,
  37558. configurable: true
  37559. });
  37560. return RectPackingMap;
  37561. })(PackedRect);
  37562. BABYLON.RectPackingMap = RectPackingMap;
  37563. })(BABYLON || (BABYLON = {}));
  37564. var BABYLON;
  37565. (function (BABYLON) {
  37566. var DynamicFloatArrayElementInfo = (function () {
  37567. function DynamicFloatArrayElementInfo() {
  37568. }
  37569. return DynamicFloatArrayElementInfo;
  37570. })();
  37571. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  37572. /**
  37573. * 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.
  37574. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  37575. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  37576. * 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.
  37577. * 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.
  37578. * 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".
  37579. */
  37580. var DynamicFloatArray = (function () {
  37581. /**
  37582. * Construct an instance of the dynamic float array
  37583. * @param stride size of one element in float (i.e. not bytes!)
  37584. * @param initialElementCount the number of available entries at construction
  37585. */
  37586. function DynamicFloatArray(stride, initialElementCount) {
  37587. this.compareValueOffset = null;
  37588. this.sortingAscending = true;
  37589. this._stride = stride;
  37590. this.buffer = new Float32Array(stride * initialElementCount);
  37591. this._lastUsed = 0;
  37592. this._firstFree = 0;
  37593. this._allEntries = new Array(initialElementCount);
  37594. this._freeEntries = new Array(initialElementCount);
  37595. for (var i = 0; i < initialElementCount; i++) {
  37596. var element = new DynamicFloatArrayElementInfo();
  37597. element.offset = i * stride;
  37598. this._allEntries[i] = element;
  37599. this._freeEntries[initialElementCount - i - 1] = element;
  37600. }
  37601. }
  37602. /**
  37603. * Allocate an element in the array.
  37604. * @return the element info instance that contains the offset into the main buffer of the element's location.
  37605. * Beware, this offset may change when you call pack()
  37606. */
  37607. DynamicFloatArray.prototype.allocElement = function () {
  37608. if (this._freeEntries.length === 0) {
  37609. this._growBuffer();
  37610. }
  37611. var el = this._freeEntries.pop();
  37612. this._lastUsed = Math.max(el.offset, this._lastUsed);
  37613. if (el.offset === this._firstFree) {
  37614. if (this._freeEntries.length > 0) {
  37615. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  37616. }
  37617. else {
  37618. this._firstFree += this._stride;
  37619. }
  37620. }
  37621. return el;
  37622. };
  37623. /**
  37624. * Free the element corresponding to the given element info
  37625. * @param elInfo the element that describe the allocated element
  37626. */
  37627. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  37628. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  37629. this._freeEntries.push(elInfo);
  37630. };
  37631. /**
  37632. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  37633. * 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().
  37634. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  37635. */
  37636. DynamicFloatArray.prototype.pack = function () {
  37637. // no free slot? no need to pack
  37638. if (this._freeEntries.length === 0) {
  37639. return this.buffer;
  37640. }
  37641. // If the buffer is already packed the last used will always be lower than the first free
  37642. // 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.
  37643. if (this._lastUsed < this._firstFree) {
  37644. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  37645. return elementsBuffer_1;
  37646. }
  37647. var s = this._stride;
  37648. // 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
  37649. var lastFree = new DynamicFloatArrayElementInfo();
  37650. lastFree.offset = this.totalElementCount * s;
  37651. this._freeEntries.push(lastFree);
  37652. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  37653. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37654. var firstFreeSlotOffset = sortedFree[0].offset;
  37655. var freeZoneSize = 1;
  37656. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  37657. var prevOffset = sortedFree[0].offset;
  37658. for (var i = 1; i < sortedFree.length; i++) {
  37659. // 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
  37660. if (firstFreeSlotOffset >= occupiedZoneSize) {
  37661. break;
  37662. }
  37663. var curFree = sortedFree[i];
  37664. var curOffset = curFree.offset;
  37665. // Compute the distance between this offset and the previous
  37666. var distance = curOffset - prevOffset;
  37667. // If the distance is the stride size, they are adjacent, it good, move to the next
  37668. if (distance === s) {
  37669. // Free zone is one element bigger
  37670. ++freeZoneSize;
  37671. // as we're about to iterate to the next, the cur becomes the previous...
  37672. prevOffset = curOffset;
  37673. continue;
  37674. }
  37675. // Distance is bigger, which means there's x element between the previous free and this one
  37676. var usedRange = (distance / s) - 1;
  37677. // Two cases the free zone is smaller than the data to move or bigger
  37678. // Copy what can fit in the free zone
  37679. var curMoveOffset = curOffset - s;
  37680. var copyCount = Math.min(freeZoneSize, usedRange);
  37681. for (var j = 0; j < copyCount; j++) {
  37682. var freeI = firstFreeSlotOffset / s;
  37683. var curI = curMoveOffset / s;
  37684. var moveEl = sortedAll[curI];
  37685. this._moveElement(moveEl, firstFreeSlotOffset);
  37686. var replacedEl = sortedAll[freeI];
  37687. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  37688. replacedEl.offset = curMoveOffset;
  37689. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  37690. sortedAll[freeI] = moveEl;
  37691. sortedAll[curI] = replacedEl;
  37692. curMoveOffset -= s;
  37693. firstFreeSlotOffset += s;
  37694. }
  37695. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  37696. if (freeZoneSize <= usedRange) {
  37697. firstFreeSlotOffset = curMoveOffset + s;
  37698. freeZoneSize = 1 + copyCount;
  37699. }
  37700. else {
  37701. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  37702. }
  37703. // as we're about to iterate to the next, the cur becomes the previous...
  37704. prevOffset = curOffset;
  37705. }
  37706. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  37707. this._lastUsed = firstFreeSlotOffset - s;
  37708. this._firstFree = firstFreeSlotOffset;
  37709. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  37710. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  37711. this._allEntries = sortedAll;
  37712. return elementsBuffer;
  37713. };
  37714. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  37715. for (var i = 0; i < this._stride; i++) {
  37716. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  37717. }
  37718. element.offset = destOffset;
  37719. };
  37720. DynamicFloatArray.prototype._growBuffer = function () {
  37721. // Allocate the new buffer with 50% more entries, copy the content of the current one
  37722. var newElCount = Math.floor(this.totalElementCount * 1.5);
  37723. var newBuffer = new Float32Array(newElCount * this._stride);
  37724. newBuffer.set(this.buffer);
  37725. var curCount = this.totalElementCount;
  37726. var addedCount = newElCount - this.totalElementCount;
  37727. for (var i = 0; i < addedCount; i++) {
  37728. var element = new DynamicFloatArrayElementInfo();
  37729. element.offset = (curCount + i) * this.stride;
  37730. this._allEntries.push(element);
  37731. this._freeEntries[addedCount - i - 1] = element;
  37732. }
  37733. this._firstFree = curCount * this.stride;
  37734. this.buffer = newBuffer;
  37735. };
  37736. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  37737. /**
  37738. * Get the total count of entries that can fit in the current buffer
  37739. * @returns the elements count
  37740. */
  37741. get: function () {
  37742. return this._allEntries.length;
  37743. },
  37744. enumerable: true,
  37745. configurable: true
  37746. });
  37747. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  37748. /**
  37749. * Get the count of free entries that can still be allocated without resizing the buffer
  37750. * @returns the free elements count
  37751. */
  37752. get: function () {
  37753. return this._freeEntries.length;
  37754. },
  37755. enumerable: true,
  37756. configurable: true
  37757. });
  37758. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  37759. /**
  37760. * Get the count of allocated elements
  37761. * @returns the allocated elements count
  37762. */
  37763. get: function () {
  37764. return this._allEntries.length - this._freeEntries.length;
  37765. },
  37766. enumerable: true,
  37767. configurable: true
  37768. });
  37769. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  37770. /**
  37771. * Return the size of one element in float
  37772. * @returns the size in float
  37773. */
  37774. get: function () {
  37775. return this._stride;
  37776. },
  37777. enumerable: true,
  37778. configurable: true
  37779. });
  37780. DynamicFloatArray.prototype.sort = function () {
  37781. var _this = this;
  37782. if (!this.compareValueOffset) {
  37783. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  37784. }
  37785. var count = this.usedElementCount;
  37786. // Do we have to (re)create the sort table?
  37787. if (!this._sortTable || this._sortTable.length < count) {
  37788. // 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...
  37789. var newCount = Math.min(this.totalElementCount, count * 2);
  37790. this._sortTable = new Array(newCount);
  37791. }
  37792. if (!this._sortedTable || this._sortedTable.length !== count) {
  37793. this._sortedTable = new Array(count);
  37794. }
  37795. // Because, you know...
  37796. this.pack();
  37797. //let stride = this.stride;
  37798. //for (let i = 0; i < count; i++) {
  37799. // let si = this._sortTable[i];
  37800. // if (!si) {
  37801. // si = new SortInfo();
  37802. // this._sortTable[i] = si;
  37803. // }
  37804. // si.entry = this._allEntries[i];
  37805. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  37806. // si.swapedOffset = null;
  37807. // this._sortedTable[i] = si;
  37808. //}
  37809. var curOffset = 0;
  37810. var stride = this.stride;
  37811. for (var i = 0; i < count; i++, curOffset += stride) {
  37812. var si = this._sortTable[i];
  37813. if (!si) {
  37814. si = new SortInfo();
  37815. this._sortTable[i] = si;
  37816. }
  37817. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  37818. si.offset = curOffset;
  37819. si.swapedOffset = null;
  37820. this._sortedTable[i] = si;
  37821. }
  37822. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  37823. if (this.sortingAscending) {
  37824. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  37825. }
  37826. else {
  37827. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  37828. }
  37829. var swapElements = function (src, dst) {
  37830. for (var i = 0; i < stride; i++) {
  37831. var tps = _this.buffer[dst + i];
  37832. _this.buffer[dst + i] = _this.buffer[src + i];
  37833. _this.buffer[src + i] = tps;
  37834. }
  37835. };
  37836. // 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:
  37837. // 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),
  37838. // and I still want something with a good algorithm complexity.
  37839. // 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,
  37840. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  37841. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  37842. // 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
  37843. // until we find a SortInfo object without a swapedOffset which means we got the right location
  37844. // 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
  37845. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  37846. for (var i = 0; i < count; i++) {
  37847. // Get the element to move
  37848. var sourceSI = this._sortedTable[i];
  37849. var destSI = this._sortTable[i];
  37850. var sourceOff = sourceSI.offset;
  37851. // If the source changed location, find the new one
  37852. if (sourceSI.swapedOffset) {
  37853. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  37854. var curSI = sourceSI;
  37855. while (curSI.swapedOffset) {
  37856. curSI = this._sortTable[curSI.swapedOffset / stride];
  37857. }
  37858. // Finally get the right location
  37859. sourceOff = curSI.offset;
  37860. }
  37861. // Tag the element being replaced with its new location
  37862. destSI.swapedOffset = sourceOff;
  37863. // Swap elements (only if needed)
  37864. if (sourceOff !== destSI.offset) {
  37865. swapElements(sourceOff, destSI.offset);
  37866. }
  37867. // Update the offset in the corresponding DFAE
  37868. //sourceSI.entry.offset = destSI.entry.offset;
  37869. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  37870. }
  37871. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37872. return true;
  37873. };
  37874. return DynamicFloatArray;
  37875. })();
  37876. BABYLON.DynamicFloatArray = DynamicFloatArray;
  37877. var SortInfo = (function () {
  37878. function SortInfo() {
  37879. this.compareData = this.offset = this.swapedOffset = null;
  37880. }
  37881. return SortInfo;
  37882. })();
  37883. })(BABYLON || (BABYLON = {}));
  37884. var BABYLON;
  37885. (function (BABYLON) {
  37886. /**
  37887. * This class given information about a given character.
  37888. */
  37889. var CharInfo = (function () {
  37890. function CharInfo() {
  37891. }
  37892. return CharInfo;
  37893. })();
  37894. BABYLON.CharInfo = CharInfo;
  37895. var FontTexture = (function (_super) {
  37896. __extends(FontTexture, _super);
  37897. /**
  37898. * Create a new instance of the FontTexture class
  37899. * @param name the name of the texture
  37900. * @param font the font to use, use the W3C CSS notation
  37901. * @param scene the scene that owns the texture
  37902. * @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
  37903. * @param samplingMode the texture sampling mode
  37904. * @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.
  37905. */
  37906. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  37907. if (maxCharCount === void 0) { maxCharCount = 200; }
  37908. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37909. if (superSample === void 0) { superSample = false; }
  37910. _super.call(this, null, scene, true, false, samplingMode);
  37911. this._charInfos = {};
  37912. this._curCharCount = 0;
  37913. this._lastUpdateCharCount = -1;
  37914. this._usedCounter = 1;
  37915. this.name = name;
  37916. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37917. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37918. this._superSample = false;
  37919. if (superSample) {
  37920. var sfont = this.getSuperSampleFont(font);
  37921. if (sfont) {
  37922. this._superSample = true;
  37923. font = sfont;
  37924. }
  37925. }
  37926. // First canvas creation to determine the size of the texture to create
  37927. this._canvas = document.createElement("canvas");
  37928. this._context = this._canvas.getContext("2d");
  37929. this._context.font = font;
  37930. this._context.fillStyle = "white";
  37931. this._cachedFontId = null;
  37932. var res = this.getFontHeight(font);
  37933. this._lineHeightSuper = res.height;
  37934. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  37935. this._offset = res.offset - 1;
  37936. var maxCharWidth = this._context.measureText("W").width;
  37937. this._spaceWidthSuper = this._context.measureText(" ").width;
  37938. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  37939. // This is an approximate size, but should always be able to fit at least the maxCharCount
  37940. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  37941. var edge = Math.sqrt(totalEstSurface);
  37942. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  37943. // Create the texture that will store the font characters
  37944. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  37945. var textureSize = this.getSize();
  37946. this.hasAlpha = true;
  37947. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  37948. this._canvas = document.createElement("canvas");
  37949. this._canvas.width = textureSize.width;
  37950. this._canvas.height = textureSize.height;
  37951. this._context = this._canvas.getContext("2d");
  37952. this._context.textBaseline = "top";
  37953. this._context.font = font;
  37954. this._context.fillStyle = "white";
  37955. this._context.imageSmoothingEnabled = false;
  37956. this._currentFreePosition = BABYLON.Vector2.Zero();
  37957. // Add the basic ASCII based characters
  37958. for (var i = 0x20; i < 0x7F; i++) {
  37959. var c = String.fromCharCode(i);
  37960. this.getChar(c);
  37961. }
  37962. this.update();
  37963. }
  37964. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  37965. get: function () {
  37966. return this._superSample;
  37967. },
  37968. enumerable: true,
  37969. configurable: true
  37970. });
  37971. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  37972. get: function () {
  37973. return this._spaceWidth;
  37974. },
  37975. enumerable: true,
  37976. configurable: true
  37977. });
  37978. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  37979. get: function () {
  37980. return this._lineHeight;
  37981. },
  37982. enumerable: true,
  37983. configurable: true
  37984. });
  37985. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  37986. if (supersample === void 0) { supersample = false; }
  37987. var s = scene;
  37988. if (!s.__fontTextureCache__) {
  37989. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  37990. }
  37991. var dic = s.__fontTextureCache__;
  37992. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  37993. var ft = dic.get(lfn);
  37994. if (ft) {
  37995. ++ft._usedCounter;
  37996. return ft;
  37997. }
  37998. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  37999. ft._cachedFontId = lfn;
  38000. dic.add(lfn, ft);
  38001. return ft;
  38002. };
  38003. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  38004. if (supersample === void 0) { supersample = false; }
  38005. var s = scene;
  38006. var dic = s.__fontTextureCache__;
  38007. if (!dic) {
  38008. return;
  38009. }
  38010. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  38011. var font = dic.get(lfn);
  38012. if (--font._usedCounter === 0) {
  38013. dic.remove(lfn);
  38014. font.dispose();
  38015. }
  38016. };
  38017. /**
  38018. * Make sure the given char is present in the font map.
  38019. * @param char the character to get or add
  38020. * @return the CharInfo instance corresponding to the given character
  38021. */
  38022. FontTexture.prototype.getChar = function (char) {
  38023. if (char.length !== 1) {
  38024. return null;
  38025. }
  38026. var info = this._charInfos[char];
  38027. if (info) {
  38028. return info;
  38029. }
  38030. info = new CharInfo();
  38031. var measure = this._context.measureText(char);
  38032. var textureSize = this.getSize();
  38033. // we reached the end of the current line?
  38034. var width = Math.round(measure.width);
  38035. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  38036. var yMargin = xMargin;
  38037. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  38038. this._currentFreePosition.x = 0;
  38039. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  38040. // No more room?
  38041. if (this._currentFreePosition.y > textureSize.height) {
  38042. return this.getChar("!");
  38043. }
  38044. }
  38045. // Draw the character in the texture
  38046. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  38047. // Fill the CharInfo object
  38048. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  38049. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  38050. info.charWidth = this._superSample ? (width / 2) : width;
  38051. // Add the info structure
  38052. this._charInfos[char] = info;
  38053. this._curCharCount++;
  38054. // Set the next position
  38055. this._currentFreePosition.x += width + xMargin;
  38056. return info;
  38057. };
  38058. FontTexture.prototype.measureText = function (text, tabulationSize) {
  38059. if (tabulationSize === void 0) { tabulationSize = 4; }
  38060. var maxWidth = 0;
  38061. var curWidth = 0;
  38062. var lineCount = 1;
  38063. var charxpos = 0;
  38064. // Parse each char of the string
  38065. for (var _i = 0; _i < text.length; _i++) {
  38066. var char = text[_i];
  38067. // Next line feed?
  38068. if (char === "\n") {
  38069. maxWidth = Math.max(maxWidth, curWidth);
  38070. charxpos = 0;
  38071. curWidth = 0;
  38072. ++lineCount;
  38073. continue;
  38074. }
  38075. // Tabulation ?
  38076. if (char === "\t") {
  38077. var nextPos = charxpos + tabulationSize;
  38078. nextPos = nextPos - (nextPos % tabulationSize);
  38079. curWidth += (nextPos - charxpos) * this.spaceWidth;
  38080. charxpos = nextPos;
  38081. continue;
  38082. }
  38083. if (char < " ") {
  38084. continue;
  38085. }
  38086. curWidth += this.getChar(char).charWidth;
  38087. ++charxpos;
  38088. }
  38089. maxWidth = Math.max(maxWidth, curWidth);
  38090. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  38091. };
  38092. FontTexture.prototype.getSuperSampleFont = function (font) {
  38093. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  38094. 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*$/;
  38095. var res = font.toLocaleLowerCase().match(regex);
  38096. if (res == null) {
  38097. return null;
  38098. }
  38099. var size = parseInt(res[4]);
  38100. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  38101. var newFont = "";
  38102. for (var j = 1; j < res.length; j++) {
  38103. if (res[j] != null) {
  38104. newFont += res[j] + " ";
  38105. }
  38106. }
  38107. return newFont;
  38108. };
  38109. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  38110. FontTexture.prototype.getFontHeight = function (font) {
  38111. var fontDraw = document.createElement("canvas");
  38112. var ctx = fontDraw.getContext('2d');
  38113. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  38114. ctx.textBaseline = 'top';
  38115. ctx.fillStyle = 'white';
  38116. ctx.font = font;
  38117. ctx.fillText('jH|', 0, 0);
  38118. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  38119. var start = -1;
  38120. var end = -1;
  38121. for (var row = 0; row < fontDraw.height; row++) {
  38122. for (var column = 0; column < fontDraw.width; column++) {
  38123. var index = (row * fontDraw.width + column) * 4;
  38124. if (pixels[index] === 0) {
  38125. if (column === fontDraw.width - 1 && start !== -1) {
  38126. end = row;
  38127. row = fontDraw.height;
  38128. break;
  38129. }
  38130. continue;
  38131. }
  38132. else {
  38133. if (start === -1) {
  38134. start = row;
  38135. }
  38136. break;
  38137. }
  38138. }
  38139. }
  38140. return { height: (end - start) + 1, offset: start - 1 };
  38141. };
  38142. Object.defineProperty(FontTexture.prototype, "canRescale", {
  38143. get: function () {
  38144. return false;
  38145. },
  38146. enumerable: true,
  38147. configurable: true
  38148. });
  38149. FontTexture.prototype.getContext = function () {
  38150. return this._context;
  38151. };
  38152. /**
  38153. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  38154. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  38155. */
  38156. FontTexture.prototype.update = function () {
  38157. // Update only if there's new char added since the previous update
  38158. if (this._lastUpdateCharCount < this._curCharCount) {
  38159. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  38160. this._lastUpdateCharCount = this._curCharCount;
  38161. }
  38162. };
  38163. // cloning should be prohibited, there's no point to duplicate this texture at all
  38164. FontTexture.prototype.clone = function () {
  38165. return null;
  38166. };
  38167. /**
  38168. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  38169. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  38170. */
  38171. FontTexture.prototype.incCachedFontTextureCounter = function () {
  38172. ++this._usedCounter;
  38173. };
  38174. /**
  38175. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  38176. */
  38177. FontTexture.prototype.decCachedFontTextureCounter = function () {
  38178. var s = this.getScene();
  38179. var dic = s.__fontTextureCache__;
  38180. if (!dic) {
  38181. return;
  38182. }
  38183. if (--this._usedCounter === 0) {
  38184. dic.remove(this._cachedFontId);
  38185. this.dispose();
  38186. }
  38187. };
  38188. return FontTexture;
  38189. })(BABYLON.Texture);
  38190. BABYLON.FontTexture = FontTexture;
  38191. })(BABYLON || (BABYLON = {}));
  38192. var BABYLON;
  38193. (function (BABYLON) {
  38194. var MapTexture = (function (_super) {
  38195. __extends(MapTexture, _super);
  38196. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  38197. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38198. if (useMipMap === void 0) { useMipMap = false; }
  38199. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  38200. this.name = name;
  38201. this._size = size;
  38202. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38203. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38204. // Create the rectPackMap that will allocate portion of the texture
  38205. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  38206. // Create the texture that will store the content
  38207. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  38208. }
  38209. /**
  38210. * Allocate a rectangle of a given size in the texture map
  38211. * @param size the size of the rectangle to allocation
  38212. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  38213. */
  38214. MapTexture.prototype.allocateRect = function (size) {
  38215. return this._rectPackingMap.addRect(size);
  38216. };
  38217. /**
  38218. * Free a given rectangle from the texture map
  38219. * @param rectInfo the instance corresponding to the rect to free.
  38220. */
  38221. MapTexture.prototype.freeRect = function (rectInfo) {
  38222. if (rectInfo) {
  38223. rectInfo.freeContent();
  38224. }
  38225. };
  38226. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  38227. /**
  38228. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  38229. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  38230. * @returns {}
  38231. */
  38232. get: function () {
  38233. return this._rectPackingMap.freeSpace;
  38234. },
  38235. enumerable: true,
  38236. configurable: true
  38237. });
  38238. /**
  38239. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  38240. * 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.
  38241. * Don't forget to call unbindTexture when you're done rendering
  38242. * @param rect the zone to render to
  38243. * @param clear true to clear the portion's color/depth data
  38244. */
  38245. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  38246. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  38247. };
  38248. /**
  38249. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  38250. * 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.
  38251. * Don't forget to call unbindTexture when you're done rendering
  38252. * @param pos the position into the texture
  38253. * @param size the portion to fit the clip space to
  38254. * @param clear true to clear the portion's color/depth data
  38255. */
  38256. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  38257. var engine = this.getScene().getEngine();
  38258. engine.bindFramebuffer(this._texture);
  38259. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  38260. if (clear) {
  38261. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  38262. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  38263. }
  38264. };
  38265. /**
  38266. * Unbind the texture map from the rendering engine.
  38267. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  38268. * @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.
  38269. */
  38270. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  38271. // Dump ?
  38272. if (dumpForDebug) {
  38273. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  38274. }
  38275. var engine = this.getScene().getEngine();
  38276. if (this._replacedViewport) {
  38277. engine.setViewport(this._replacedViewport);
  38278. this._replacedViewport = null;
  38279. }
  38280. engine.unBindFramebuffer(this._texture);
  38281. };
  38282. Object.defineProperty(MapTexture.prototype, "canRescale", {
  38283. get: function () {
  38284. return false;
  38285. },
  38286. enumerable: true,
  38287. configurable: true
  38288. });
  38289. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  38290. // Anyway, there's not much point to use this method for this kind of texture I guess
  38291. MapTexture.prototype.clone = function () {
  38292. return null;
  38293. };
  38294. return MapTexture;
  38295. })(BABYLON.Texture);
  38296. BABYLON.MapTexture = MapTexture;
  38297. })(BABYLON || (BABYLON = {}));
  38298. var BABYLON;
  38299. (function (BABYLON) {
  38300. /**
  38301. * Stores 2D Bounding Information.
  38302. * This class handles a circle area and a bounding rectangle one.
  38303. */
  38304. var BoundingInfo2D = (function () {
  38305. function BoundingInfo2D() {
  38306. this.radius = 0;
  38307. this.center = BABYLON.Vector2.Zero();
  38308. this.extent = BABYLON.Vector2.Zero();
  38309. }
  38310. /**
  38311. * Create a BoundingInfo2D object from a given size
  38312. * @param size the size that will be used to set the extend, radius will be computed from it.
  38313. */
  38314. BoundingInfo2D.CreateFromSize = function (size) {
  38315. var r = new BoundingInfo2D();
  38316. BoundingInfo2D.CreateFromSizeToRef(size, r);
  38317. return r;
  38318. };
  38319. /**
  38320. * Create a BoundingInfo2D object from a given radius
  38321. * @param radius the radius to use, the extent will be computed from it.
  38322. */
  38323. BoundingInfo2D.CreateFromRadius = function (radius) {
  38324. var r = new BoundingInfo2D();
  38325. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  38326. return r;
  38327. };
  38328. /**
  38329. * Create a BoundingInfo2D object from a list of points.
  38330. * The resulted object will be the smallest bounding area that includes all the given points.
  38331. * @param points an array of points to compute the bounding object from.
  38332. */
  38333. BoundingInfo2D.CreateFromPoints = function (points) {
  38334. var r = new BoundingInfo2D();
  38335. BoundingInfo2D.CreateFromPointsToRef(points, r);
  38336. return r;
  38337. };
  38338. /**
  38339. * Update a BoundingInfo2D object using the given Size as input
  38340. * @param size the bounding data will be computed from this size.
  38341. * @param b must be a valid/allocated object, it will contain the result of the operation
  38342. */
  38343. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  38344. if (!size) {
  38345. size = BABYLON.Size.Zero();
  38346. }
  38347. b.center.x = +size.width / 2;
  38348. b.center.y = +size.height / 2;
  38349. b.extent.x = b.center.x;
  38350. b.extent.y = b.center.y;
  38351. b.radius = b.extent.length();
  38352. };
  38353. /**
  38354. * Update a BoundingInfo2D object using the given radius as input
  38355. * @param radius the bounding data will be computed from this radius
  38356. * @param b must be a valid/allocated object, it will contain the result of the operation
  38357. */
  38358. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  38359. b.center.x = b.center.y = 0;
  38360. var r = +radius;
  38361. b.extent.x = r;
  38362. b.extent.y = r;
  38363. b.radius = r;
  38364. };
  38365. /**
  38366. * Update a BoundingInfo2D object using the given points array as input
  38367. * @param points the point array to use to update the bounding data
  38368. * @param b must be a valid/allocated object, it will contain the result of the operation
  38369. */
  38370. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  38371. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  38372. for (var _i = 0; _i < points.length; _i++) {
  38373. var p = points[_i];
  38374. xmin = Math.min(p.x, xmin);
  38375. xmax = Math.max(p.x, xmax);
  38376. ymin = Math.min(p.y, ymin);
  38377. ymax = Math.max(p.y, ymax);
  38378. }
  38379. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  38380. };
  38381. /**
  38382. * Update a BoundingInfo2D object using the given min/max values as input
  38383. * @param xmin the smallest x coordinate
  38384. * @param xmax the biggest x coordinate
  38385. * @param ymin the smallest y coordinate
  38386. * @param ymax the buggest y coordinate
  38387. * @param b must be a valid/allocated object, it will contain the result of the operation
  38388. */
  38389. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  38390. var w = xmax - xmin;
  38391. var h = ymax - ymin;
  38392. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  38393. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  38394. b.radius = b.extent.length();
  38395. };
  38396. /**
  38397. * Duplicate this instance and return a new one
  38398. * @return the duplicated instance
  38399. */
  38400. BoundingInfo2D.prototype.clone = function () {
  38401. var r = new BoundingInfo2D();
  38402. r.center = this.center.clone();
  38403. r.radius = this.radius;
  38404. r.extent = this.extent.clone();
  38405. return r;
  38406. };
  38407. BoundingInfo2D.prototype.clear = function () {
  38408. this.center.copyFromFloats(0, 0);
  38409. this.radius = 0;
  38410. this.extent.copyFromFloats(0, 0);
  38411. };
  38412. BoundingInfo2D.prototype.copyFrom = function (src) {
  38413. this.center.copyFrom(src.center);
  38414. this.radius = src.radius;
  38415. this.extent.copyFrom(src.extent);
  38416. };
  38417. /**
  38418. * return the max extend of the bounding info
  38419. */
  38420. BoundingInfo2D.prototype.max = function () {
  38421. var r = BABYLON.Vector2.Zero();
  38422. this.maxToRef(r);
  38423. return r;
  38424. };
  38425. /**
  38426. * Update a vector2 with the max extend of the bounding info
  38427. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  38428. */
  38429. BoundingInfo2D.prototype.maxToRef = function (result) {
  38430. result.x = this.center.x + this.extent.x;
  38431. result.y = this.center.y + this.extent.y;
  38432. };
  38433. /**
  38434. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  38435. * @param matrix the transformation matrix to apply
  38436. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  38437. */
  38438. BoundingInfo2D.prototype.transform = function (matrix) {
  38439. var r = new BoundingInfo2D();
  38440. this.transformToRef(matrix, r);
  38441. return r;
  38442. };
  38443. /**
  38444. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  38445. * @param other the second BoundingInfo2D to compute the union with this one
  38446. * @return a new instance containing the result of the union
  38447. */
  38448. BoundingInfo2D.prototype.union = function (other) {
  38449. var r = new BoundingInfo2D();
  38450. this.unionToRef(other, r);
  38451. return r;
  38452. };
  38453. /**
  38454. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  38455. * 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.
  38456. * @param matrix The matrix to use to compute the transformation
  38457. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  38458. */
  38459. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  38460. // Construct a bounding box based on the extent values
  38461. var p = BoundingInfo2D._transform;
  38462. p[0].x = this.center.x + this.extent.x;
  38463. p[0].y = this.center.y + this.extent.y;
  38464. p[1].x = this.center.x + this.extent.x;
  38465. p[1].y = this.center.y - this.extent.y;
  38466. p[2].x = this.center.x - this.extent.x;
  38467. p[2].y = this.center.y - this.extent.y;
  38468. p[3].x = this.center.x - this.extent.x;
  38469. p[3].y = this.center.y + this.extent.y;
  38470. // Transform the four points of the bounding box with the matrix
  38471. for (var i = 0; i < 4; i++) {
  38472. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  38473. }
  38474. BoundingInfo2D.CreateFromPointsToRef(p, result);
  38475. };
  38476. /**
  38477. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  38478. * 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.
  38479. * @param other the second object used to compute the union
  38480. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  38481. */
  38482. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  38483. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  38484. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  38485. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  38486. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  38487. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  38488. };
  38489. /**
  38490. * Check if the given point is inside the BoundingInfo.
  38491. * The test is first made on the radius, then inside the rectangle described by the extent
  38492. * @param pickPosition the position to test
  38493. * @return true if the point is inside, false otherwise
  38494. */
  38495. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  38496. // is it inside the radius?
  38497. var pickLocal = pickPosition.subtract(this.center);
  38498. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  38499. // is it inside the rectangle?
  38500. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  38501. }
  38502. return false;
  38503. };
  38504. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  38505. return BoundingInfo2D;
  38506. })();
  38507. BABYLON.BoundingInfo2D = BoundingInfo2D;
  38508. })(BABYLON || (BABYLON = {}));
  38509. var BABYLON;
  38510. (function (BABYLON) {
  38511. /**
  38512. * Base class implementing the ILocable interface.
  38513. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  38514. */
  38515. var LockableBase = (function () {
  38516. function LockableBase() {
  38517. }
  38518. LockableBase.prototype.isLocked = function () {
  38519. return this._isLocked;
  38520. };
  38521. LockableBase.prototype.lock = function () {
  38522. if (this._isLocked) {
  38523. return true;
  38524. }
  38525. this.onLock();
  38526. this._isLocked = true;
  38527. return false;
  38528. };
  38529. /**
  38530. * Protected handler that will be called when the instance is about to be locked.
  38531. */
  38532. LockableBase.prototype.onLock = function () {
  38533. };
  38534. return LockableBase;
  38535. })();
  38536. BABYLON.LockableBase = LockableBase;
  38537. var SolidColorBrush2D = (function (_super) {
  38538. __extends(SolidColorBrush2D, _super);
  38539. function SolidColorBrush2D(color, lock) {
  38540. if (lock === void 0) { lock = false; }
  38541. _super.call(this);
  38542. this._color = color;
  38543. if (lock) {
  38544. {
  38545. this.lock();
  38546. }
  38547. }
  38548. }
  38549. /**
  38550. * Return true if the brush is transparent, false if it's totally opaque
  38551. */
  38552. SolidColorBrush2D.prototype.isTransparent = function () {
  38553. return this._color && this._color.a < 1.0;
  38554. };
  38555. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  38556. /**
  38557. * The color used by this instance to render
  38558. * @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.
  38559. */
  38560. get: function () {
  38561. return this._color;
  38562. },
  38563. set: function (value) {
  38564. if (this.isLocked()) {
  38565. return;
  38566. }
  38567. this._color = value;
  38568. },
  38569. enumerable: true,
  38570. configurable: true
  38571. });
  38572. /**
  38573. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  38574. */
  38575. SolidColorBrush2D.prototype.toString = function () {
  38576. return this._color.toHexString();
  38577. };
  38578. SolidColorBrush2D = __decorate([
  38579. BABYLON.className("SolidColorBrush2D")
  38580. ], SolidColorBrush2D);
  38581. return SolidColorBrush2D;
  38582. })(LockableBase);
  38583. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  38584. var GradientColorBrush2D = (function (_super) {
  38585. __extends(GradientColorBrush2D, _super);
  38586. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  38587. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  38588. if (rotation === void 0) { rotation = 0; }
  38589. if (scale === void 0) { scale = 1; }
  38590. if (lock === void 0) { lock = false; }
  38591. _super.call(this);
  38592. this._color1 = color1;
  38593. this._color2 = color2;
  38594. this._translation = translation;
  38595. this._rotation = rotation;
  38596. this._scale = scale;
  38597. if (lock) {
  38598. this.lock();
  38599. }
  38600. }
  38601. /**
  38602. * Return true if the brush is transparent, false if it's totally opaque
  38603. */
  38604. GradientColorBrush2D.prototype.isTransparent = function () {
  38605. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  38606. };
  38607. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  38608. /**
  38609. * First color, the blend will start from this color
  38610. */
  38611. get: function () {
  38612. return this._color1;
  38613. },
  38614. set: function (value) {
  38615. if (this.isLocked()) {
  38616. return;
  38617. }
  38618. this._color1 = value;
  38619. },
  38620. enumerable: true,
  38621. configurable: true
  38622. });
  38623. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  38624. /**
  38625. * Second color, the blend will end to this color
  38626. */
  38627. get: function () {
  38628. return this._color2;
  38629. },
  38630. set: function (value) {
  38631. if (this.isLocked()) {
  38632. return;
  38633. }
  38634. this._color2 = value;
  38635. },
  38636. enumerable: true,
  38637. configurable: true
  38638. });
  38639. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  38640. /**
  38641. * Translation vector to apply on the blend
  38642. * Default is [0;0]
  38643. */
  38644. get: function () {
  38645. return this._translation;
  38646. },
  38647. set: function (value) {
  38648. if (this.isLocked()) {
  38649. return;
  38650. }
  38651. this._translation = value;
  38652. },
  38653. enumerable: true,
  38654. configurable: true
  38655. });
  38656. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  38657. /**
  38658. * Rotation in radian to apply to the brush
  38659. * Default direction of the brush is vertical, you can change this using this property.
  38660. * Default is 0.
  38661. */
  38662. get: function () {
  38663. return this._rotation;
  38664. },
  38665. set: function (value) {
  38666. if (this.isLocked()) {
  38667. return;
  38668. }
  38669. this._rotation = value;
  38670. },
  38671. enumerable: true,
  38672. configurable: true
  38673. });
  38674. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  38675. /**
  38676. * Scale factor to apply to the gradient.
  38677. * Default is 1: no scale.
  38678. */
  38679. get: function () {
  38680. return this._scale;
  38681. },
  38682. set: function (value) {
  38683. if (this.isLocked()) {
  38684. return;
  38685. }
  38686. this._scale = value;
  38687. },
  38688. enumerable: true,
  38689. configurable: true
  38690. });
  38691. /**
  38692. * Return a string describing the brush
  38693. */
  38694. GradientColorBrush2D.prototype.toString = function () {
  38695. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  38696. };
  38697. /**
  38698. * Build a unique key string for the given parameters
  38699. */
  38700. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  38701. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  38702. };
  38703. GradientColorBrush2D = __decorate([
  38704. BABYLON.className("GradientColorBrush2D")
  38705. ], GradientColorBrush2D);
  38706. return GradientColorBrush2D;
  38707. })(LockableBase);
  38708. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  38709. })(BABYLON || (BABYLON = {}));
  38710. var BABYLON;
  38711. (function (BABYLON) {
  38712. var Prim2DClassInfo = (function () {
  38713. function Prim2DClassInfo() {
  38714. }
  38715. return Prim2DClassInfo;
  38716. })();
  38717. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  38718. var Prim2DPropInfo = (function () {
  38719. function Prim2DPropInfo() {
  38720. }
  38721. Prim2DPropInfo.PROPKIND_MODEL = 1;
  38722. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  38723. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  38724. return Prim2DPropInfo;
  38725. })();
  38726. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  38727. /**
  38728. * Custom type of the propertyChanged observable
  38729. */
  38730. var PropertyChangedInfo = (function () {
  38731. function PropertyChangedInfo() {
  38732. }
  38733. return PropertyChangedInfo;
  38734. })();
  38735. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  38736. var ClassTreeInfo = (function () {
  38737. function ClassTreeInfo(baseClass, type, classContentFactory) {
  38738. this._baseClass = baseClass;
  38739. this._type = type;
  38740. this._subClasses = new Array();
  38741. this._levelContent = new BABYLON.StringDictionary();
  38742. this._classContentFactory = classContentFactory;
  38743. }
  38744. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  38745. get: function () {
  38746. if (!this._classContent) {
  38747. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  38748. }
  38749. return this._classContent;
  38750. },
  38751. enumerable: true,
  38752. configurable: true
  38753. });
  38754. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  38755. get: function () {
  38756. return this._type;
  38757. },
  38758. enumerable: true,
  38759. configurable: true
  38760. });
  38761. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  38762. get: function () {
  38763. return this._levelContent;
  38764. },
  38765. enumerable: true,
  38766. configurable: true
  38767. });
  38768. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  38769. get: function () {
  38770. if (!this._fullContent) {
  38771. var dic = new BABYLON.StringDictionary();
  38772. var curLevel = this;
  38773. while (curLevel) {
  38774. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  38775. curLevel = curLevel._baseClass;
  38776. }
  38777. this._fullContent = dic;
  38778. }
  38779. return this._fullContent;
  38780. },
  38781. enumerable: true,
  38782. configurable: true
  38783. });
  38784. ClassTreeInfo.prototype.getLevelOf = function (type) {
  38785. // Are we already there?
  38786. if (type === this._type) {
  38787. return this;
  38788. }
  38789. var baseProto = Object.getPrototypeOf(type);
  38790. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  38791. if (!curProtoContent) {
  38792. this.getLevelOf(baseProto);
  38793. }
  38794. return this.getOrAddType(baseProto, type);
  38795. };
  38796. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  38797. // Are we at the level corresponding to the baseType?
  38798. // If so, get or add the level we're looking for
  38799. if (baseType === this._type) {
  38800. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  38801. var subType = _a[_i];
  38802. if (subType.type === type) {
  38803. return subType.node;
  38804. }
  38805. }
  38806. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  38807. var info = { type: type, node: node };
  38808. this._subClasses.push(info);
  38809. return info.node;
  38810. }
  38811. // Recurse down to keep looking for the node corresponding to the baseTypeName
  38812. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  38813. var subType = _c[_b];
  38814. var info = subType.node.getOrAddType(baseType, type);
  38815. if (info) {
  38816. return info;
  38817. }
  38818. }
  38819. return null;
  38820. };
  38821. ClassTreeInfo.get = function (type) {
  38822. var dic = type["__classTreeInfo"];
  38823. if (!dic) {
  38824. return null;
  38825. }
  38826. return dic.getLevelOf(type);
  38827. };
  38828. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  38829. var dic = type["__classTreeInfo"];
  38830. if (!dic) {
  38831. dic = new ClassTreeInfo(null, type, classContentFactory);
  38832. type["__classTreeInfo"] = dic;
  38833. }
  38834. return dic;
  38835. };
  38836. return ClassTreeInfo;
  38837. })();
  38838. BABYLON.ClassTreeInfo = ClassTreeInfo;
  38839. var SmartPropertyPrim = (function () {
  38840. function SmartPropertyPrim() {
  38841. this._flags = 0;
  38842. this._modelKey = null;
  38843. this._instanceDirtyFlags = 0;
  38844. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  38845. this.animations = new Array();
  38846. }
  38847. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  38848. /**
  38849. * Check if the object is disposed or not.
  38850. * @returns true if the object is dispose, false otherwise.
  38851. */
  38852. get: function () {
  38853. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  38854. },
  38855. enumerable: true,
  38856. configurable: true
  38857. });
  38858. /**
  38859. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  38860. * @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.
  38861. */
  38862. SmartPropertyPrim.prototype.dispose = function () {
  38863. if (this.isDisposed) {
  38864. return false;
  38865. }
  38866. // Don't set to null, it may upset somebody...
  38867. this.animations.splice(0);
  38868. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  38869. return true;
  38870. };
  38871. /**
  38872. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  38873. * Look at Sprite2D for more information
  38874. */
  38875. SmartPropertyPrim.prototype.getAnimatables = function () {
  38876. return new Array();
  38877. };
  38878. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  38879. /**
  38880. * Property giving the Model Key associated to the property.
  38881. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  38882. * @returns the model key string.
  38883. */
  38884. get: function () {
  38885. var _this = this;
  38886. // No need to compute it?
  38887. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  38888. return this._modelKey;
  38889. }
  38890. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  38891. var propDic = this.propDic;
  38892. propDic.forEach(function (k, v) {
  38893. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  38894. var propVal = _this[v.name];
  38895. // 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
  38896. if (propVal && propVal.constructor === Array) {
  38897. var firstVal = propVal[0];
  38898. if (!firstVal) {
  38899. propVal = 0;
  38900. }
  38901. else {
  38902. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  38903. }
  38904. }
  38905. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  38906. }
  38907. });
  38908. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  38909. this._modelKey = modelKey;
  38910. return modelKey;
  38911. },
  38912. enumerable: true,
  38913. configurable: true
  38914. });
  38915. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  38916. /**
  38917. * States if the Primitive is dirty and should be rendered again next time.
  38918. * @returns true is dirty, false otherwise
  38919. */
  38920. get: function () {
  38921. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  38922. },
  38923. enumerable: true,
  38924. configurable: true
  38925. });
  38926. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  38927. /**
  38928. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  38929. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  38930. */
  38931. get: function () {
  38932. if (!this._propInfo) {
  38933. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  38934. if (!cti) {
  38935. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  38936. }
  38937. this._propInfo = cti.fullContent;
  38938. }
  38939. return this._propInfo;
  38940. },
  38941. enumerable: true,
  38942. configurable: true
  38943. });
  38944. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  38945. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  38946. var node = dic.getLevelOf(target);
  38947. var propInfo = node.levelContent.get(propId.toString());
  38948. if (propInfo) {
  38949. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  38950. }
  38951. // Create, setup and add the PropInfo object to our prop dictionary
  38952. propInfo = new Prim2DPropInfo();
  38953. propInfo.id = propId;
  38954. propInfo.flagId = Math.pow(2, propId);
  38955. propInfo.kind = kind;
  38956. propInfo.name = propName;
  38957. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  38958. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  38959. propInfo.typeLevelCompare = typeLevelCompare;
  38960. node.levelContent.add(propName, propInfo);
  38961. return propInfo;
  38962. };
  38963. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  38964. // Nothing to nothing: nothing to do!
  38965. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  38966. return true;
  38967. }
  38968. // Check value unchanged
  38969. if ((curValue != null) && (newValue != null)) {
  38970. if (typeof (curValue.equals) == "function") {
  38971. if (curValue.equals(newValue)) {
  38972. return true;
  38973. }
  38974. }
  38975. else {
  38976. if (curValue === newValue) {
  38977. return true;
  38978. }
  38979. }
  38980. }
  38981. return false;
  38982. };
  38983. SmartPropertyPrim.prototype._triggerPropertyChanged = function (propInfo, newValue) {
  38984. if (this.isDisposed) {
  38985. return;
  38986. }
  38987. if (!propInfo) {
  38988. return;
  38989. }
  38990. this._handlePropChanged(undefined, newValue, propInfo.name, propInfo, propInfo.typeLevelCompare);
  38991. };
  38992. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  38993. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  38994. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  38995. if (this instanceof BABYLON.Prim2DBase) {
  38996. var curprim = this;
  38997. while (curprim) {
  38998. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  38999. if (curprim.isSizeAuto) {
  39000. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  39001. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  39002. }
  39003. if (curprim instanceof BABYLON.Group2D) {
  39004. if (curprim.isRenderableGroup) {
  39005. break;
  39006. }
  39007. }
  39008. curprim = curprim.parent;
  39009. }
  39010. }
  39011. };
  39012. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  39013. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  39014. if (propInfo.dirtyBoundingInfo) {
  39015. this._boundingBoxDirty();
  39016. }
  39017. else if (propInfo.dirtyParentBoundingInfo) {
  39018. var p = this._parent;
  39019. if (p != null) {
  39020. p._boundingBoxDirty();
  39021. }
  39022. }
  39023. // Trigger property changed
  39024. var info = SmartPropertyPrim.propChangedInfo;
  39025. info.oldValue = curValue;
  39026. info.newValue = newValue;
  39027. info.propertyName = propName;
  39028. var propMask = propInfo.flagId;
  39029. this.propertyChanged.notifyObservers(info, propMask);
  39030. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  39031. if (this instanceof BABYLON.Group2D) {
  39032. this.handleGroupChanged(propInfo);
  39033. }
  39034. // Check for parent layout dirty
  39035. if (this instanceof BABYLON.Prim2DBase) {
  39036. var p = this._parent;
  39037. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  39038. p._setLayoutDirty();
  39039. }
  39040. }
  39041. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  39042. var instanceDirty = false;
  39043. if (typeLevelCompare && curValue != null && newValue != null) {
  39044. var cvProto = curValue.__proto__;
  39045. var nvProto = newValue.__proto__;
  39046. instanceDirty = (cvProto === nvProto);
  39047. }
  39048. // Set the dirty flags
  39049. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  39050. if (!this.isDirty) {
  39051. this._setFlags(SmartPropertyPrim.flagModelDirty);
  39052. }
  39053. }
  39054. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  39055. this.onPrimitivePropertyDirty(propMask);
  39056. }
  39057. };
  39058. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  39059. this.onPrimBecomesDirty();
  39060. this._instanceDirtyFlags |= propFlagId;
  39061. };
  39062. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  39063. };
  39064. /**
  39065. * Check if a given set of properties are dirty or not.
  39066. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  39067. * @return true if at least one property is dirty, false if none of them are.
  39068. */
  39069. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  39070. return (this._instanceDirtyFlags & flags) !== 0;
  39071. };
  39072. /**
  39073. * Clear a given set of properties.
  39074. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  39075. * @return the new set of property still marked as dirty
  39076. */
  39077. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  39078. this._instanceDirtyFlags &= ~flags;
  39079. return this._instanceDirtyFlags;
  39080. };
  39081. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  39082. this._instanceDirtyFlags = 0;
  39083. this._clearFlags(SmartPropertyPrim.flagPrimInDirtyList | SmartPropertyPrim.flagNeedRefresh);
  39084. };
  39085. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  39086. /**
  39087. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  39088. */
  39089. get: function () {
  39090. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  39091. this.updateLevelBoundingInfo();
  39092. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  39093. }
  39094. return this._levelBoundingInfo;
  39095. },
  39096. enumerable: true,
  39097. configurable: true
  39098. });
  39099. /**
  39100. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  39101. */
  39102. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  39103. };
  39104. /**
  39105. * Property method called when the Primitive becomes dirty
  39106. */
  39107. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  39108. };
  39109. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  39110. return function (target, propName, descriptor) {
  39111. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  39112. if (piStore) {
  39113. piStore(propInfo);
  39114. }
  39115. var getter = descriptor.get, setter = descriptor.set;
  39116. // Overload the property setter implementation to add our own logic
  39117. descriptor.set = function (val) {
  39118. // check for disposed first, do nothing
  39119. if (this.isDisposed) {
  39120. return;
  39121. }
  39122. var curVal = getter.call(this);
  39123. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  39124. return;
  39125. }
  39126. // Cast the object we're working one
  39127. var prim = this;
  39128. // Change the value
  39129. setter.call(this, val);
  39130. // Notify change, dirty flags update
  39131. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  39132. };
  39133. };
  39134. };
  39135. /**
  39136. * Add an externally attached data from its key.
  39137. * This method call will fail and return false, if such key already exists.
  39138. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  39139. * @param key the unique key that identifies the data
  39140. * @param data the data object to associate to the key for this Engine instance
  39141. * @return true if no such key were already present and the data was added successfully, false otherwise
  39142. */
  39143. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  39144. if (!this._externalData) {
  39145. this._externalData = new BABYLON.StringDictionary();
  39146. }
  39147. return this._externalData.add(key, data);
  39148. };
  39149. /**
  39150. * Get an externally attached data from its key
  39151. * @param key the unique key that identifies the data
  39152. * @return the associated data, if present (can be null), or undefined if not present
  39153. */
  39154. SmartPropertyPrim.prototype.getExternalData = function (key) {
  39155. if (!this._externalData) {
  39156. return null;
  39157. }
  39158. return this._externalData.get(key);
  39159. };
  39160. /**
  39161. * Get an externally attached data from its key, create it using a factory if it's not already present
  39162. * @param key the unique key that identifies the data
  39163. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  39164. * @return the associated data, can be null if the factory returned null.
  39165. */
  39166. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  39167. if (!this._externalData) {
  39168. this._externalData = new BABYLON.StringDictionary();
  39169. }
  39170. return this._externalData.getOrAddWithFactory(key, factory);
  39171. };
  39172. /**
  39173. * Remove an externally attached data from the Engine instance
  39174. * @param key the unique key that identifies the data
  39175. * @return true if the data was successfully removed, false if it doesn't exist
  39176. */
  39177. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  39178. if (!this._externalData) {
  39179. return false;
  39180. }
  39181. return this._externalData.remove(key);
  39182. };
  39183. /**
  39184. * Check if a given flag is set
  39185. * @param flag the flag value
  39186. * @return true if set, false otherwise
  39187. */
  39188. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  39189. return (this._flags & flag) !== 0;
  39190. };
  39191. /**
  39192. * Check if all given flags are set
  39193. * @param flags the flags ORed
  39194. * @return true if all the flags are set, false otherwise
  39195. */
  39196. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  39197. return (this._flags & flags) === flags;
  39198. };
  39199. /**
  39200. * Check if at least one flag of the given flags is set
  39201. * @param flags the flags ORed
  39202. * @return true if at least one flag is set, false otherwise
  39203. */
  39204. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  39205. return (this._flags & flags) !== 0;
  39206. };
  39207. /**
  39208. * Clear the given flags
  39209. * @param flags the flags to clear
  39210. */
  39211. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  39212. this._flags &= ~flags;
  39213. };
  39214. /**
  39215. * Set the given flags to true state
  39216. * @param flags the flags ORed to set
  39217. * @return the flags state before this call
  39218. */
  39219. SmartPropertyPrim.prototype._setFlags = function (flags) {
  39220. var cur = this._flags;
  39221. this._flags |= flags;
  39222. return cur;
  39223. };
  39224. /**
  39225. * Change the state of the given flags
  39226. * @param flags the flags ORed to change
  39227. * @param state true to set them, false to clear them
  39228. */
  39229. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  39230. if (state) {
  39231. this._flags |= flags;
  39232. }
  39233. else {
  39234. this._flags &= ~flags;
  39235. }
  39236. };
  39237. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  39238. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  39239. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  39240. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  39241. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  39242. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  39243. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  39244. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  39245. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  39246. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  39247. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  39248. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  39249. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  39250. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  39251. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  39252. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  39253. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  39254. SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
  39255. SmartPropertyPrim.flagNeedRefresh = 0x0020000; // set if the primitive wasn't successful at refresh
  39256. SmartPropertyPrim.flagActualScaleDirty = 0x0040000; // set if the actualScale property needs to be recomputed
  39257. SmartPropertyPrim.flagDontInheritParentScale = 0x0080000; // set if the actualScale must not use its parent's scale to be computed
  39258. SmartPropertyPrim.flagGlobalTransformDirty = 0x0100000; // set if the global transform must be recomputed due to a local transform change
  39259. SmartPropertyPrim = __decorate([
  39260. BABYLON.className("SmartPropertyPrim")
  39261. ], SmartPropertyPrim);
  39262. return SmartPropertyPrim;
  39263. })();
  39264. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  39265. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  39266. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  39267. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  39268. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  39269. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  39270. }
  39271. BABYLON.modelLevelProperty = modelLevelProperty;
  39272. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  39273. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  39274. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  39275. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  39276. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  39277. }
  39278. BABYLON.instanceLevelProperty = instanceLevelProperty;
  39279. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  39280. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  39281. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  39282. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  39283. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  39284. }
  39285. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  39286. })(BABYLON || (BABYLON = {}));
  39287. var BABYLON;
  39288. (function (BABYLON) {
  39289. var PrepareRender2DContext = (function () {
  39290. function PrepareRender2DContext() {
  39291. this.forceRefreshPrimitive = false;
  39292. }
  39293. return PrepareRender2DContext;
  39294. })();
  39295. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  39296. var Render2DContext = (function () {
  39297. function Render2DContext(renderMode) {
  39298. this._renderMode = renderMode;
  39299. this.useInstancing = false;
  39300. this.groupInfoPartData = null;
  39301. this.partDataStartIndex = this.partDataEndIndex = null;
  39302. this.instancedBuffers = null;
  39303. }
  39304. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  39305. /**
  39306. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  39307. */
  39308. get: function () {
  39309. return this._renderMode;
  39310. },
  39311. enumerable: true,
  39312. configurable: true
  39313. });
  39314. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  39315. /**
  39316. * The set of primitives to render is opaque.
  39317. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  39318. */
  39319. get: function () {
  39320. return Render2DContext._renderModeOpaque;
  39321. },
  39322. enumerable: true,
  39323. configurable: true
  39324. });
  39325. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  39326. /**
  39327. * The set of primitives to render is using Alpha Test (aka masking).
  39328. * 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.
  39329. */
  39330. get: function () {
  39331. return Render2DContext._renderModeAlphaTest;
  39332. },
  39333. enumerable: true,
  39334. configurable: true
  39335. });
  39336. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  39337. /**
  39338. * The set of primitives to render is transparent.
  39339. * 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.
  39340. */
  39341. get: function () {
  39342. return Render2DContext._renderModeTransparent;
  39343. },
  39344. enumerable: true,
  39345. configurable: true
  39346. });
  39347. Render2DContext._renderModeOpaque = 1;
  39348. Render2DContext._renderModeAlphaTest = 2;
  39349. Render2DContext._renderModeTransparent = 3;
  39350. return Render2DContext;
  39351. })();
  39352. BABYLON.Render2DContext = Render2DContext;
  39353. /**
  39354. * This class store information for the pointerEventObservable Observable.
  39355. * 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.
  39356. */
  39357. var PrimitivePointerInfo = (function () {
  39358. function PrimitivePointerInfo() {
  39359. this.primitivePointerPos = BABYLON.Vector2.Zero();
  39360. this.tilt = BABYLON.Vector2.Zero();
  39361. this.cancelBubble = false;
  39362. }
  39363. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  39364. // 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.
  39365. /**
  39366. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  39367. * Bubbles: yes
  39368. */
  39369. get: function () {
  39370. return PrimitivePointerInfo._pointerOver;
  39371. },
  39372. enumerable: true,
  39373. configurable: true
  39374. });
  39375. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  39376. /**
  39377. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  39378. * Bubbles: no
  39379. */
  39380. get: function () {
  39381. return PrimitivePointerInfo._pointerEnter;
  39382. },
  39383. enumerable: true,
  39384. configurable: true
  39385. });
  39386. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  39387. /**
  39388. * 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.
  39389. * Bubbles: yes
  39390. */
  39391. get: function () {
  39392. return PrimitivePointerInfo._pointerDown;
  39393. },
  39394. enumerable: true,
  39395. configurable: true
  39396. });
  39397. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  39398. /**
  39399. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  39400. * Bubbles: yes
  39401. */
  39402. get: function () {
  39403. return PrimitivePointerInfo._pointerMouseWheel;
  39404. },
  39405. enumerable: true,
  39406. configurable: true
  39407. });
  39408. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  39409. /**
  39410. * 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.
  39411. * Bubbles: yes
  39412. */
  39413. get: function () {
  39414. return PrimitivePointerInfo._pointerMove;
  39415. },
  39416. enumerable: true,
  39417. configurable: true
  39418. });
  39419. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  39420. /**
  39421. * 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.
  39422. * Bubbles: yes
  39423. */
  39424. get: function () {
  39425. return PrimitivePointerInfo._pointerUp;
  39426. },
  39427. enumerable: true,
  39428. configurable: true
  39429. });
  39430. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  39431. /**
  39432. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  39433. * Bubbles: yes
  39434. */
  39435. get: function () {
  39436. return PrimitivePointerInfo._pointerOut;
  39437. },
  39438. enumerable: true,
  39439. configurable: true
  39440. });
  39441. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  39442. /**
  39443. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  39444. * Bubbles: no
  39445. */
  39446. get: function () {
  39447. return PrimitivePointerInfo._pointerLeave;
  39448. },
  39449. enumerable: true,
  39450. configurable: true
  39451. });
  39452. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  39453. /**
  39454. * 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.
  39455. * Bubbles: yes
  39456. */
  39457. get: function () {
  39458. return PrimitivePointerInfo._pointerGotCapture;
  39459. },
  39460. enumerable: true,
  39461. configurable: true
  39462. });
  39463. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  39464. /**
  39465. * This event type is raised after pointer capture is released for a pointer.
  39466. * Bubbles: yes
  39467. */
  39468. get: function () {
  39469. return PrimitivePointerInfo._pointerLostCapture;
  39470. },
  39471. enumerable: true,
  39472. configurable: true
  39473. });
  39474. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  39475. get: function () {
  39476. return PrimitivePointerInfo._mouseWheelPrecision;
  39477. },
  39478. enumerable: true,
  39479. configurable: true
  39480. });
  39481. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  39482. this.relatedTarget = prim;
  39483. this.relatedTargetPointerPos = primPointerPos;
  39484. };
  39485. PrimitivePointerInfo.getEventTypeName = function (mask) {
  39486. switch (mask) {
  39487. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  39488. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  39489. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  39490. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  39491. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  39492. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  39493. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  39494. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  39495. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  39496. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  39497. }
  39498. };
  39499. PrimitivePointerInfo._pointerOver = 0x0001;
  39500. PrimitivePointerInfo._pointerEnter = 0x0002;
  39501. PrimitivePointerInfo._pointerDown = 0x0004;
  39502. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  39503. PrimitivePointerInfo._pointerMove = 0x0010;
  39504. PrimitivePointerInfo._pointerUp = 0x0020;
  39505. PrimitivePointerInfo._pointerOut = 0x0040;
  39506. PrimitivePointerInfo._pointerLeave = 0x0080;
  39507. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  39508. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  39509. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  39510. return PrimitivePointerInfo;
  39511. })();
  39512. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  39513. /**
  39514. * Defines the horizontal and vertical alignment information for a Primitive.
  39515. */
  39516. var PrimitiveAlignment = (function () {
  39517. function PrimitiveAlignment(changeCallback) {
  39518. this._changedCallback = changeCallback;
  39519. this._horizontal = PrimitiveAlignment.AlignLeft;
  39520. this._vertical = PrimitiveAlignment.AlignBottom;
  39521. }
  39522. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  39523. /**
  39524. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  39525. */
  39526. get: function () { return PrimitiveAlignment._AlignLeft; },
  39527. enumerable: true,
  39528. configurable: true
  39529. });
  39530. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  39531. /**
  39532. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  39533. */
  39534. get: function () { return PrimitiveAlignment._AlignTop; },
  39535. enumerable: true,
  39536. configurable: true
  39537. });
  39538. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  39539. /**
  39540. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  39541. */
  39542. get: function () { return PrimitiveAlignment._AlignRight; },
  39543. enumerable: true,
  39544. configurable: true
  39545. });
  39546. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  39547. /**
  39548. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  39549. */
  39550. get: function () { return PrimitiveAlignment._AlignBottom; },
  39551. enumerable: true,
  39552. configurable: true
  39553. });
  39554. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  39555. /**
  39556. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  39557. */
  39558. get: function () { return PrimitiveAlignment._AlignCenter; },
  39559. enumerable: true,
  39560. configurable: true
  39561. });
  39562. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  39563. /**
  39564. * The content is stretched toward the opposite edges of the Primitive
  39565. */
  39566. get: function () { return PrimitiveAlignment._AlignStretch; },
  39567. enumerable: true,
  39568. configurable: true
  39569. });
  39570. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  39571. /**
  39572. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  39573. */
  39574. get: function () {
  39575. return this._horizontal;
  39576. },
  39577. set: function (value) {
  39578. if (this._horizontal === value) {
  39579. return;
  39580. }
  39581. this._horizontal = value;
  39582. this._changedCallback();
  39583. },
  39584. enumerable: true,
  39585. configurable: true
  39586. });
  39587. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  39588. /**
  39589. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  39590. */
  39591. get: function () {
  39592. return this._vertical;
  39593. },
  39594. set: function (value) {
  39595. if (this._vertical === value) {
  39596. return;
  39597. }
  39598. this._vertical = value;
  39599. this._changedCallback();
  39600. },
  39601. enumerable: true,
  39602. configurable: true
  39603. });
  39604. /**
  39605. * Set the horizontal alignment from a string value.
  39606. * @param text can be either: 'left','right','center','stretch'
  39607. */
  39608. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  39609. var v = text.trim().toLocaleLowerCase();
  39610. switch (v) {
  39611. case "left":
  39612. this.horizontal = PrimitiveAlignment.AlignLeft;
  39613. return;
  39614. case "right":
  39615. this.horizontal = PrimitiveAlignment.AlignRight;
  39616. return;
  39617. case "center":
  39618. this.horizontal = PrimitiveAlignment.AlignCenter;
  39619. return;
  39620. case "stretch":
  39621. this.horizontal = PrimitiveAlignment.AlignStretch;
  39622. return;
  39623. }
  39624. };
  39625. /**
  39626. * Set the vertical alignment from a string value.
  39627. * @param text can be either: 'top','bottom','center','stretch'
  39628. */
  39629. PrimitiveAlignment.prototype.setVertical = function (text) {
  39630. var v = text.trim().toLocaleLowerCase();
  39631. switch (v) {
  39632. case "top":
  39633. this.vertical = PrimitiveAlignment.AlignTop;
  39634. return;
  39635. case "bottom":
  39636. this.vertical = PrimitiveAlignment.AlignBottom;
  39637. return;
  39638. case "center":
  39639. this.vertical = PrimitiveAlignment.AlignCenter;
  39640. return;
  39641. case "stretch":
  39642. this.vertical = PrimitiveAlignment.AlignStretch;
  39643. return;
  39644. }
  39645. };
  39646. /**
  39647. * Set the horizontal and or vertical alignments from a string value.
  39648. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  39649. */
  39650. PrimitiveAlignment.prototype.fromString = function (value) {
  39651. var m = value.trim().split(",");
  39652. for (var _i = 0; _i < m.length; _i++) {
  39653. var v = m[_i];
  39654. v = v.toLocaleLowerCase().trim();
  39655. // Horizontal
  39656. var i = v.indexOf("h:");
  39657. if (i === -1) {
  39658. i = v.indexOf("horizontal:");
  39659. }
  39660. if (i !== -1) {
  39661. v = v.substr(v.indexOf(":") + 1);
  39662. this.setHorizontal(v);
  39663. continue;
  39664. }
  39665. // Vertical
  39666. i = v.indexOf("v:");
  39667. if (i === -1) {
  39668. i = v.indexOf("vertical:");
  39669. }
  39670. if (i !== -1) {
  39671. v = v.substr(v.indexOf(":") + 1);
  39672. this.setVertical(v);
  39673. continue;
  39674. }
  39675. }
  39676. };
  39677. PrimitiveAlignment._AlignLeft = 1;
  39678. PrimitiveAlignment._AlignTop = 1; // Same as left
  39679. PrimitiveAlignment._AlignRight = 2;
  39680. PrimitiveAlignment._AlignBottom = 2; // Same as right
  39681. PrimitiveAlignment._AlignCenter = 3;
  39682. PrimitiveAlignment._AlignStretch = 4;
  39683. return PrimitiveAlignment;
  39684. })();
  39685. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  39686. /**
  39687. * Stores information about a Primitive that was intersected
  39688. */
  39689. var PrimitiveIntersectedInfo = (function () {
  39690. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  39691. this.prim = prim;
  39692. this.intersectionLocation = intersectionLocation;
  39693. }
  39694. return PrimitiveIntersectedInfo;
  39695. })();
  39696. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  39697. /**
  39698. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  39699. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  39700. */
  39701. var PrimitiveThickness = (function () {
  39702. function PrimitiveThickness(parentAccess, changedCallback) {
  39703. this._parentAccess = parentAccess;
  39704. this._changedCallback = changedCallback;
  39705. this._pixels = new Array(4);
  39706. this._percentages = new Array(4);
  39707. this._setType(0, PrimitiveThickness.Auto);
  39708. this._setType(1, PrimitiveThickness.Auto);
  39709. this._setType(2, PrimitiveThickness.Auto);
  39710. this._setType(3, PrimitiveThickness.Auto);
  39711. this._pixels[0] = 0;
  39712. this._pixels[1] = 0;
  39713. this._pixels[2] = 0;
  39714. this._pixels[3] = 0;
  39715. }
  39716. /**
  39717. * Set the thickness from a string value
  39718. * @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.
  39719. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39720. */
  39721. PrimitiveThickness.prototype.fromString = function (thickness) {
  39722. this._clear();
  39723. var m = thickness.trim().split(",");
  39724. // Special case, one value to apply to all edges
  39725. if (m.length === 1 && thickness.indexOf(":") === -1) {
  39726. this._setStringValue(m[0], 0, false);
  39727. this._setStringValue(m[0], 1, false);
  39728. this._setStringValue(m[0], 2, false);
  39729. this._setStringValue(m[0], 3, false);
  39730. this._changedCallback();
  39731. return;
  39732. }
  39733. var res = false;
  39734. for (var _i = 0; _i < m.length; _i++) {
  39735. var cm = m[_i];
  39736. res = this._extractString(cm, false) || res;
  39737. }
  39738. if (!res) {
  39739. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  39740. }
  39741. // Check the margin that weren't set and set them in auto
  39742. if ((this._flags & 0x000F) === 0)
  39743. this._flags |= PrimitiveThickness.Pixel << 0;
  39744. if ((this._flags & 0x00F0) === 0)
  39745. this._flags |= PrimitiveThickness.Pixel << 4;
  39746. if ((this._flags & 0x0F00) === 0)
  39747. this._flags |= PrimitiveThickness.Pixel << 8;
  39748. if ((this._flags & 0xF000) === 0)
  39749. this._flags |= PrimitiveThickness.Pixel << 12;
  39750. this._changedCallback();
  39751. };
  39752. /**
  39753. * Set the thickness from multiple string
  39754. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39755. * @param top the top thickness to set
  39756. * @param left the left thickness to set
  39757. * @param right the right thickness to set
  39758. * @param bottom the bottom thickness to set
  39759. */
  39760. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  39761. this._clear();
  39762. this._setStringValue(top, 0, false);
  39763. this._setStringValue(left, 1, false);
  39764. this._setStringValue(right, 2, false);
  39765. this._setStringValue(bottom, 3, false);
  39766. this._changedCallback();
  39767. return this;
  39768. };
  39769. /**
  39770. * Set the thickness from pixel values
  39771. * @param top the top thickness in pixels to set
  39772. * @param left the left thickness in pixels to set
  39773. * @param right the right thickness in pixels to set
  39774. * @param bottom the bottom thickness in pixels to set
  39775. */
  39776. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  39777. this._clear();
  39778. this._pixels[0] = top;
  39779. this._pixels[1] = left;
  39780. this._pixels[2] = right;
  39781. this._pixels[3] = bottom;
  39782. this._changedCallback();
  39783. return this;
  39784. };
  39785. /**
  39786. * Apply the same pixel value to all edges
  39787. * @param margin the value to set, in pixels.
  39788. */
  39789. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  39790. this._clear();
  39791. this._pixels[0] = margin;
  39792. this._pixels[1] = margin;
  39793. this._pixels[2] = margin;
  39794. this._pixels[3] = margin;
  39795. this._changedCallback();
  39796. return this;
  39797. };
  39798. /**
  39799. * Set all edges in auto
  39800. */
  39801. PrimitiveThickness.prototype.auto = function () {
  39802. this._clear();
  39803. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  39804. this._pixels[0] = 0;
  39805. this._pixels[1] = 0;
  39806. this._pixels[2] = 0;
  39807. this._pixels[3] = 0;
  39808. this._changedCallback();
  39809. return this;
  39810. };
  39811. PrimitiveThickness.prototype._clear = function () {
  39812. this._flags = 0;
  39813. this._pixels[0] = 0;
  39814. this._pixels[1] = 0;
  39815. this._pixels[2] = 0;
  39816. this._pixels[3] = 0;
  39817. this._percentages[0] = null;
  39818. this._percentages[1] = null;
  39819. this._percentages[2] = null;
  39820. this._percentages[3] = null;
  39821. };
  39822. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  39823. var v = value.trim().toLocaleLowerCase();
  39824. if (v.indexOf("top:") === 0) {
  39825. v = v.substr(4).trim();
  39826. return this._setStringValue(v, 0, emitChanged);
  39827. }
  39828. if (v.indexOf("left:") === 0) {
  39829. v = v.substr(5).trim();
  39830. return this._setStringValue(v, 1, emitChanged);
  39831. }
  39832. if (v.indexOf("right:") === 0) {
  39833. v = v.substr(6).trim();
  39834. return this._setStringValue(v, 2, emitChanged);
  39835. }
  39836. if (v.indexOf("bottom:") === 0) {
  39837. v = v.substr(7).trim();
  39838. return this._setStringValue(v, 3, emitChanged);
  39839. }
  39840. return false;
  39841. };
  39842. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  39843. // Check for auto
  39844. var v = value.trim().toLocaleLowerCase();
  39845. if (v === "auto") {
  39846. if (this._isType(index, PrimitiveThickness.Auto)) {
  39847. return true;
  39848. }
  39849. this._setType(index, PrimitiveThickness.Auto);
  39850. this._pixels[index] = 0;
  39851. if (emitChanged) {
  39852. this._changedCallback();
  39853. }
  39854. }
  39855. else if (v === "inherit") {
  39856. if (this._isType(index, PrimitiveThickness.Inherit)) {
  39857. return true;
  39858. }
  39859. this._setType(index, PrimitiveThickness.Inherit);
  39860. this._pixels[index] = null;
  39861. if (emitChanged) {
  39862. this._changedCallback();
  39863. }
  39864. }
  39865. else {
  39866. var pI = v.indexOf("%");
  39867. // Check for percentage
  39868. if (pI !== -1) {
  39869. var n_1 = v.substr(0, pI);
  39870. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  39871. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  39872. return true;
  39873. }
  39874. this._setType(index, PrimitiveThickness.Percentage);
  39875. if (isNaN(number_1)) {
  39876. return false;
  39877. }
  39878. this._percentages[index] = number_1;
  39879. if (emitChanged) {
  39880. this._changedCallback();
  39881. }
  39882. return true;
  39883. }
  39884. // Check for pixel
  39885. var n;
  39886. pI = v.indexOf("px");
  39887. if (pI !== -1) {
  39888. n = v.substr(0, pI).trim();
  39889. }
  39890. else {
  39891. n = v;
  39892. }
  39893. var number = Number(n);
  39894. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  39895. return true;
  39896. }
  39897. if (isNaN(number)) {
  39898. return false;
  39899. }
  39900. this._pixels[index] = number;
  39901. this._setType(index, PrimitiveThickness.Pixel);
  39902. if (emitChanged) {
  39903. this._changedCallback();
  39904. }
  39905. return true;
  39906. }
  39907. };
  39908. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  39909. // 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
  39910. value = Math.round(value);
  39911. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  39912. return;
  39913. }
  39914. this._setType(index, PrimitiveThickness.Pixel);
  39915. this._pixels[index] = value;
  39916. if (emitChanged) {
  39917. this._changedCallback();
  39918. }
  39919. };
  39920. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  39921. // Clip Value to bounds
  39922. value = Math.min(1, value);
  39923. value = Math.max(0, value);
  39924. value = Math.round(value * 100) / 100; // 0.01 precision
  39925. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  39926. return;
  39927. }
  39928. this._setType(index, PrimitiveThickness.Percentage);
  39929. this._percentages[index] = value;
  39930. if (emitChanged) {
  39931. this._changedCallback();
  39932. }
  39933. };
  39934. PrimitiveThickness.prototype._getStringValue = function (index) {
  39935. var f = (this._flags >> (index * 4)) & 0xF;
  39936. switch (f) {
  39937. case PrimitiveThickness.Auto:
  39938. return "auto";
  39939. case PrimitiveThickness.Pixel:
  39940. return this._pixels[index] + "px";
  39941. case PrimitiveThickness.Percentage:
  39942. return this._percentages[index] * 100 + "%";
  39943. case PrimitiveThickness.Inherit:
  39944. return "inherit";
  39945. }
  39946. return "";
  39947. };
  39948. PrimitiveThickness.prototype._isType = function (index, type) {
  39949. var f = (this._flags >> (index * 4)) & 0xF;
  39950. return f === type;
  39951. };
  39952. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  39953. var t = (this._flags >> (index * 4)) & 0xF;
  39954. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  39955. var p = this._parentAccess();
  39956. if (p) {
  39957. return p._getType(index, true);
  39958. }
  39959. return PrimitiveThickness.Auto;
  39960. }
  39961. return t;
  39962. };
  39963. PrimitiveThickness.prototype._setType = function (index, type) {
  39964. this._flags &= ~(0xF << (index * 4));
  39965. this._flags |= type << (index * 4);
  39966. };
  39967. PrimitiveThickness.prototype.setTop = function (value) {
  39968. if (typeof value === "string") {
  39969. this._setStringValue(value, 0, true);
  39970. }
  39971. else {
  39972. this.topPixels = value;
  39973. }
  39974. };
  39975. PrimitiveThickness.prototype.setLeft = function (value) {
  39976. if (typeof value === "string") {
  39977. this._setStringValue(value, 1, true);
  39978. }
  39979. else {
  39980. this.leftPixels = value;
  39981. }
  39982. };
  39983. PrimitiveThickness.prototype.setRight = function (value) {
  39984. if (typeof value === "string") {
  39985. this._setStringValue(value, 2, true);
  39986. }
  39987. else {
  39988. this.rightPixels = value;
  39989. }
  39990. };
  39991. PrimitiveThickness.prototype.setBottom = function (value) {
  39992. if (typeof value === "string") {
  39993. this._setStringValue(value, 3, true);
  39994. }
  39995. else {
  39996. this.bottomPixels = value;
  39997. }
  39998. };
  39999. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  40000. /**
  40001. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40002. */
  40003. get: function () {
  40004. return this._getStringValue(0);
  40005. },
  40006. set: function (value) {
  40007. this._setStringValue(value, 0, true);
  40008. },
  40009. enumerable: true,
  40010. configurable: true
  40011. });
  40012. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  40013. /**
  40014. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40015. */
  40016. get: function () {
  40017. return this._getStringValue(1);
  40018. },
  40019. set: function (value) {
  40020. this._setStringValue(value, 1, true);
  40021. },
  40022. enumerable: true,
  40023. configurable: true
  40024. });
  40025. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  40026. /**
  40027. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40028. */
  40029. get: function () {
  40030. return this._getStringValue(2);
  40031. },
  40032. set: function (value) {
  40033. this._setStringValue(value, 2, true);
  40034. },
  40035. enumerable: true,
  40036. configurable: true
  40037. });
  40038. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  40039. /**
  40040. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  40041. */
  40042. get: function () {
  40043. return this._getStringValue(3);
  40044. },
  40045. set: function (value) {
  40046. this._setStringValue(value, 3, true);
  40047. },
  40048. enumerable: true,
  40049. configurable: true
  40050. });
  40051. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  40052. /**
  40053. * Get/set the top thickness in pixel.
  40054. */
  40055. get: function () {
  40056. return this._pixels[0];
  40057. },
  40058. set: function (value) {
  40059. this._setPixels(value, 0, true);
  40060. },
  40061. enumerable: true,
  40062. configurable: true
  40063. });
  40064. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  40065. /**
  40066. * Get/set the left thickness in pixel.
  40067. */
  40068. get: function () {
  40069. return this._pixels[1];
  40070. },
  40071. set: function (value) {
  40072. this._setPixels(value, 1, true);
  40073. },
  40074. enumerable: true,
  40075. configurable: true
  40076. });
  40077. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  40078. /**
  40079. * Get/set the right thickness in pixel.
  40080. */
  40081. get: function () {
  40082. return this._pixels[2];
  40083. },
  40084. set: function (value) {
  40085. this._setPixels(value, 2, true);
  40086. },
  40087. enumerable: true,
  40088. configurable: true
  40089. });
  40090. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  40091. /**
  40092. * Get/set the bottom thickness in pixel.
  40093. */
  40094. get: function () {
  40095. return this._pixels[3];
  40096. },
  40097. set: function (value) {
  40098. this._setPixels(value, 3, true);
  40099. },
  40100. enumerable: true,
  40101. configurable: true
  40102. });
  40103. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  40104. /**
  40105. * Get/set the top thickness in percentage.
  40106. * The get will return a valid value only if the edge type is percentage.
  40107. * The Set will change the edge mode if needed
  40108. */
  40109. get: function () {
  40110. return this._percentages[0];
  40111. },
  40112. set: function (value) {
  40113. this._setPercentage(value, 0, true);
  40114. },
  40115. enumerable: true,
  40116. configurable: true
  40117. });
  40118. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  40119. /**
  40120. * Get/set the left thickness in percentage.
  40121. * The get will return a valid value only if the edge mode is percentage.
  40122. * The Set will change the edge mode if needed
  40123. */
  40124. get: function () {
  40125. return this._percentages[1];
  40126. },
  40127. set: function (value) {
  40128. this._setPercentage(value, 1, true);
  40129. },
  40130. enumerable: true,
  40131. configurable: true
  40132. });
  40133. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  40134. /**
  40135. * Get/set the right thickness in percentage.
  40136. * The get will return a valid value only if the edge mode is percentage.
  40137. * The Set will change the edge mode if needed
  40138. */
  40139. get: function () {
  40140. return this._percentages[2];
  40141. },
  40142. set: function (value) {
  40143. this._setPercentage(value, 2, true);
  40144. },
  40145. enumerable: true,
  40146. configurable: true
  40147. });
  40148. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  40149. /**
  40150. * Get/set the bottom thickness in percentage.
  40151. * The get will return a valid value only if the edge mode is percentage.
  40152. * The Set will change the edge mode if needed
  40153. */
  40154. get: function () {
  40155. return this._percentages[3];
  40156. },
  40157. set: function (value) {
  40158. this._setPercentage(value, 3, true);
  40159. },
  40160. enumerable: true,
  40161. configurable: true
  40162. });
  40163. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  40164. /**
  40165. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  40166. */
  40167. get: function () {
  40168. return this._getType(0, false);
  40169. },
  40170. set: function (mode) {
  40171. this._setType(0, mode);
  40172. },
  40173. enumerable: true,
  40174. configurable: true
  40175. });
  40176. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  40177. /**
  40178. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  40179. */
  40180. get: function () {
  40181. return this._getType(1, false);
  40182. },
  40183. set: function (mode) {
  40184. this._setType(1, mode);
  40185. },
  40186. enumerable: true,
  40187. configurable: true
  40188. });
  40189. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  40190. /**
  40191. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  40192. */
  40193. get: function () {
  40194. return this._getType(2, false);
  40195. },
  40196. set: function (mode) {
  40197. this._setType(2, mode);
  40198. },
  40199. enumerable: true,
  40200. configurable: true
  40201. });
  40202. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  40203. /**
  40204. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  40205. */
  40206. get: function () {
  40207. return this._getType(3, false);
  40208. },
  40209. set: function (mode) {
  40210. this._setType(3, mode);
  40211. },
  40212. enumerable: true,
  40213. configurable: true
  40214. });
  40215. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  40216. var type = this._getType(index, false);
  40217. if (type === PrimitiveThickness.Inherit) {
  40218. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  40219. return;
  40220. }
  40221. if (type !== PrimitiveThickness.Percentage) {
  40222. return;
  40223. }
  40224. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  40225. this._pixels[index] = pixels;
  40226. if (emitChanged) {
  40227. this._changedCallback();
  40228. }
  40229. };
  40230. /**
  40231. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  40232. * @param sourceArea the source area
  40233. * @param contentSize the content size to position/resize
  40234. * @param alignment the alignment setting
  40235. * @param dstOffset the position of the content
  40236. * @param dstArea the new size of the content
  40237. */
  40238. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea) {
  40239. // Fetch some data
  40240. var topType = this._getType(0, true);
  40241. var leftType = this._getType(1, true);
  40242. var rightType = this._getType(2, true);
  40243. var bottomType = this._getType(3, true);
  40244. var hasWidth = contentSize && (contentSize.width != null);
  40245. var hasHeight = contentSize && (contentSize.height != null);
  40246. var width = hasWidth ? contentSize.width : 0;
  40247. var height = hasHeight ? contentSize.height : 0;
  40248. var isTopAuto = topType === PrimitiveThickness.Auto;
  40249. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  40250. var isRightAuto = rightType === PrimitiveThickness.Auto;
  40251. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  40252. switch (alignment.horizontal) {
  40253. case PrimitiveAlignment.AlignLeft:
  40254. {
  40255. if (isLeftAuto) {
  40256. dstOffset.x = 0;
  40257. }
  40258. else {
  40259. this._computePixels(1, sourceArea, true);
  40260. dstOffset.x = this.leftPixels;
  40261. }
  40262. dstArea.width = width;
  40263. break;
  40264. }
  40265. case PrimitiveAlignment.AlignRight:
  40266. {
  40267. if (isRightAuto) {
  40268. dstOffset.x = Math.round(sourceArea.width - width);
  40269. }
  40270. else {
  40271. this._computePixels(2, sourceArea, true);
  40272. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  40273. }
  40274. dstArea.width = width;
  40275. break;
  40276. }
  40277. case PrimitiveAlignment.AlignStretch:
  40278. {
  40279. if (isLeftAuto) {
  40280. dstOffset.x = 0;
  40281. }
  40282. else {
  40283. this._computePixels(1, sourceArea, true);
  40284. dstOffset.x = this.leftPixels;
  40285. }
  40286. var right = 0;
  40287. if (!isRightAuto) {
  40288. this._computePixels(2, sourceArea, true);
  40289. right = this.rightPixels;
  40290. }
  40291. dstArea.width = sourceArea.width - (dstOffset.x + right);
  40292. break;
  40293. }
  40294. case PrimitiveAlignment.AlignCenter:
  40295. {
  40296. if (!isLeftAuto) {
  40297. this._computePixels(1, sourceArea, true);
  40298. }
  40299. if (!isRightAuto) {
  40300. this._computePixels(2, sourceArea, true);
  40301. }
  40302. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  40303. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  40304. dstArea.width = width;
  40305. break;
  40306. }
  40307. }
  40308. switch (alignment.vertical) {
  40309. case PrimitiveAlignment.AlignTop:
  40310. {
  40311. if (isTopAuto) {
  40312. dstOffset.y = sourceArea.height - height;
  40313. }
  40314. else {
  40315. this._computePixels(0, sourceArea, true);
  40316. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  40317. }
  40318. dstArea.height = height;
  40319. break;
  40320. }
  40321. case PrimitiveAlignment.AlignBottom:
  40322. {
  40323. if (isBottomAuto) {
  40324. dstOffset.y = 0;
  40325. }
  40326. else {
  40327. this._computePixels(3, sourceArea, true);
  40328. dstOffset.y = this.bottomPixels;
  40329. }
  40330. dstArea.height = height;
  40331. break;
  40332. }
  40333. case PrimitiveAlignment.AlignStretch:
  40334. {
  40335. if (isBottomAuto) {
  40336. dstOffset.y = 0;
  40337. }
  40338. else {
  40339. this._computePixels(3, sourceArea, true);
  40340. dstOffset.y = this.bottomPixels;
  40341. }
  40342. var top_1 = 0;
  40343. if (!isTopAuto) {
  40344. this._computePixels(0, sourceArea, true);
  40345. top_1 = this.topPixels;
  40346. }
  40347. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  40348. break;
  40349. }
  40350. case PrimitiveAlignment.AlignCenter:
  40351. {
  40352. if (!isTopAuto) {
  40353. this._computePixels(0, sourceArea, true);
  40354. }
  40355. if (!isBottomAuto) {
  40356. this._computePixels(3, sourceArea, true);
  40357. }
  40358. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  40359. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  40360. dstArea.height = height;
  40361. break;
  40362. }
  40363. }
  40364. };
  40365. /**
  40366. * Compute an area and its position considering this thickness properties based on a given source area
  40367. * @param sourceArea the source area
  40368. * @param dstOffset the position of the resulting area
  40369. * @param dstArea the size of the resulting area
  40370. */
  40371. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  40372. this._computePixels(0, sourceArea, true);
  40373. this._computePixels(1, sourceArea, true);
  40374. this._computePixels(2, sourceArea, true);
  40375. this._computePixels(3, sourceArea, true);
  40376. dstOffset.x = this.leftPixels;
  40377. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  40378. dstOffset.y = this.bottomPixels;
  40379. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  40380. };
  40381. /**
  40382. * Compute an area considering this thickness properties based on a given source area
  40383. * @param sourceArea the source area
  40384. * @param result the resulting area
  40385. */
  40386. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  40387. this._computePixels(0, sourceArea, true);
  40388. this._computePixels(1, sourceArea, true);
  40389. this._computePixels(2, sourceArea, true);
  40390. this._computePixels(3, sourceArea, true);
  40391. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  40392. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  40393. };
  40394. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  40395. this._computePixels(0, sourceArea, true);
  40396. this._computePixels(1, sourceArea, true);
  40397. this._computePixels(2, sourceArea, true);
  40398. this._computePixels(3, sourceArea, true);
  40399. dstOffset.x = this.leftPixels;
  40400. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  40401. dstOffset.y = this.bottomPixels;
  40402. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  40403. };
  40404. PrimitiveThickness.Auto = 0x1;
  40405. PrimitiveThickness.Inherit = 0x2;
  40406. PrimitiveThickness.Percentage = 0x4;
  40407. PrimitiveThickness.Pixel = 0x8;
  40408. return PrimitiveThickness;
  40409. })();
  40410. BABYLON.PrimitiveThickness = PrimitiveThickness;
  40411. /**
  40412. * Main class used for the Primitive Intersection API
  40413. */
  40414. var IntersectInfo2D = (function () {
  40415. function IntersectInfo2D() {
  40416. this.findFirstOnly = false;
  40417. this.intersectHidden = false;
  40418. this.pickPosition = BABYLON.Vector2.Zero();
  40419. }
  40420. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  40421. /**
  40422. * true if at least one primitive intersected during the test
  40423. */
  40424. get: function () {
  40425. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  40426. },
  40427. enumerable: true,
  40428. configurable: true
  40429. });
  40430. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  40431. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  40432. var cur = _a[_i];
  40433. if (cur.prim === prim) {
  40434. return cur.intersectionLocation;
  40435. }
  40436. }
  40437. return null;
  40438. };
  40439. // Internals, don't use
  40440. IntersectInfo2D.prototype._exit = function (firstLevel) {
  40441. if (firstLevel) {
  40442. this._globalPickPosition = null;
  40443. }
  40444. };
  40445. return IntersectInfo2D;
  40446. })();
  40447. BABYLON.IntersectInfo2D = IntersectInfo2D;
  40448. var Prim2DBase = (function (_super) {
  40449. __extends(Prim2DBase, _super);
  40450. function Prim2DBase(settings) {
  40451. // Avoid checking every time if the object exists
  40452. if (settings == null) {
  40453. settings = {};
  40454. }
  40455. // BASE CLASS CALL
  40456. _super.call(this);
  40457. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  40458. var owner;
  40459. var parent;
  40460. if (Prim2DBase._isCanvasInit) {
  40461. owner = this;
  40462. parent = null;
  40463. this._canvasPreInit(settings);
  40464. }
  40465. else {
  40466. if (settings.parent != null) {
  40467. parent = settings.parent;
  40468. owner = settings.parent.owner;
  40469. if (!owner) {
  40470. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  40471. }
  40472. 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)) {
  40473. 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");
  40474. }
  40475. }
  40476. }
  40477. // Fields initialization
  40478. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40479. this._size = null; //Size.Zero();
  40480. this._scale = new BABYLON.Vector2(1, 1);
  40481. this._actualSize = null;
  40482. this._boundingSize = BABYLON.Size.Zero();
  40483. this._layoutArea = BABYLON.Size.Zero();
  40484. this._layoutAreaPos = BABYLON.Vector2.Zero();
  40485. this._marginOffset = BABYLON.Vector2.Zero();
  40486. this._paddingOffset = BABYLON.Vector2.Zero();
  40487. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  40488. this._parentContentArea = BABYLON.Size.Zero();
  40489. this._lastAutoSizeArea = BABYLON.Size.Zero();
  40490. this._contentArea = new BABYLON.Size(null, null);
  40491. this._pointerEventObservable = new BABYLON.Observable();
  40492. this._boundingInfo = new BABYLON.BoundingInfo2D();
  40493. this._owner = owner;
  40494. this._parent = null;
  40495. this._margin = null;
  40496. this._padding = null;
  40497. this._marginAlignment = null;
  40498. this._id = settings.id;
  40499. this.propertyChanged = new BABYLON.Observable();
  40500. this._children = new Array();
  40501. this._localTransform = new BABYLON.Matrix();
  40502. this._globalTransform = null;
  40503. this._invGlobalTransform = null;
  40504. this._globalTransformProcessStep = 0;
  40505. this._globalTransformStep = 0;
  40506. this._renderGroup = null;
  40507. this._primLinearPosition = 0;
  40508. this._manualZOrder = null;
  40509. this._zOrder = 0;
  40510. this._zMax = 0;
  40511. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40512. this._actualOpacity = 0;
  40513. this._actualScale = BABYLON.Vector2.Zero();
  40514. var isPickable = true;
  40515. var isContainer = true;
  40516. if (settings.isPickable !== undefined) {
  40517. isPickable = settings.isPickable;
  40518. }
  40519. if (settings.isContainer !== undefined) {
  40520. isContainer = settings.isContainer;
  40521. }
  40522. if (settings.dontInheritParentScale) {
  40523. this._setFlags(BABYLON.SmartPropertyPrim.flagDontInheritParentScale);
  40524. }
  40525. this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0) | BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  40526. if (settings.opacity != null) {
  40527. this._opacity = settings.opacity;
  40528. }
  40529. else {
  40530. this._opacity = 1;
  40531. }
  40532. this._updateRenderMode();
  40533. if (settings.childrenFlatZOrder) {
  40534. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40535. }
  40536. // If the parent is given, initialize the hierarchy/owner related data
  40537. if (parent != null) {
  40538. parent.addChild(this);
  40539. this._hierarchyDepth = parent._hierarchyDepth + 1;
  40540. this._patchHierarchy(parent.owner);
  40541. }
  40542. // If it's a group, detect its own states
  40543. if (this.owner && this instanceof BABYLON.Group2D) {
  40544. var group = this;
  40545. group.detectGroupStates();
  40546. }
  40547. // Time to insert children if some are specified
  40548. if (settings.children != null) {
  40549. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  40550. var child = _a[_i];
  40551. this.addChild(child);
  40552. // Good time to patch the hierarchy, it won't go very far if there's no need to
  40553. if (this.owner != null) {
  40554. child._patchHierarchy(this.owner);
  40555. }
  40556. }
  40557. }
  40558. if (settings.zOrder != null) {
  40559. this.zOrder = settings.zOrder;
  40560. }
  40561. // Set the model related properties
  40562. if (settings.position != null) {
  40563. this.position = settings.position;
  40564. }
  40565. else if (settings.x != null || settings.y != null) {
  40566. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  40567. }
  40568. else {
  40569. this._position = null;
  40570. }
  40571. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  40572. if (settings.scale != null) {
  40573. this.scale = settings.scale;
  40574. }
  40575. else {
  40576. if (settings.scaleX != null) {
  40577. this.scaleX = settings.scaleX;
  40578. }
  40579. if (settings.scaleY != null) {
  40580. this.scaleY = settings.scaleY;
  40581. }
  40582. }
  40583. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  40584. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  40585. // Layout Engine
  40586. if (settings.layoutEngine != null) {
  40587. if (typeof settings.layoutEngine === "string") {
  40588. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  40589. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  40590. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40591. }
  40592. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  40593. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  40594. }
  40595. else if (name_1.indexOf("verticalstackpanel") === 0) {
  40596. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  40597. }
  40598. }
  40599. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  40600. this.layoutEngine = settings.layoutEngine;
  40601. }
  40602. }
  40603. // Set the layout/margin stuffs
  40604. if (settings.marginTop) {
  40605. this.margin.setTop(settings.marginTop);
  40606. }
  40607. if (settings.marginLeft) {
  40608. this.margin.setLeft(settings.marginLeft);
  40609. }
  40610. if (settings.marginRight) {
  40611. this.margin.setRight(settings.marginRight);
  40612. }
  40613. if (settings.marginBottom) {
  40614. this.margin.setBottom(settings.marginBottom);
  40615. }
  40616. if (settings.margin) {
  40617. if (typeof settings.margin === "string") {
  40618. this.margin.fromString(settings.margin);
  40619. }
  40620. else {
  40621. this.margin.fromUniformPixels(settings.margin);
  40622. }
  40623. }
  40624. if (settings.marginHAlignment) {
  40625. this.marginAlignment.horizontal = settings.marginHAlignment;
  40626. }
  40627. if (settings.marginVAlignment) {
  40628. this.marginAlignment.vertical = settings.marginVAlignment;
  40629. }
  40630. if (settings.marginAlignment) {
  40631. this.marginAlignment.fromString(settings.marginAlignment);
  40632. }
  40633. if (settings.paddingTop) {
  40634. this.padding.setTop(settings.paddingTop);
  40635. }
  40636. if (settings.paddingLeft) {
  40637. this.padding.setLeft(settings.paddingLeft);
  40638. }
  40639. if (settings.paddingRight) {
  40640. this.padding.setRight(settings.paddingRight);
  40641. }
  40642. if (settings.paddingBottom) {
  40643. this.padding.setBottom(settings.paddingBottom);
  40644. }
  40645. if (settings.padding) {
  40646. this.padding.fromString(settings.padding);
  40647. }
  40648. // Dirty layout and positioning
  40649. this._parentLayoutDirty();
  40650. this._positioningDirty();
  40651. }
  40652. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  40653. get: function () {
  40654. if (!this._actionManager) {
  40655. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  40656. }
  40657. return this._actionManager;
  40658. },
  40659. enumerable: true,
  40660. configurable: true
  40661. });
  40662. /**
  40663. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  40664. * @param predicate the predicate to test on each parent
  40665. * @return the first primitive where the predicate was successful
  40666. */
  40667. Prim2DBase.prototype.traverseUp = function (predicate) {
  40668. var p = this;
  40669. while (p != null) {
  40670. if (predicate(p)) {
  40671. return p;
  40672. }
  40673. p = p._parent;
  40674. }
  40675. return null;
  40676. };
  40677. Object.defineProperty(Prim2DBase.prototype, "owner", {
  40678. /**
  40679. * Retrieve the owner Canvas2D
  40680. */
  40681. get: function () {
  40682. return this._owner;
  40683. },
  40684. enumerable: true,
  40685. configurable: true
  40686. });
  40687. Object.defineProperty(Prim2DBase.prototype, "parent", {
  40688. /**
  40689. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  40690. */
  40691. get: function () {
  40692. return this._parent;
  40693. },
  40694. enumerable: true,
  40695. configurable: true
  40696. });
  40697. Object.defineProperty(Prim2DBase.prototype, "children", {
  40698. /**
  40699. * The array of direct children primitives
  40700. */
  40701. get: function () {
  40702. return this._children;
  40703. },
  40704. enumerable: true,
  40705. configurable: true
  40706. });
  40707. Object.defineProperty(Prim2DBase.prototype, "id", {
  40708. /**
  40709. * The identifier of this primitive, may not be unique, it's for information purpose only
  40710. */
  40711. get: function () {
  40712. return this._id;
  40713. },
  40714. enumerable: true,
  40715. configurable: true
  40716. });
  40717. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  40718. get: function () {
  40719. if (this._actualPosition != null) {
  40720. return this._actualPosition;
  40721. }
  40722. if (this._position != null) {
  40723. return this._position;
  40724. }
  40725. // At least return 0,0, we can't return null on actualPosition
  40726. return Prim2DBase._nullPosition;
  40727. },
  40728. /**
  40729. * DO NOT INVOKE for internal purpose only
  40730. */
  40731. set: function (val) {
  40732. this._actualPosition = val;
  40733. },
  40734. enumerable: true,
  40735. configurable: true
  40736. });
  40737. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  40738. /**
  40739. * Shortcut to actualPosition.x
  40740. */
  40741. get: function () {
  40742. return this.actualPosition.x;
  40743. },
  40744. enumerable: true,
  40745. configurable: true
  40746. });
  40747. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  40748. /**
  40749. * Shortcut to actualPosition.y
  40750. */
  40751. get: function () {
  40752. return this.actualPosition.y;
  40753. },
  40754. enumerable: true,
  40755. configurable: true
  40756. });
  40757. Object.defineProperty(Prim2DBase.prototype, "position", {
  40758. /**
  40759. * Position of the primitive, relative to its parent.
  40760. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  40761. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  40762. * Setting this property may have no effect is specific alignment are in effect.
  40763. */
  40764. get: function () {
  40765. return this._position || Prim2DBase._nullPosition;
  40766. },
  40767. set: function (value) {
  40768. if (!this._checkPositionChange()) {
  40769. return;
  40770. }
  40771. this._position = value;
  40772. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  40773. },
  40774. enumerable: true,
  40775. configurable: true
  40776. });
  40777. Object.defineProperty(Prim2DBase.prototype, "x", {
  40778. /**
  40779. * Direct access to the position.x value of the primitive
  40780. * Use this property when you only want to change one component of the position property
  40781. */
  40782. get: function () {
  40783. if (!this._position) {
  40784. return null;
  40785. }
  40786. return this._position.x;
  40787. },
  40788. set: function (value) {
  40789. if (!this._checkPositionChange()) {
  40790. return;
  40791. }
  40792. if (!this._position) {
  40793. this._position = BABYLON.Vector2.Zero();
  40794. }
  40795. if (this._position.x === value) {
  40796. return;
  40797. }
  40798. this._position.x = value;
  40799. this._triggerPropertyChanged(Prim2DBase.positionProperty, value);
  40800. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  40801. },
  40802. enumerable: true,
  40803. configurable: true
  40804. });
  40805. Object.defineProperty(Prim2DBase.prototype, "y", {
  40806. /**
  40807. * Direct access to the position.y value of the primitive
  40808. * Use this property when you only want to change one component of the position property
  40809. */
  40810. get: function () {
  40811. if (!this._position) {
  40812. return null;
  40813. }
  40814. return this._position.y;
  40815. },
  40816. set: function (value) {
  40817. if (!this._checkPositionChange()) {
  40818. return;
  40819. }
  40820. if (!this._position) {
  40821. this._position = BABYLON.Vector2.Zero();
  40822. }
  40823. if (this._position.y === value) {
  40824. return;
  40825. }
  40826. this._position.y = value;
  40827. this._triggerPropertyChanged(Prim2DBase.positionProperty, value);
  40828. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  40829. },
  40830. enumerable: true,
  40831. configurable: true
  40832. });
  40833. Object.defineProperty(Prim2DBase.prototype, "size", {
  40834. /**
  40835. * Size of the primitive or its bounding area
  40836. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  40837. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  40838. */
  40839. get: function () {
  40840. if (!this._size || this._size.width == null || this._size.height == null) {
  40841. if (Prim2DBase.boundinbBoxReentrency) {
  40842. return Prim2DBase.nullSize;
  40843. }
  40844. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  40845. return this._boundingSize;
  40846. }
  40847. Prim2DBase.boundinbBoxReentrency = true;
  40848. var b = this.boundingInfo;
  40849. Prim2DBase.boundinbBoxReentrency = false;
  40850. return this._boundingSize;
  40851. }
  40852. return this._size;
  40853. },
  40854. set: function (value) {
  40855. this._size = value;
  40856. },
  40857. enumerable: true,
  40858. configurable: true
  40859. });
  40860. Object.defineProperty(Prim2DBase.prototype, "width", {
  40861. /**
  40862. * Direct access to the size.width value of the primitive
  40863. * Use this property when you only want to change one component of the size property
  40864. */
  40865. get: function () {
  40866. if (!this.size) {
  40867. return null;
  40868. }
  40869. return this.size.width;
  40870. },
  40871. set: function (value) {
  40872. if (!this.size) {
  40873. this.size = new BABYLON.Size(value, 0);
  40874. return;
  40875. }
  40876. if (this.size.width === value) {
  40877. return;
  40878. }
  40879. this.size.width = value;
  40880. this._triggerPropertyChanged(Prim2DBase.sizeProperty, value);
  40881. this._positioningDirty();
  40882. },
  40883. enumerable: true,
  40884. configurable: true
  40885. });
  40886. Object.defineProperty(Prim2DBase.prototype, "height", {
  40887. /**
  40888. * Direct access to the size.height value of the primitive
  40889. * Use this property when you only want to change one component of the size property
  40890. */
  40891. get: function () {
  40892. if (!this.size) {
  40893. return null;
  40894. }
  40895. return this.size.height;
  40896. },
  40897. set: function (value) {
  40898. if (!this.size) {
  40899. this.size = new BABYLON.Size(0, value);
  40900. return;
  40901. }
  40902. if (this.size.height === value) {
  40903. return;
  40904. }
  40905. this.size.height = value;
  40906. this._triggerPropertyChanged(Prim2DBase.sizeProperty, value);
  40907. this._positioningDirty();
  40908. },
  40909. enumerable: true,
  40910. configurable: true
  40911. });
  40912. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  40913. get: function () {
  40914. return this._rotation;
  40915. },
  40916. set: function (value) {
  40917. this._rotation = value;
  40918. },
  40919. enumerable: true,
  40920. configurable: true
  40921. });
  40922. Object.defineProperty(Prim2DBase.prototype, "scale", {
  40923. get: function () {
  40924. return this._scale.x;
  40925. },
  40926. set: function (value) {
  40927. this._scale.x = this._scale.y = value;
  40928. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  40929. this._spreadActualScaleDirty();
  40930. },
  40931. enumerable: true,
  40932. configurable: true
  40933. });
  40934. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  40935. /**
  40936. * Return the size of the primitive as it's being rendered into the target.
  40937. * 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.
  40938. * BEWARE: don't use the setter, it's for internal purpose only
  40939. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  40940. */
  40941. get: function () {
  40942. if (this._actualSize) {
  40943. return this._actualSize;
  40944. }
  40945. return this._size;
  40946. },
  40947. set: function (value) {
  40948. if (this._actualSize.equals(value)) {
  40949. return;
  40950. }
  40951. this._actualSize = value;
  40952. },
  40953. enumerable: true,
  40954. configurable: true
  40955. });
  40956. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  40957. get: function () {
  40958. if (this._manualZOrder != null) {
  40959. return this._manualZOrder;
  40960. }
  40961. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40962. this._updateZOrder();
  40963. }
  40964. return (1 - this._zOrder);
  40965. },
  40966. enumerable: true,
  40967. configurable: true
  40968. });
  40969. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  40970. /**
  40971. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  40972. * The Primitive's size won't be less than specified.
  40973. * The default value depends of the Primitive type
  40974. */
  40975. get: function () {
  40976. return this._minSize;
  40977. },
  40978. set: function (value) {
  40979. if (this._minSize && value && this._minSize.equals(value)) {
  40980. return;
  40981. }
  40982. this._minSize = value;
  40983. this._parentLayoutDirty();
  40984. },
  40985. enumerable: true,
  40986. configurable: true
  40987. });
  40988. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  40989. /**
  40990. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  40991. * The Primitive's size won't be more than specified.
  40992. * The default value depends of the Primitive type
  40993. */
  40994. get: function () {
  40995. return this._maxSize;
  40996. },
  40997. set: function (value) {
  40998. if (this._maxSize && value && this._maxSize.equals(value)) {
  40999. return;
  41000. }
  41001. this._maxSize = value;
  41002. this._parentLayoutDirty();
  41003. },
  41004. enumerable: true,
  41005. configurable: true
  41006. });
  41007. Object.defineProperty(Prim2DBase.prototype, "origin", {
  41008. /**
  41009. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  41010. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  41011. * For instance:
  41012. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  41013. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  41014. * 0,1 means the center is top/left
  41015. * @returns The normalized center.
  41016. */
  41017. get: function () {
  41018. return this._origin;
  41019. },
  41020. set: function (value) {
  41021. this._origin = value;
  41022. },
  41023. enumerable: true,
  41024. configurable: true
  41025. });
  41026. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  41027. get: function () {
  41028. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  41029. },
  41030. set: function (value) {
  41031. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  41032. },
  41033. enumerable: true,
  41034. configurable: true
  41035. });
  41036. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  41037. get: function () {
  41038. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  41039. },
  41040. set: function (value) {
  41041. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  41042. },
  41043. enumerable: true,
  41044. configurable: true
  41045. });
  41046. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  41047. get: function () {
  41048. return this._manualZOrder;
  41049. },
  41050. set: function (value) {
  41051. if (this._manualZOrder === value) {
  41052. return;
  41053. }
  41054. this._manualZOrder = value;
  41055. this.onZOrderChanged();
  41056. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  41057. this._actualZOrderChangedObservable.notifyObservers(value);
  41058. }
  41059. },
  41060. enumerable: true,
  41061. configurable: true
  41062. });
  41063. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  41064. get: function () {
  41065. return this._manualZOrder != null;
  41066. },
  41067. enumerable: true,
  41068. configurable: true
  41069. });
  41070. Object.defineProperty(Prim2DBase.prototype, "margin", {
  41071. get: function () {
  41072. var _this = this;
  41073. if (!this._margin) {
  41074. this._margin = new PrimitiveThickness(function () {
  41075. if (!_this.parent) {
  41076. return null;
  41077. }
  41078. return _this.parent.margin;
  41079. }, function () { return _this._positioningDirty(); });
  41080. }
  41081. return this._margin;
  41082. },
  41083. enumerable: true,
  41084. configurable: true
  41085. });
  41086. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  41087. get: function () {
  41088. return (this._margin !== null) || (this._marginAlignment !== null);
  41089. },
  41090. enumerable: true,
  41091. configurable: true
  41092. });
  41093. Object.defineProperty(Prim2DBase.prototype, "padding", {
  41094. get: function () {
  41095. var _this = this;
  41096. if (!this._padding) {
  41097. this._padding = new PrimitiveThickness(function () {
  41098. if (!_this.parent) {
  41099. return null;
  41100. }
  41101. return _this.parent.padding;
  41102. }, function () { return _this._positioningDirty(); });
  41103. }
  41104. return this._padding;
  41105. },
  41106. enumerable: true,
  41107. configurable: true
  41108. });
  41109. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  41110. get: function () {
  41111. return this._padding !== null;
  41112. },
  41113. enumerable: true,
  41114. configurable: true
  41115. });
  41116. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  41117. get: function () {
  41118. var _this = this;
  41119. if (!this._marginAlignment) {
  41120. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  41121. }
  41122. return this._marginAlignment;
  41123. },
  41124. enumerable: true,
  41125. configurable: true
  41126. });
  41127. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  41128. get: function () {
  41129. return this._opacity;
  41130. },
  41131. set: function (value) {
  41132. if (value < 0) {
  41133. value = 0;
  41134. }
  41135. else if (value > 1) {
  41136. value = 1;
  41137. }
  41138. if (this._opacity === value) {
  41139. return;
  41140. }
  41141. this._opacity = value;
  41142. this._updateRenderMode();
  41143. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41144. this._spreadActualOpacityChanged();
  41145. },
  41146. enumerable: true,
  41147. configurable: true
  41148. });
  41149. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  41150. get: function () {
  41151. return this._scale.x;
  41152. },
  41153. set: function (value) {
  41154. this._scale.x = value;
  41155. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41156. this._spreadActualScaleDirty();
  41157. },
  41158. enumerable: true,
  41159. configurable: true
  41160. });
  41161. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  41162. get: function () {
  41163. return this._scale.y;
  41164. },
  41165. set: function (value) {
  41166. this._scale.y = value;
  41167. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41168. this._spreadActualScaleDirty();
  41169. },
  41170. enumerable: true,
  41171. configurable: true
  41172. });
  41173. Prim2DBase.prototype._spreadActualScaleDirty = function () {
  41174. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41175. var child = _a[_i];
  41176. child._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41177. child._spreadActualScaleDirty();
  41178. }
  41179. };
  41180. Object.defineProperty(Prim2DBase.prototype, "actualScale", {
  41181. /**
  41182. * Returns the actual scale of this Primitive, the value is computed from the scale property of this primitive, multiplied by the actualScale of its parent one (if any). The Vector2 object returned contains the scale for both X and Y axis
  41183. */
  41184. get: function () {
  41185. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualScaleDirty)) {
  41186. var cur = this._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : this.parent;
  41187. var sx = this.scaleX;
  41188. var sy = this.scaleY;
  41189. while (cur) {
  41190. sx *= cur.scaleX;
  41191. sy *= cur.scaleY;
  41192. cur = cur._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : cur.parent;
  41193. }
  41194. this._actualScale.copyFromFloats(sx, sy);
  41195. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  41196. }
  41197. return this._actualScale;
  41198. },
  41199. enumerable: true,
  41200. configurable: true
  41201. });
  41202. Object.defineProperty(Prim2DBase.prototype, "actualScaleX", {
  41203. /**
  41204. * Get the actual Scale of the X axis, shortcut for this.actualScale.x
  41205. */
  41206. get: function () {
  41207. return this.actualScale.x;
  41208. },
  41209. enumerable: true,
  41210. configurable: true
  41211. });
  41212. Object.defineProperty(Prim2DBase.prototype, "actualScaleY", {
  41213. /**
  41214. * Get the actual Scale of the Y axis, shortcut for this.actualScale.y
  41215. */
  41216. get: function () {
  41217. return this.actualScale.y;
  41218. },
  41219. enumerable: true,
  41220. configurable: true
  41221. });
  41222. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  41223. /**
  41224. * Get the actual opacity level, this property is computed from the opacity property, multiplied by the actualOpacity of its parent (if any)
  41225. */
  41226. get: function () {
  41227. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  41228. var cur = this.parent;
  41229. var op = this.opacity;
  41230. while (cur) {
  41231. op *= cur.opacity;
  41232. cur = cur.parent;
  41233. }
  41234. this._actualOpacity = op;
  41235. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41236. }
  41237. return this._actualOpacity;
  41238. },
  41239. enumerable: true,
  41240. configurable: true
  41241. });
  41242. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  41243. /**
  41244. * Get/set the layout engine to use for this primitive.
  41245. * The default layout engine is the CanvasLayoutEngine.
  41246. */
  41247. get: function () {
  41248. if (!this._layoutEngine) {
  41249. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  41250. }
  41251. return this._layoutEngine;
  41252. },
  41253. set: function (value) {
  41254. if (this._layoutEngine === value) {
  41255. return;
  41256. }
  41257. this._changeLayoutEngine(value);
  41258. },
  41259. enumerable: true,
  41260. configurable: true
  41261. });
  41262. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  41263. /**
  41264. * Get/set the layout are of this primitive.
  41265. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  41266. * The setter should only be called by a Layout Engine class.
  41267. */
  41268. get: function () {
  41269. return this._layoutArea;
  41270. },
  41271. set: function (val) {
  41272. if (this._layoutArea.equals(val)) {
  41273. return;
  41274. }
  41275. this._positioningDirty();
  41276. this._layoutArea = val;
  41277. },
  41278. enumerable: true,
  41279. configurable: true
  41280. });
  41281. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  41282. /**
  41283. * Get/set the layout area position (relative to the parent primitive).
  41284. * The setter should only be called by a Layout Engine class.
  41285. */
  41286. get: function () {
  41287. return this._layoutAreaPos;
  41288. },
  41289. set: function (val) {
  41290. if (this._layoutAreaPos.equals(val)) {
  41291. return;
  41292. }
  41293. this._positioningDirty();
  41294. this._layoutAreaPos = val;
  41295. },
  41296. enumerable: true,
  41297. configurable: true
  41298. });
  41299. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  41300. /**
  41301. * Define if the Primitive can be subject to intersection test or not (default is true)
  41302. */
  41303. get: function () {
  41304. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  41305. },
  41306. set: function (value) {
  41307. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  41308. },
  41309. enumerable: true,
  41310. configurable: true
  41311. });
  41312. Object.defineProperty(Prim2DBase.prototype, "isContainer", {
  41313. /**
  41314. * Define if the Primitive acts as a container or not
  41315. * A container will encapsulate its children for interaction event.
  41316. * If it's not a container events will be process down to children if the primitive is not pickable.
  41317. * Default value is true
  41318. */
  41319. get: function () {
  41320. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
  41321. },
  41322. set: function (value) {
  41323. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
  41324. },
  41325. enumerable: true,
  41326. configurable: true
  41327. });
  41328. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  41329. /**
  41330. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  41331. */
  41332. get: function () {
  41333. return this._hierarchyDepth;
  41334. },
  41335. enumerable: true,
  41336. configurable: true
  41337. });
  41338. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  41339. /**
  41340. * Retrieve the Group that is responsible to render this primitive
  41341. */
  41342. get: function () {
  41343. return this._renderGroup;
  41344. },
  41345. enumerable: true,
  41346. configurable: true
  41347. });
  41348. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  41349. /**
  41350. * Get the global transformation matrix of the primitive
  41351. */
  41352. get: function () {
  41353. this._updateLocalTransform();
  41354. return this._globalTransform;
  41355. },
  41356. enumerable: true,
  41357. configurable: true
  41358. });
  41359. /**
  41360. * return the global position of the primitive, relative to its canvas
  41361. */
  41362. Prim2DBase.prototype.getGlobalPosition = function () {
  41363. var v = new BABYLON.Vector2(0, 0);
  41364. this.getGlobalPositionByRef(v);
  41365. return v;
  41366. };
  41367. /**
  41368. * return the global position of the primitive, relative to its canvas
  41369. * @param v the valid Vector2 object where the global position will be stored
  41370. */
  41371. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  41372. v.x = this.globalTransform.m[12];
  41373. v.y = this.globalTransform.m[13];
  41374. };
  41375. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  41376. /**
  41377. * Get invert of the global transformation matrix of the primitive
  41378. */
  41379. get: function () {
  41380. this._updateLocalTransform();
  41381. return this._invGlobalTransform;
  41382. },
  41383. enumerable: true,
  41384. configurable: true
  41385. });
  41386. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  41387. /**
  41388. * Get the local transformation of the primitive
  41389. */
  41390. get: function () {
  41391. this._updateLocalTransform();
  41392. return this._localTransform;
  41393. },
  41394. enumerable: true,
  41395. configurable: true
  41396. });
  41397. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  41398. /**
  41399. * Get the boundingInfo associated to the primitive and its children.
  41400. * The value is supposed to be always up to date
  41401. */
  41402. get: function () {
  41403. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  41404. if (this.owner) {
  41405. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  41406. }
  41407. if (this.isSizedByContent) {
  41408. this._boundingInfo.clear();
  41409. }
  41410. else {
  41411. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  41412. }
  41413. var bi = this._boundingInfo;
  41414. var tps = new BABYLON.BoundingInfo2D();
  41415. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41416. var curChild = _a[_i];
  41417. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  41418. bi.unionToRef(tps, bi);
  41419. }
  41420. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  41421. 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);
  41422. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  41423. }
  41424. return this._boundingInfo;
  41425. },
  41426. enumerable: true,
  41427. configurable: true
  41428. });
  41429. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  41430. /**
  41431. * Determine if the size is automatically computed or fixed because manually specified.
  41432. * Use the actualSize property to get the final/real size of the primitive
  41433. * @returns true if the size is automatically computed, false if it were manually specified.
  41434. */
  41435. get: function () {
  41436. return this._size == null;
  41437. },
  41438. enumerable: true,
  41439. configurable: true
  41440. });
  41441. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  41442. /**
  41443. * Return true if this prim has an auto size which is set by the children's global bounding box
  41444. */
  41445. get: function () {
  41446. return (this._size == null) && (this._children.length > 0);
  41447. },
  41448. enumerable: true,
  41449. configurable: true
  41450. });
  41451. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  41452. /**
  41453. * Determine if the position is automatically computed or fixed because manually specified.
  41454. * Use the actualPosition property to get the final/real position of the primitive
  41455. * @returns true if the position is automatically computed, false if it were manually specified.
  41456. */
  41457. get: function () {
  41458. return this._position == null;
  41459. },
  41460. enumerable: true,
  41461. configurable: true
  41462. });
  41463. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  41464. /**
  41465. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  41466. */
  41467. get: function () {
  41468. return this._pointerEventObservable;
  41469. },
  41470. enumerable: true,
  41471. configurable: true
  41472. });
  41473. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  41474. get: function () {
  41475. if (!this._actualZOrderChangedObservable) {
  41476. this._actualZOrderChangedObservable = new BABYLON.Observable();
  41477. }
  41478. return this._actualZOrderChangedObservable;
  41479. },
  41480. enumerable: true,
  41481. configurable: true
  41482. });
  41483. Prim2DBase.prototype.findById = function (id) {
  41484. if (this._id === id) {
  41485. return this;
  41486. }
  41487. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41488. var child = _a[_i];
  41489. var r = child.findById(id);
  41490. if (r != null) {
  41491. return r;
  41492. }
  41493. }
  41494. };
  41495. Prim2DBase.prototype.onZOrderChanged = function () {
  41496. };
  41497. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  41498. return false;
  41499. };
  41500. /**
  41501. * Capture all the Events of the given PointerId for this primitive.
  41502. * Don't forget to call releasePointerEventsCapture when done.
  41503. * @param pointerId the Id of the pointer to capture the events from.
  41504. */
  41505. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  41506. return this.owner._setPointerCapture(pointerId, this);
  41507. };
  41508. /**
  41509. * Release a captured pointer made with setPointerEventCapture.
  41510. * @param pointerId the Id of the pointer to release the capture from.
  41511. */
  41512. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  41513. return this.owner._releasePointerCapture(pointerId, this);
  41514. };
  41515. /**
  41516. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  41517. * @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.
  41518. */
  41519. Prim2DBase.prototype.intersect = function (intersectInfo) {
  41520. if (!intersectInfo) {
  41521. return false;
  41522. }
  41523. // If this is null it means this method is call for the first level, initialize stuffs
  41524. var firstLevel = !intersectInfo._globalPickPosition;
  41525. if (firstLevel) {
  41526. // 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).
  41527. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  41528. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  41529. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  41530. intersectInfo.intersectedPrimitives = new Array();
  41531. intersectInfo.topMostIntersectedPrimitive = null;
  41532. }
  41533. if (!intersectInfo.intersectHidden && !this.isVisible) {
  41534. return false;
  41535. }
  41536. var id = this.id;
  41537. if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  41538. var ownerGroup = this.getExternalData("__cachedGroup__");
  41539. return ownerGroup.intersect(intersectInfo);
  41540. }
  41541. // 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).
  41542. var isIntersectionTest = false;
  41543. if (this instanceof BABYLON.Group2D) {
  41544. var g = this;
  41545. isIntersectionTest = g.isCachedGroup;
  41546. }
  41547. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  41548. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  41549. intersectInfo._exit(firstLevel);
  41550. return false;
  41551. }
  41552. // Fast rejection test with boundingInfo
  41553. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  41554. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  41555. intersectInfo._exit(firstLevel);
  41556. return false;
  41557. }
  41558. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  41559. var levelIntersectRes = false;
  41560. if (this.isPickable) {
  41561. levelIntersectRes = this.levelIntersect(intersectInfo);
  41562. if (levelIntersectRes) {
  41563. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  41564. intersectInfo.intersectedPrimitives.push(pii);
  41565. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  41566. intersectInfo.topMostIntersectedPrimitive = pii;
  41567. }
  41568. // If we must stop at the first intersection, we're done, quit!
  41569. if (intersectInfo.findFirstOnly) {
  41570. intersectInfo._exit(firstLevel);
  41571. return true;
  41572. }
  41573. }
  41574. }
  41575. // Recurse to children if needed
  41576. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  41577. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41578. var curChild = _a[_i];
  41579. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  41580. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  41581. continue;
  41582. }
  41583. // Must compute the localPickLocation for the children level
  41584. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  41585. // If we got an intersection with the child and we only need to find the first one, quit!
  41586. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  41587. intersectInfo._exit(firstLevel);
  41588. return true;
  41589. }
  41590. }
  41591. }
  41592. intersectInfo._exit(firstLevel);
  41593. return intersectInfo.isIntersected;
  41594. };
  41595. /**
  41596. * Move a child object into a new position regarding its siblings to change its rendering order.
  41597. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  41598. * @param child the object to move
  41599. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  41600. */
  41601. Prim2DBase.prototype.moveChild = function (child, previous) {
  41602. if (child.parent !== this) {
  41603. return false;
  41604. }
  41605. var childIndex = this._children.indexOf(child);
  41606. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  41607. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41608. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41609. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  41610. }
  41611. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  41612. return true;
  41613. };
  41614. /**
  41615. * Move the given child so it's displayed on the top of all its siblings
  41616. * @param child the primitive to move to the top
  41617. */
  41618. Prim2DBase.prototype.moveChildToTop = function (child) {
  41619. return this.moveChild(child, this._children[this._children.length - 1]);
  41620. };
  41621. /**
  41622. * Move the given child so it's displayed on the bottom of all its siblings
  41623. * @param child the primitive to move to the top
  41624. */
  41625. Prim2DBase.prototype.moveChildToBottom = function (child) {
  41626. return this.moveChild(child, null);
  41627. };
  41628. /**
  41629. * Move this primitive to be at the top among all its sibling
  41630. */
  41631. Prim2DBase.prototype.moveToTop = function () {
  41632. if (this.parent == null) {
  41633. return false;
  41634. }
  41635. return this.parent.moveChildToTop(this);
  41636. };
  41637. /**
  41638. * Move this primitive to be at the bottom among all its sibling
  41639. */
  41640. Prim2DBase.prototype.moveToBottom = function () {
  41641. if (this.parent == null) {
  41642. return false;
  41643. }
  41644. return this.parent.moveChildToBottom(this);
  41645. };
  41646. Prim2DBase.prototype.addChild = function (child) {
  41647. child._parent = this;
  41648. this._boundingBoxDirty();
  41649. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41650. if (flat) {
  41651. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41652. child._setZOrder(this._zOrder, true);
  41653. child._zMax = this._zOrder;
  41654. }
  41655. else {
  41656. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41657. }
  41658. var length = this._children.push(child);
  41659. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  41660. };
  41661. /**
  41662. * Dispose the primitive, remove it from its parent.
  41663. */
  41664. Prim2DBase.prototype.dispose = function () {
  41665. if (!_super.prototype.dispose.call(this)) {
  41666. return false;
  41667. }
  41668. if (this._actionManager) {
  41669. this._actionManager.dispose();
  41670. this._actionManager = null;
  41671. }
  41672. // If there's a parent, remove this object from its parent list
  41673. if (this._parent) {
  41674. if (this instanceof BABYLON.Group2D) {
  41675. var g = this;
  41676. if (g.isRenderableGroup) {
  41677. var parentRenderable = this.parent.traverseUp(function (p) { return (p instanceof BABYLON.Group2D && p.isRenderableGroup); });
  41678. if (parentRenderable != null) {
  41679. var l = parentRenderable._renderableData._childrenRenderableGroups;
  41680. var i_1 = l.indexOf(g);
  41681. if (i_1 !== -1) {
  41682. l.splice(i_1, 1);
  41683. }
  41684. }
  41685. }
  41686. }
  41687. var i = this._parent._children.indexOf(this);
  41688. if (i !== undefined) {
  41689. this._parent._children.splice(i, 1);
  41690. }
  41691. this._parent = null;
  41692. }
  41693. // Recurse dispose to children
  41694. if (this._children) {
  41695. while (this._children.length > 0) {
  41696. this._children[this._children.length - 1].dispose();
  41697. }
  41698. }
  41699. return true;
  41700. };
  41701. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  41702. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  41703. this._renderGroup._addPrimToDirtyList(this);
  41704. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  41705. }
  41706. };
  41707. Prim2DBase.prototype._needPrepare = function () {
  41708. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty | BABYLON.SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  41709. };
  41710. Prim2DBase.prototype._prepareRender = function (context) {
  41711. this._prepareRenderPre(context);
  41712. this._prepareRenderPost(context);
  41713. };
  41714. Prim2DBase.prototype._prepareRenderPre = function (context) {
  41715. };
  41716. Prim2DBase.prototype._prepareRenderPost = function (context) {
  41717. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  41718. if (this instanceof BABYLON.Group2D) {
  41719. var self = this;
  41720. if (self.isRenderableGroup) {
  41721. return;
  41722. }
  41723. }
  41724. // Check if we need to recurse the prepare to children primitives
  41725. // - must have children
  41726. // - the global transform of this level have changed, or
  41727. // - the visible state of primitive has changed
  41728. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  41729. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  41730. this._children.forEach(function (c) {
  41731. // As usual stop the recursion if we meet a renderable group
  41732. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  41733. c._prepareRender(context);
  41734. }
  41735. });
  41736. }
  41737. // Finally reset the dirty flags as we've processed everything
  41738. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  41739. this._instanceDirtyFlags = 0;
  41740. };
  41741. Prim2DBase.prototype._canvasPreInit = function (settings) {
  41742. };
  41743. Prim2DBase.CheckParent = function (parent) {
  41744. //if (!Prim2DBase._isCanvasInit && !parent) {
  41745. // 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)");
  41746. //}
  41747. };
  41748. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  41749. for (var _i = 0; _i < list.length; _i++) {
  41750. var cur = list[_i];
  41751. cur.updateCachedStates(recurse);
  41752. }
  41753. };
  41754. Prim2DBase.prototype._parentLayoutDirty = function () {
  41755. if (!this._parent || this._parent.isDisposed) {
  41756. return;
  41757. }
  41758. this._parent._setLayoutDirty();
  41759. };
  41760. Prim2DBase.prototype._setLayoutDirty = function () {
  41761. this.onPrimBecomesDirty();
  41762. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  41763. };
  41764. Prim2DBase.prototype._checkPositionChange = function () {
  41765. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  41766. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  41767. return false;
  41768. }
  41769. return true;
  41770. };
  41771. Prim2DBase.prototype._positioningDirty = function () {
  41772. this.onPrimBecomesDirty();
  41773. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41774. };
  41775. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  41776. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41777. var child = _a[_i];
  41778. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41779. child._updateRenderMode();
  41780. child.onPrimBecomesDirty();
  41781. child._spreadActualOpacityChanged();
  41782. }
  41783. };
  41784. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  41785. this._layoutEngine = engine;
  41786. };
  41787. Prim2DBase.prototype._updateLocalTransform = function () {
  41788. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.scaleXProperty.flagId | Prim2DBase.scaleYProperty.flagId | Prim2DBase.originProperty.flagId;
  41789. if (this.checkPropertiesDirty(tflags)) {
  41790. if (this.owner) {
  41791. this.owner.addupdateLocalTransformCounter(1);
  41792. }
  41793. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  41794. var local;
  41795. var pos = this.position;
  41796. if (this._origin.x === 0 && this._origin.y === 0) {
  41797. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale.x, this._scale.y, 1), rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  41798. this._localTransform = local;
  41799. }
  41800. else {
  41801. // -Origin offset
  41802. var as = this.actualSize;
  41803. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  41804. // -Origin * rotation
  41805. rot.toRotationMatrix(Prim2DBase._t1);
  41806. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  41807. // -Origin * rotation * scale
  41808. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase._t0);
  41809. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  41810. // -Origin * rotation * scale * (Origin + Position)
  41811. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  41812. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  41813. }
  41814. this.clearPropertiesDirty(tflags);
  41815. this._setFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  41816. return true;
  41817. }
  41818. return false;
  41819. };
  41820. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  41821. if (this.isDisposed) {
  41822. return;
  41823. }
  41824. this.owner.addCachedGroupRenderCounter(1);
  41825. // Check if the parent is synced
  41826. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  41827. this._parent.updateCachedStates(false);
  41828. }
  41829. // Update Z-Order if needed
  41830. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41831. this._updateZOrder();
  41832. }
  41833. // Update actualSize only if there' not positioning to recompute and the size changed
  41834. // Otherwise positioning will take care of it.
  41835. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41836. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  41837. var size = this.size;
  41838. if (size) {
  41839. if (this.size.width != null) {
  41840. this.actualSize.width = this.size.width;
  41841. }
  41842. if (this.size.height != null) {
  41843. this.actualSize.height = this.size.height;
  41844. }
  41845. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41846. }
  41847. }
  41848. // Check for layout update
  41849. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41850. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  41851. this.owner.addUpdateLayoutCounter(1);
  41852. this._layoutEngine.updateLayout(this);
  41853. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  41854. }
  41855. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41856. var autoContentChanged = false;
  41857. if (this.isSizeAuto) {
  41858. if (!this._lastAutoSizeArea) {
  41859. autoContentChanged = this.size !== null;
  41860. }
  41861. else {
  41862. autoContentChanged = (!this._lastAutoSizeArea.equals(this.size));
  41863. }
  41864. }
  41865. // Check for positioning update
  41866. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  41867. this._updatePositioning();
  41868. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41869. if (sizeDirty) {
  41870. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41871. }
  41872. positioningComputed = true;
  41873. }
  41874. if (positioningComputed && this._parent) {
  41875. this._parentContentArea.copyFrom(this._parent.contentArea);
  41876. }
  41877. // Check if we must update this prim
  41878. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  41879. this.owner.addUpdateGlobalTransformCounter(1);
  41880. var curVisibleState = this.isVisible;
  41881. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  41882. // Detect a change of visibility
  41883. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  41884. // Get/compute the localTransform
  41885. var localDirty = this._updateLocalTransform();
  41886. var parentPaddingChanged = false;
  41887. var parentPaddingOffset = Prim2DBase._v0;
  41888. if (this._parent) {
  41889. parentPaddingOffset = this._parent._paddingOffset;
  41890. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  41891. }
  41892. // Check if there are changes in the parent that will force us to update the global matrix
  41893. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  41894. // Check if we have to update the globalTransform
  41895. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty)) {
  41896. var globalTransform = this._parent ? this._parent._globalTransform : null;
  41897. var localTransform;
  41898. Prim2DBase._transMtx.copyFrom(this._localTransform);
  41899. Prim2DBase._transMtx.m[12] += this._layoutAreaPos.x + this._marginOffset.x + parentPaddingOffset.x;
  41900. Prim2DBase._transMtx.m[13] += this._layoutAreaPos.y + this._marginOffset.y + parentPaddingOffset.y;
  41901. localTransform = Prim2DBase._transMtx;
  41902. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  41903. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  41904. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  41905. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  41906. this._clearFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  41907. }
  41908. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  41909. }
  41910. if (recurse) {
  41911. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41912. var child = _a[_i];
  41913. // Stop the recursion if we meet a renderable group
  41914. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  41915. }
  41916. }
  41917. };
  41918. Prim2DBase.prototype._updatePositioning = function () {
  41919. if (this.owner) {
  41920. this.owner.addUpdatePositioningCounter(1);
  41921. }
  41922. // From this point we assume that the primitive layoutArea is computed and up to date.
  41923. // We know have to :
  41924. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  41925. // 2. Determine the contentArea based on the padding property.
  41926. // 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
  41927. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  41928. if (this.actualSize.width == null) {
  41929. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  41930. }
  41931. if (this.actualSize.height == null) {
  41932. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  41933. }
  41934. }
  41935. // Apply margin
  41936. if (this._hasMargin) {
  41937. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  41938. this.actualSize = Prim2DBase._size.clone();
  41939. }
  41940. var isSizeAuto = this.isSizeAuto;
  41941. if (this._hasPadding) {
  41942. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  41943. if (isSizeAuto) {
  41944. var content = this.size.clone();
  41945. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  41946. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  41947. this._contentArea.copyFrom(content);
  41948. this.actualSize = Prim2DBase._size.clone();
  41949. // Changing the padding has resize the prim, which forces us to recompute margin again
  41950. if (this._hasMargin) {
  41951. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  41952. }
  41953. }
  41954. else {
  41955. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  41956. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  41957. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  41958. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  41959. this._paddingOffset.x += Prim2DBase._icPos.x;
  41960. this._paddingOffset.y += Prim2DBase._icPos.y;
  41961. this._contentArea.copyFrom(Prim2DBase._size);
  41962. }
  41963. }
  41964. else {
  41965. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  41966. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  41967. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  41968. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  41969. this._contentArea.copyFrom(Prim2DBase._icArea);
  41970. }
  41971. if (!this._position) {
  41972. var aPos = new BABYLON.Vector2(this._layoutAreaPos.x + this._marginOffset.x, this._layoutAreaPos.y + this._marginOffset.y);
  41973. this.actualPosition = aPos;
  41974. }
  41975. if (isSizeAuto) {
  41976. this._lastAutoSizeArea = this.size;
  41977. }
  41978. };
  41979. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  41980. /**
  41981. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  41982. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  41983. */
  41984. get: function () {
  41985. // Check for positioning update
  41986. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  41987. this._updatePositioning();
  41988. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41989. }
  41990. return this._contentArea;
  41991. },
  41992. enumerable: true,
  41993. configurable: true
  41994. });
  41995. Prim2DBase.prototype._patchHierarchy = function (owner) {
  41996. this._owner = owner;
  41997. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  41998. if (this._renderGroup != null) {
  41999. return;
  42000. }
  42001. if (this instanceof BABYLON.Group2D) {
  42002. var group = this;
  42003. group.detectGroupStates();
  42004. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  42005. group.owner._registerTrackedNode(this);
  42006. }
  42007. }
  42008. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  42009. if (this._parent) {
  42010. this._parentLayoutDirty();
  42011. }
  42012. // Make sure the prim is in the dirtyList if it should be
  42013. if (this._renderGroup && this.isDirty) {
  42014. var list = this._renderGroup._renderableData._primDirtyList;
  42015. var i = list.indexOf(this);
  42016. if (i === -1) {
  42017. list.push(this);
  42018. }
  42019. }
  42020. // Recurse
  42021. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42022. var child = _a[_i];
  42023. child._hierarchyDepth = this._hierarchyDepth + 1;
  42024. child._patchHierarchy(owner);
  42025. }
  42026. };
  42027. Prim2DBase.prototype._updateZOrder = function () {
  42028. var prevLinPos = this._primLinearPosition;
  42029. var startI = 0;
  42030. var startZ = this._zOrder;
  42031. // 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
  42032. var childrenCount = this._children.length;
  42033. if (this._firstZDirtyIndex > 0) {
  42034. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  42035. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  42036. prevLinPos = prevPrim._primLinearPosition;
  42037. startI = this._firstZDirtyIndex - 1;
  42038. startZ = prevPrim._zOrder;
  42039. }
  42040. }
  42041. var startPos = prevLinPos;
  42042. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  42043. Prim2DBase._totalCount = 0;
  42044. for (var i = startI; i < childrenCount; i++) {
  42045. var child = this._children[i];
  42046. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  42047. }
  42048. // Compute the new Z-Order for all the primitives
  42049. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  42050. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  42051. // 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.
  42052. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  42053. // 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...
  42054. if (Prim2DBase._zRebuildReentrency) {
  42055. var p = this._parent;
  42056. if (p == null) {
  42057. // 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...)
  42058. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  42059. Prim2DBase._zRebuildReentrency = false;
  42060. return;
  42061. }
  42062. p._firstZDirtyIndex = 0;
  42063. return p._updateZOrder();
  42064. }
  42065. Prim2DBase._zRebuildReentrency = true;
  42066. this._firstZDirtyIndex = 0;
  42067. this._updateZOrder();
  42068. Prim2DBase._zRebuildReentrency = false;
  42069. }
  42070. for (var i = startI; i < childrenCount; i++) {
  42071. var child = this._children[i];
  42072. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  42073. }
  42074. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  42075. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  42076. var p = _a[_i];
  42077. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  42078. }
  42079. Prim2DBase._zOrderChangedNotifList.splice(0);
  42080. this._firstZDirtyIndex = Prim2DBase._bigInt;
  42081. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  42082. };
  42083. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  42084. if (this.isManualZOrder) {
  42085. return prevLinPos;
  42086. }
  42087. this._primLinearPosition = ++prevLinPos;
  42088. Prim2DBase._totalCount++;
  42089. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  42090. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  42091. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42092. var child = _a[_i];
  42093. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  42094. }
  42095. }
  42096. return prevLinPos;
  42097. };
  42098. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  42099. if (this.isManualZOrder) {
  42100. return null;
  42101. }
  42102. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  42103. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  42104. this._setZOrder(newZ, false);
  42105. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  42106. this._firstZDirtyIndex = Prim2DBase._bigInt;
  42107. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  42108. }
  42109. var curZ = newZ;
  42110. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  42111. if (isFlat) {
  42112. if (this._children.length > 0) {
  42113. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  42114. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42115. var child = _a[_i];
  42116. child._updatePrimitiveFlatZOrder(this._zOrder);
  42117. }
  42118. }
  42119. }
  42120. else {
  42121. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  42122. var child = _c[_b];
  42123. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  42124. if (r != null) {
  42125. curZ = r;
  42126. }
  42127. }
  42128. }
  42129. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  42130. return curZ;
  42131. };
  42132. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  42133. if (this.isManualZOrder) {
  42134. return;
  42135. }
  42136. this._setZOrder(newZ, false);
  42137. this._zMax = newZ;
  42138. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  42139. this._firstZDirtyIndex = Prim2DBase._bigInt;
  42140. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  42141. }
  42142. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42143. var child = _a[_i];
  42144. child._updatePrimitiveFlatZOrder(newZ);
  42145. }
  42146. };
  42147. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  42148. if (newZ !== this._zOrder) {
  42149. this._zOrder = newZ;
  42150. this.onPrimBecomesDirty();
  42151. this.onZOrderChanged();
  42152. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  42153. if (directEmit) {
  42154. this._actualZOrderChangedObservable.notifyObservers(newZ);
  42155. }
  42156. else {
  42157. Prim2DBase._zOrderChangedNotifList.push(this);
  42158. }
  42159. }
  42160. }
  42161. };
  42162. Prim2DBase.prototype._updateRenderMode = function () {
  42163. };
  42164. /**
  42165. * This method is used to alter the contentArea of the Primitive before margin is applied.
  42166. * 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.
  42167. * @param primSize the current size of the primitive
  42168. * @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!
  42169. * @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!
  42170. */
  42171. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  42172. initialContentArea.copyFrom(primSize);
  42173. initialContentPosition.x = initialContentPosition.y = 0;
  42174. };
  42175. /**
  42176. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  42177. * Check the Rectangle2D implementation for a concrete application.
  42178. * @param primSize the current size of the primitive
  42179. * @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!
  42180. */
  42181. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  42182. newPrimSize.copyFrom(primSize);
  42183. };
  42184. Prim2DBase.PRIM2DBASE_PROPCOUNT = 16;
  42185. Prim2DBase._bigInt = Math.pow(2, 30);
  42186. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  42187. Prim2DBase.boundinbBoxReentrency = false;
  42188. Prim2DBase.nullSize = BABYLON.Size.Zero();
  42189. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  42190. Prim2DBase._isCanvasInit = false;
  42191. Prim2DBase._t0 = new BABYLON.Matrix();
  42192. Prim2DBase._t1 = new BABYLON.Matrix();
  42193. Prim2DBase._t2 = new BABYLON.Matrix();
  42194. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  42195. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  42196. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  42197. Prim2DBase._icArea = BABYLON.Size.Zero();
  42198. Prim2DBase._size = BABYLON.Size.Zero();
  42199. Prim2DBase._zOrderChangedNotifList = new Array();
  42200. Prim2DBase._zRebuildReentrency = false;
  42201. Prim2DBase._totalCount = 0;
  42202. __decorate([
  42203. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  42204. ], Prim2DBase.prototype, "actualPosition", null);
  42205. __decorate([
  42206. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  42207. ], Prim2DBase.prototype, "position", null);
  42208. __decorate([
  42209. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  42210. ], Prim2DBase.prototype, "size", null);
  42211. __decorate([
  42212. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  42213. ], Prim2DBase.prototype, "rotation", null);
  42214. __decorate([
  42215. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  42216. ], Prim2DBase.prototype, "scale", null);
  42217. __decorate([
  42218. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  42219. ], Prim2DBase.prototype, "origin", null);
  42220. __decorate([
  42221. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  42222. ], Prim2DBase.prototype, "levelVisible", null);
  42223. __decorate([
  42224. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  42225. ], Prim2DBase.prototype, "isVisible", null);
  42226. __decorate([
  42227. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  42228. ], Prim2DBase.prototype, "zOrder", null);
  42229. __decorate([
  42230. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  42231. ], Prim2DBase.prototype, "margin", null);
  42232. __decorate([
  42233. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  42234. ], Prim2DBase.prototype, "padding", null);
  42235. __decorate([
  42236. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  42237. ], Prim2DBase.prototype, "marginAlignment", null);
  42238. __decorate([
  42239. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  42240. ], Prim2DBase.prototype, "opacity", null);
  42241. __decorate([
  42242. BABYLON.instanceLevelProperty(14, function (pi) { return Prim2DBase.scaleXProperty = pi; }, false, true)
  42243. ], Prim2DBase.prototype, "scaleX", null);
  42244. __decorate([
  42245. BABYLON.instanceLevelProperty(15, function (pi) { return Prim2DBase.scaleYProperty = pi; }, false, true)
  42246. ], Prim2DBase.prototype, "scaleY", null);
  42247. Prim2DBase = __decorate([
  42248. BABYLON.className("Prim2DBase")
  42249. ], Prim2DBase);
  42250. return Prim2DBase;
  42251. })(BABYLON.SmartPropertyPrim);
  42252. BABYLON.Prim2DBase = Prim2DBase;
  42253. })(BABYLON || (BABYLON = {}));
  42254. var BABYLON;
  42255. (function (BABYLON) {
  42256. var GroupInstanceInfo = (function () {
  42257. function GroupInstanceInfo(owner, mrc, partCount) {
  42258. this._partCount = partCount;
  42259. this.owner = owner;
  42260. this.modelRenderCache = mrc;
  42261. this.modelRenderCache.addRef();
  42262. this.partIndexFromId = new BABYLON.StringDictionary();
  42263. this._usedShaderCategories = new Array(partCount);
  42264. this._strides = new Array(partCount);
  42265. this._opaqueData = null;
  42266. this._alphaTestData = null;
  42267. this._transparentData = null;
  42268. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  42269. }
  42270. GroupInstanceInfo.prototype.dispose = function () {
  42271. if (this._isDisposed) {
  42272. return false;
  42273. }
  42274. if (this.modelRenderCache) {
  42275. this.modelRenderCache.dispose();
  42276. this.modelRenderCache = null;
  42277. }
  42278. var engine = this.owner.owner.engine;
  42279. if (this._opaqueData) {
  42280. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  42281. this._opaqueData = null;
  42282. }
  42283. if (this._alphaTestData) {
  42284. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  42285. this._alphaTestData = null;
  42286. }
  42287. if (this._transparentData) {
  42288. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  42289. this._transparentData = null;
  42290. }
  42291. this.partIndexFromId = null;
  42292. this._isDisposed = true;
  42293. return true;
  42294. };
  42295. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  42296. get: function () {
  42297. return this._opaqueData != null;
  42298. },
  42299. enumerable: true,
  42300. configurable: true
  42301. });
  42302. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  42303. get: function () {
  42304. return this._alphaTestData != null;
  42305. },
  42306. enumerable: true,
  42307. configurable: true
  42308. });
  42309. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  42310. get: function () {
  42311. return this._transparentData != null;
  42312. },
  42313. enumerable: true,
  42314. configurable: true
  42315. });
  42316. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  42317. get: function () {
  42318. if (!this._opaqueData) {
  42319. this._opaqueData = new Array(this._partCount);
  42320. for (var i = 0; i < this._partCount; i++) {
  42321. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  42322. }
  42323. }
  42324. return this._opaqueData;
  42325. },
  42326. enumerable: true,
  42327. configurable: true
  42328. });
  42329. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  42330. get: function () {
  42331. if (!this._alphaTestData) {
  42332. this._alphaTestData = new Array(this._partCount);
  42333. for (var i = 0; i < this._partCount; i++) {
  42334. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  42335. }
  42336. }
  42337. return this._alphaTestData;
  42338. },
  42339. enumerable: true,
  42340. configurable: true
  42341. });
  42342. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  42343. get: function () {
  42344. if (!this._transparentData) {
  42345. this._transparentData = new Array(this._partCount);
  42346. for (var i = 0; i < this._partCount; i++) {
  42347. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  42348. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  42349. }
  42350. }
  42351. return this._transparentData;
  42352. },
  42353. enumerable: true,
  42354. configurable: true
  42355. });
  42356. GroupInstanceInfo.prototype.sortTransparentData = function () {
  42357. if (!this.transparentOrderDirty) {
  42358. return;
  42359. }
  42360. for (var i = 0; i < this._transparentData.length; i++) {
  42361. var td = this._transparentData[i];
  42362. td._partData.sort();
  42363. }
  42364. this.transparentOrderDirty = false;
  42365. };
  42366. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  42367. get: function () {
  42368. return this._usedShaderCategories;
  42369. },
  42370. enumerable: true,
  42371. configurable: true
  42372. });
  42373. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  42374. get: function () {
  42375. return this._strides;
  42376. },
  42377. enumerable: true,
  42378. configurable: true
  42379. });
  42380. return GroupInstanceInfo;
  42381. })();
  42382. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  42383. var TransparentSegment = (function () {
  42384. function TransparentSegment() {
  42385. this.groupInsanceInfo = null;
  42386. this.startZ = 0;
  42387. this.endZ = 0;
  42388. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  42389. this.endDataIndex = 0;
  42390. this.partBuffers = null;
  42391. }
  42392. TransparentSegment.prototype.dispose = function (engine) {
  42393. if (this.partBuffers) {
  42394. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  42395. this.partBuffers.splice(0);
  42396. this.partBuffers = null;
  42397. }
  42398. };
  42399. return TransparentSegment;
  42400. })();
  42401. BABYLON.TransparentSegment = TransparentSegment;
  42402. var GroupInfoPartData = (function () {
  42403. function GroupInfoPartData(stride) {
  42404. this._partData = null;
  42405. this._partBuffer = null;
  42406. this._partBufferSize = 0;
  42407. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  42408. this._isDisposed = false;
  42409. }
  42410. GroupInfoPartData.prototype.dispose = function (engine) {
  42411. if (this._isDisposed) {
  42412. return false;
  42413. }
  42414. if (this._partBuffer) {
  42415. engine._releaseBuffer(this._partBuffer);
  42416. this._partBuffer = null;
  42417. }
  42418. this._partData = null;
  42419. this._isDisposed = true;
  42420. };
  42421. return GroupInfoPartData;
  42422. })();
  42423. BABYLON.GroupInfoPartData = GroupInfoPartData;
  42424. var TransparentGroupInfoPartData = (function (_super) {
  42425. __extends(TransparentGroupInfoPartData, _super);
  42426. function TransparentGroupInfoPartData(stride, zoff) {
  42427. _super.call(this, stride);
  42428. this._partData.compareValueOffset = zoff;
  42429. this._partData.sortingAscending = false;
  42430. }
  42431. return TransparentGroupInfoPartData;
  42432. })(GroupInfoPartData);
  42433. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  42434. var ModelRenderCache = (function () {
  42435. function ModelRenderCache(engine, modelKey) {
  42436. this._engine = engine;
  42437. this._modelKey = modelKey;
  42438. this._nextKey = 1;
  42439. this._refCounter = 1;
  42440. this._partData = null;
  42441. }
  42442. ModelRenderCache.prototype.dispose = function () {
  42443. if (--this._refCounter !== 0) {
  42444. return false;
  42445. }
  42446. // Remove the Model Render Cache from the global dictionary
  42447. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  42448. if (edata) {
  42449. edata.DisposeModelRenderCache(this);
  42450. }
  42451. return true;
  42452. };
  42453. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  42454. get: function () {
  42455. return this._refCounter <= 0;
  42456. },
  42457. enumerable: true,
  42458. configurable: true
  42459. });
  42460. ModelRenderCache.prototype.addRef = function () {
  42461. return ++this._refCounter;
  42462. };
  42463. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  42464. get: function () {
  42465. return this._modelKey;
  42466. },
  42467. enumerable: true,
  42468. configurable: true
  42469. });
  42470. /**
  42471. * Render the model instances
  42472. * @param instanceInfo
  42473. * @param context
  42474. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  42475. */
  42476. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  42477. return true;
  42478. };
  42479. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  42480. for (var i = 0; i < this._partData.length; i++) {
  42481. if (this._partData[i]._partId === partId) {
  42482. return i;
  42483. }
  42484. }
  42485. return null;
  42486. };
  42487. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  42488. var i = this.getPartIndexFromId(partId);
  42489. if (i === null) {
  42490. return null;
  42491. }
  42492. var ci = this._partsClassInfo[i];
  42493. var categories = this._partData[i]._partUsedCategories;
  42494. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  42495. return res;
  42496. };
  42497. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  42498. var pd = this._partData[partIndex];
  42499. var offset = (pd._partDataStride / 4) * elementCount;
  42500. var pci = this._partsClassInfo[partIndex];
  42501. var self = this;
  42502. pci.fullContent.forEach(function (k, v) {
  42503. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  42504. switch (v.dataType) {
  42505. case 4 /* float */:
  42506. {
  42507. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42508. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  42509. break;
  42510. }
  42511. case 0 /* Vector2 */:
  42512. {
  42513. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42514. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  42515. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  42516. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  42517. break;
  42518. }
  42519. case 5 /* Color3 */:
  42520. case 1 /* Vector3 */:
  42521. {
  42522. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42523. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  42524. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  42525. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  42526. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  42527. break;
  42528. }
  42529. case 6 /* Color4 */:
  42530. case 2 /* Vector4 */:
  42531. {
  42532. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42533. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  42534. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  42535. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  42536. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  42537. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  42538. break;
  42539. }
  42540. default:
  42541. }
  42542. }
  42543. });
  42544. };
  42545. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  42546. // let i = this.getPartIndexFromId(partId);
  42547. // if (i === null) {
  42548. // return null;
  42549. // }
  42550. // let pci = this._partsClassInfo[i];
  42551. // pci.fullContent.forEach((k, v) => {
  42552. // if (uniforms.indexOf(v.attributeName) !== -1) {
  42553. // v.uniformLocation = effect.getUniform(v.attributeName);
  42554. // }
  42555. // });
  42556. //}
  42557. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  42558. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  42559. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  42560. return ModelRenderCache;
  42561. })();
  42562. BABYLON.ModelRenderCache = ModelRenderCache;
  42563. var ModelRenderCachePartData = (function () {
  42564. function ModelRenderCachePartData() {
  42565. }
  42566. return ModelRenderCachePartData;
  42567. })();
  42568. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  42569. })(BABYLON || (BABYLON = {}));
  42570. var BABYLON;
  42571. (function (BABYLON) {
  42572. var InstanceClassInfo = (function () {
  42573. function InstanceClassInfo(base) {
  42574. this._baseInfo = base;
  42575. this._nextOffset = new BABYLON.StringDictionary();
  42576. this._attributes = new Array();
  42577. }
  42578. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  42579. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  42580. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  42581. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  42582. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  42583. if (push) {
  42584. this._attributes.push(propInfo);
  42585. }
  42586. };
  42587. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  42588. var catInline = ";" + categories.join(";") + ";";
  42589. var res = new Array();
  42590. var curInfo = this;
  42591. while (curInfo) {
  42592. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  42593. var attrib = _a[_i];
  42594. // 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
  42595. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  42596. var index = effect.getAttributeLocationByName(attrib.attributeName);
  42597. var iai = new BABYLON.InstancingAttributeInfo();
  42598. iai.index = index;
  42599. 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)
  42600. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  42601. iai.attributeName = attrib.attributeName;
  42602. res.push(iai);
  42603. }
  42604. }
  42605. curInfo = curInfo._baseInfo;
  42606. }
  42607. return res;
  42608. };
  42609. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  42610. var res = new Array();
  42611. var curInfo = this;
  42612. while (curInfo) {
  42613. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  42614. var attrib = _a[_i];
  42615. // 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
  42616. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  42617. res.push(attrib.attributeName);
  42618. }
  42619. }
  42620. curInfo = curInfo._baseInfo;
  42621. }
  42622. return res;
  42623. };
  42624. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  42625. var curOffset = 0;
  42626. var curBase = this._baseInfo;
  42627. while (curBase) {
  42628. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  42629. curBase = curBase._baseInfo;
  42630. }
  42631. return curOffset;
  42632. };
  42633. return InstanceClassInfo;
  42634. })();
  42635. BABYLON.InstanceClassInfo = InstanceClassInfo;
  42636. var InstancePropInfo = (function () {
  42637. function InstancePropInfo() {
  42638. this.instanceOffset = new BABYLON.StringDictionary();
  42639. }
  42640. InstancePropInfo.prototype.setSize = function (val) {
  42641. if (val instanceof BABYLON.Vector2) {
  42642. this.size = 8;
  42643. this.dataType = 0 /* Vector2 */;
  42644. return;
  42645. }
  42646. if (val instanceof BABYLON.Vector3) {
  42647. this.size = 12;
  42648. this.dataType = 1 /* Vector3 */;
  42649. return;
  42650. }
  42651. if (val instanceof BABYLON.Vector4) {
  42652. this.size = 16;
  42653. this.dataType = 2 /* Vector4 */;
  42654. return;
  42655. }
  42656. if (val instanceof BABYLON.Matrix) {
  42657. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  42658. }
  42659. if (typeof (val) === "number") {
  42660. this.size = 4;
  42661. this.dataType = 4 /* float */;
  42662. return;
  42663. }
  42664. if (val instanceof BABYLON.Color3) {
  42665. this.size = 12;
  42666. this.dataType = 5 /* Color3 */;
  42667. return;
  42668. }
  42669. if (val instanceof BABYLON.Color4) {
  42670. this.size = 16;
  42671. this.dataType = 6 /* Color4 */;
  42672. return;
  42673. }
  42674. if (val instanceof BABYLON.Size) {
  42675. this.size = 8;
  42676. this.dataType = 7 /* Size */;
  42677. return;
  42678. }
  42679. return;
  42680. };
  42681. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  42682. switch (this.dataType) {
  42683. case 0 /* Vector2 */:
  42684. {
  42685. var v = val;
  42686. array[offset + 0] = v.x;
  42687. array[offset + 1] = v.y;
  42688. break;
  42689. }
  42690. case 1 /* Vector3 */:
  42691. {
  42692. var v = val;
  42693. array[offset + 0] = v.x;
  42694. array[offset + 1] = v.y;
  42695. array[offset + 2] = v.z;
  42696. break;
  42697. }
  42698. case 2 /* Vector4 */:
  42699. {
  42700. var v = val;
  42701. array[offset + 0] = v.x;
  42702. array[offset + 1] = v.y;
  42703. array[offset + 2] = v.z;
  42704. array[offset + 3] = v.w;
  42705. break;
  42706. }
  42707. case 5 /* Color3 */:
  42708. {
  42709. var v = val;
  42710. array[offset + 0] = v.r;
  42711. array[offset + 1] = v.g;
  42712. array[offset + 2] = v.b;
  42713. break;
  42714. }
  42715. case 6 /* Color4 */:
  42716. {
  42717. var v = val;
  42718. array[offset + 0] = v.r;
  42719. array[offset + 1] = v.g;
  42720. array[offset + 2] = v.b;
  42721. array[offset + 3] = v.a;
  42722. break;
  42723. }
  42724. case 4 /* float */:
  42725. {
  42726. var v = val;
  42727. array[offset] = v;
  42728. break;
  42729. }
  42730. case 3 /* Matrix */:
  42731. {
  42732. var v = val;
  42733. for (var i = 0; i < 16; i++) {
  42734. array[offset + i] = v.m[i];
  42735. }
  42736. break;
  42737. }
  42738. case 7 /* Size */:
  42739. {
  42740. var s = val;
  42741. array[offset + 0] = s.width;
  42742. array[offset + 1] = s.height;
  42743. break;
  42744. }
  42745. }
  42746. };
  42747. return InstancePropInfo;
  42748. })();
  42749. BABYLON.InstancePropInfo = InstancePropInfo;
  42750. function instanceData(category, shaderAttributeName) {
  42751. return function (target, propName, descriptor) {
  42752. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  42753. var node = dic.getLevelOf(target);
  42754. var instanceDataName = propName;
  42755. shaderAttributeName = shaderAttributeName || instanceDataName;
  42756. var info = node.levelContent.get(instanceDataName);
  42757. if (info) {
  42758. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  42759. }
  42760. info = new InstancePropInfo();
  42761. info.attributeName = shaderAttributeName;
  42762. info.category = category || null;
  42763. if (info.category) {
  42764. info.delimitedCategory = ";" + info.category + ";";
  42765. }
  42766. node.levelContent.add(instanceDataName, info);
  42767. descriptor.get = function () {
  42768. return null;
  42769. };
  42770. descriptor.set = function (val) {
  42771. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  42772. // Quit if it's the case, otherwise we could overwrite data somewhere...
  42773. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  42774. return;
  42775. }
  42776. if (!info.size) {
  42777. info.setSize(val);
  42778. node.classContent.mapProperty(info, true);
  42779. }
  42780. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  42781. node.classContent.mapProperty(info, false);
  42782. }
  42783. var obj = this;
  42784. if (obj.dataBuffer && obj.dataElements) {
  42785. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  42786. info.writeData(obj.dataBuffer.buffer, offset, val);
  42787. }
  42788. };
  42789. };
  42790. }
  42791. BABYLON.instanceData = instanceData;
  42792. var InstanceDataBase = (function () {
  42793. function InstanceDataBase(partId, dataElementCount) {
  42794. this.id = partId;
  42795. this.curElement = 0;
  42796. this._dataElementCount = dataElementCount;
  42797. this.renderMode = 0;
  42798. this.arrayLengthChanged = false;
  42799. }
  42800. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  42801. get: function () {
  42802. return null;
  42803. },
  42804. enumerable: true,
  42805. configurable: true
  42806. });
  42807. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  42808. get: function () {
  42809. return null;
  42810. },
  42811. enumerable: true,
  42812. configurable: true
  42813. });
  42814. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  42815. get: function () {
  42816. return null;
  42817. },
  42818. enumerable: true,
  42819. configurable: true
  42820. });
  42821. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  42822. get: function () {
  42823. return null;
  42824. },
  42825. enumerable: true,
  42826. configurable: true
  42827. });
  42828. InstanceDataBase.prototype.getClassTreeInfo = function () {
  42829. if (!this.typeInfo) {
  42830. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  42831. }
  42832. return this.typeInfo;
  42833. };
  42834. InstanceDataBase.prototype.allocElements = function () {
  42835. if (!this.dataBuffer || this.dataElements) {
  42836. return;
  42837. }
  42838. var res = new Array(this.dataElementCount);
  42839. for (var i = 0; i < this.dataElementCount; i++) {
  42840. res[i] = this.dataBuffer.allocElement();
  42841. }
  42842. this.dataElements = res;
  42843. };
  42844. InstanceDataBase.prototype.freeElements = function () {
  42845. if (!this.dataElements) {
  42846. return;
  42847. }
  42848. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  42849. var ei = _a[_i];
  42850. this.dataBuffer.freeElement(ei);
  42851. }
  42852. this.dataElements = null;
  42853. };
  42854. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  42855. get: function () {
  42856. return this._dataElementCount;
  42857. },
  42858. set: function (value) {
  42859. if (value === this._dataElementCount) {
  42860. return;
  42861. }
  42862. this.arrayLengthChanged = true;
  42863. this.freeElements();
  42864. this._dataElementCount = value;
  42865. this.allocElements();
  42866. },
  42867. enumerable: true,
  42868. configurable: true
  42869. });
  42870. __decorate([
  42871. instanceData()
  42872. ], InstanceDataBase.prototype, "zBias", null);
  42873. __decorate([
  42874. instanceData()
  42875. ], InstanceDataBase.prototype, "transformX", null);
  42876. __decorate([
  42877. instanceData()
  42878. ], InstanceDataBase.prototype, "transformY", null);
  42879. __decorate([
  42880. instanceData()
  42881. ], InstanceDataBase.prototype, "opacity", null);
  42882. return InstanceDataBase;
  42883. })();
  42884. BABYLON.InstanceDataBase = InstanceDataBase;
  42885. var RenderablePrim2D = (function (_super) {
  42886. __extends(RenderablePrim2D, _super);
  42887. function RenderablePrim2D(settings) {
  42888. _super.call(this, settings);
  42889. this._transparentPrimitiveInfo = null;
  42890. }
  42891. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  42892. get: function () {
  42893. return this._useTextureAlpha() || this._isPrimAlphaTest();
  42894. },
  42895. enumerable: true,
  42896. configurable: true
  42897. });
  42898. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  42899. get: function () {
  42900. return (this.actualOpacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  42901. },
  42902. enumerable: true,
  42903. configurable: true
  42904. });
  42905. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  42906. get: function () {
  42907. return this._renderMode;
  42908. },
  42909. enumerable: true,
  42910. configurable: true
  42911. });
  42912. /**
  42913. * Dispose the primitive and its resources, remove it from its parent
  42914. */
  42915. RenderablePrim2D.prototype.dispose = function () {
  42916. if (!_super.prototype.dispose.call(this)) {
  42917. return false;
  42918. }
  42919. if (this.renderGroup) {
  42920. this.renderGroup._setCacheGroupDirty();
  42921. }
  42922. if (this._transparentPrimitiveInfo) {
  42923. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  42924. this._transparentPrimitiveInfo = null;
  42925. }
  42926. if (this._instanceDataParts) {
  42927. this._cleanupInstanceDataParts();
  42928. }
  42929. if (this._modelRenderCache) {
  42930. this._modelRenderCache.dispose();
  42931. this._modelRenderCache = null;
  42932. }
  42933. if (this._instanceDataParts) {
  42934. this._instanceDataParts.forEach(function (p) {
  42935. p.freeElements();
  42936. });
  42937. this._instanceDataParts = null;
  42938. }
  42939. return true;
  42940. };
  42941. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  42942. var gii = null;
  42943. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42944. var part = _a[_i];
  42945. part.freeElements();
  42946. gii = part.groupInstanceInfo;
  42947. }
  42948. if (gii) {
  42949. var usedCount = 0;
  42950. if (gii.hasOpaqueData) {
  42951. var od = gii.opaqueData[0];
  42952. usedCount += od._partData.usedElementCount;
  42953. gii.opaqueDirty = true;
  42954. }
  42955. if (gii.hasAlphaTestData) {
  42956. var atd = gii.alphaTestData[0];
  42957. usedCount += atd._partData.usedElementCount;
  42958. gii.alphaTestDirty = true;
  42959. }
  42960. if (gii.hasTransparentData) {
  42961. var td = gii.transparentData[0];
  42962. usedCount += td._partData.usedElementCount;
  42963. gii.transparentDirty = true;
  42964. }
  42965. if (usedCount === 0 && gii.modelRenderCache != null) {
  42966. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  42967. gii.dispose();
  42968. }
  42969. if (this._modelRenderCache) {
  42970. this._modelRenderCache.dispose();
  42971. this._modelRenderCache = null;
  42972. }
  42973. }
  42974. this._instanceDataParts = null;
  42975. };
  42976. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  42977. _super.prototype._prepareRenderPre.call(this, context);
  42978. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  42979. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  42980. this._cleanupInstanceDataParts();
  42981. }
  42982. // Need to create the model?
  42983. var setupModelRenderCache = false;
  42984. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  42985. setupModelRenderCache = this._createModelRenderCache();
  42986. }
  42987. var gii = null;
  42988. var newInstance = false;
  42989. // Need to create the instance data parts?
  42990. if (!this._instanceDataParts) {
  42991. // Yes, flag it for later, more processing will have to be done
  42992. newInstance = true;
  42993. gii = this._createModelDataParts();
  42994. }
  42995. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  42996. if (setupModelRenderCache) {
  42997. this.setupModelRenderCache(this._modelRenderCache);
  42998. }
  42999. // 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.
  43000. // 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.
  43001. if (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  43002. this._updateInstanceDataParts(gii);
  43003. }
  43004. };
  43005. RenderablePrim2D.prototype._createModelRenderCache = function () {
  43006. var _this = this;
  43007. var setupModelRenderCache = false;
  43008. if (this._modelRenderCache) {
  43009. this._modelRenderCache.dispose();
  43010. }
  43011. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  43012. var mrc = _this.createModelRenderCache(key);
  43013. setupModelRenderCache = true;
  43014. return mrc;
  43015. });
  43016. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  43017. // if this is still false it means the MRC already exists, so we add a reference to it
  43018. if (!setupModelRenderCache) {
  43019. this._modelRenderCache.addRef();
  43020. }
  43021. return setupModelRenderCache;
  43022. };
  43023. RenderablePrim2D.prototype._createModelDataParts = function () {
  43024. var _this = this;
  43025. // Create the instance data parts of the primitive and store them
  43026. var parts = this.createInstanceDataParts();
  43027. this._instanceDataParts = parts;
  43028. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  43029. if (!this._modelRenderCache._partData) {
  43030. this._setupModelRenderCache(parts);
  43031. }
  43032. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  43033. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  43034. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  43035. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  43036. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  43037. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  43038. var part = _this._instanceDataParts[j];
  43039. res.partIndexFromId.add(part.id.toString(), j);
  43040. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  43041. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  43042. }
  43043. return res;
  43044. });
  43045. // Get the GroupInfoDataPart corresponding to the render category of the part
  43046. var rm = 0;
  43047. var gipd = null;
  43048. if (this.isTransparent) {
  43049. gipd = gii.transparentData;
  43050. rm = BABYLON.Render2DContext.RenderModeTransparent;
  43051. }
  43052. else if (this.isAlphaTest) {
  43053. gipd = gii.alphaTestData;
  43054. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  43055. }
  43056. else {
  43057. gipd = gii.opaqueData;
  43058. rm = BABYLON.Render2DContext.RenderModeOpaque;
  43059. }
  43060. // For each instance data part of the primitive, allocate the instanced element it needs for render
  43061. for (var i = 0; i < parts.length; i++) {
  43062. var part = parts[i];
  43063. part.dataBuffer = gipd[i]._partData;
  43064. part.allocElements();
  43065. part.renderMode = rm;
  43066. part.groupInstanceInfo = gii;
  43067. }
  43068. return gii;
  43069. };
  43070. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  43071. var ctiArray = new Array();
  43072. this._modelRenderCache._partData = new Array();
  43073. for (var _i = 0; _i < parts.length; _i++) {
  43074. var dataPart = parts[_i];
  43075. var pd = new BABYLON.ModelRenderCachePartData();
  43076. this._modelRenderCache._partData.push(pd);
  43077. var cat = this.getUsedShaderCategories(dataPart);
  43078. var cti = dataPart.getClassTreeInfo();
  43079. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  43080. var curVisible = this.isVisible;
  43081. this.isVisible = true;
  43082. // 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.
  43083. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  43084. var joinCat = ";" + cat.join(";") + ";";
  43085. pd._partJoinedUsedCategories = joinCat;
  43086. InstanceClassInfo._CurCategories = joinCat;
  43087. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  43088. if (!this.refreshInstanceDataPart(dataPart)) {
  43089. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  43090. }
  43091. this.afterRefreshForLayoutConstruction(dataPart, obj);
  43092. this.isVisible = curVisible;
  43093. var size = 0;
  43094. cti.fullContent.forEach(function (k, v) {
  43095. if (!v.category || cat.indexOf(v.category) !== -1) {
  43096. if (v.attributeName === "zBias") {
  43097. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  43098. }
  43099. if (!v.size) {
  43100. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  43101. }
  43102. else {
  43103. size += v.size;
  43104. }
  43105. }
  43106. });
  43107. pd._partDataStride = size;
  43108. pd._partUsedCategories = cat;
  43109. pd._partId = dataPart.id;
  43110. ctiArray.push(cti);
  43111. }
  43112. this._modelRenderCache._partsClassInfo = ctiArray;
  43113. };
  43114. RenderablePrim2D.prototype.onZOrderChanged = function () {
  43115. if (this.isTransparent && this._transparentPrimitiveInfo) {
  43116. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  43117. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  43118. // Flag the transparentData dirty has will have to sort it again
  43119. gii.transparentOrderDirty = true;
  43120. }
  43121. };
  43122. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  43123. return false;
  43124. };
  43125. RenderablePrim2D.prototype._useTextureAlpha = function () {
  43126. return false;
  43127. };
  43128. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  43129. return false;
  43130. };
  43131. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  43132. return false;
  43133. };
  43134. RenderablePrim2D.prototype._isPrimTransparent = function () {
  43135. return false;
  43136. };
  43137. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  43138. // Fetch the GroupInstanceInfo if we don't already have it
  43139. var rd = this.renderGroup._renderableData;
  43140. if (!gii) {
  43141. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  43142. }
  43143. var isTransparent = this.isTransparent;
  43144. var isAlphaTest = this.isAlphaTest;
  43145. var wereTransparent = false;
  43146. // Check a render mode change
  43147. var rmChanged = false;
  43148. if (this._instanceDataParts.length > 0) {
  43149. var firstPart = this._instanceDataParts[0];
  43150. var partRM = firstPart.renderMode;
  43151. var curRM = this.renderMode;
  43152. if (partRM !== curRM) {
  43153. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  43154. rmChanged = true;
  43155. var gipd;
  43156. switch (curRM) {
  43157. case BABYLON.Render2DContext.RenderModeTransparent:
  43158. gipd = gii.transparentData;
  43159. break;
  43160. case BABYLON.Render2DContext.RenderModeAlphaTest:
  43161. gipd = gii.alphaTestData;
  43162. break;
  43163. default:
  43164. gipd = gii.opaqueData;
  43165. }
  43166. for (var i = 0; i < this._instanceDataParts.length; i++) {
  43167. var part = this._instanceDataParts[i];
  43168. part.freeElements();
  43169. part.dataBuffer = gipd[i]._partData;
  43170. part.renderMode = curRM;
  43171. }
  43172. }
  43173. }
  43174. // Handle changes related to ZOffset
  43175. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  43176. if (isTransparent || wereTransparent) {
  43177. // Handle visibility change, which is also triggered when the primitive just got created
  43178. if (visChanged || rmChanged) {
  43179. if (this.isVisible && !wereTransparent) {
  43180. if (!this._transparentPrimitiveInfo) {
  43181. // Add the primitive to the list of transparent ones in the group that render is
  43182. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  43183. }
  43184. }
  43185. else {
  43186. if (this._transparentPrimitiveInfo) {
  43187. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  43188. this._transparentPrimitiveInfo = null;
  43189. }
  43190. }
  43191. gii.transparentOrderDirty = true;
  43192. }
  43193. }
  43194. var rebuildTrans = false;
  43195. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  43196. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  43197. var part = _a[_i];
  43198. var justAllocated = false;
  43199. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  43200. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  43201. part.allocElements();
  43202. justAllocated = true;
  43203. }
  43204. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  43205. // Will return false if the instance should not be rendered (not visible or other any reasons)
  43206. part.arrayLengthChanged = false;
  43207. if (!this.refreshInstanceDataPart(part)) {
  43208. // Free the data element
  43209. if (part.dataElements) {
  43210. part.freeElements();
  43211. }
  43212. // The refresh couldn't succeed, push the primitive to be dirty again for the next render
  43213. if (this.isVisible) {
  43214. rd._primNewDirtyList.push(this);
  43215. }
  43216. }
  43217. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  43218. }
  43219. this._instanceDirtyFlags = 0;
  43220. // Make the appropriate data dirty
  43221. if (isTransparent) {
  43222. gii.transparentDirty = true;
  43223. if (rebuildTrans) {
  43224. rd._transparentListChanged = true;
  43225. }
  43226. }
  43227. else if (isAlphaTest) {
  43228. gii.alphaTestDirty = true;
  43229. }
  43230. else {
  43231. gii.opaqueDirty = true;
  43232. }
  43233. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  43234. };
  43235. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  43236. var minOff = BABYLON.Prim2DBase._bigInt;
  43237. var maxOff = 0;
  43238. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  43239. var part = _a[_i];
  43240. if (part && part.dataElements) {
  43241. part.dataBuffer.pack();
  43242. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  43243. var el = _c[_b];
  43244. minOff = Math.min(minOff, el.offset);
  43245. maxOff = Math.max(maxOff, el.offset);
  43246. }
  43247. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  43248. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  43249. }
  43250. }
  43251. };
  43252. // This internal method is mainly used for transparency processing
  43253. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  43254. var length = this._instanceDataParts.length;
  43255. for (var i = 0; i < length; i++) {
  43256. var part = this._instanceDataParts[i];
  43257. if (part) {
  43258. var stride = part.dataBuffer.stride;
  43259. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  43260. // check if it's the last in the DFA
  43261. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  43262. return null;
  43263. }
  43264. // Return the Z of the next primitive that lies in the DFA
  43265. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  43266. }
  43267. }
  43268. return null;
  43269. };
  43270. // This internal method is mainly used for transparency processing
  43271. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  43272. var length = this._instanceDataParts.length;
  43273. for (var i = 0; i < length; i++) {
  43274. var part = this._instanceDataParts[i];
  43275. if (part) {
  43276. var stride = part.dataBuffer.stride;
  43277. var firstElementOffset = part.dataElements[0].offset;
  43278. // check if it's the first in the DFA
  43279. if (firstElementOffset === 0) {
  43280. return null;
  43281. }
  43282. // Return the Z of the previous primitive that lies in the DFA
  43283. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  43284. }
  43285. }
  43286. return null;
  43287. };
  43288. /**
  43289. * Transform a given point using the Primitive's origin setting.
  43290. * This method requires the Primitive's actualSize to be accurate
  43291. * @param p the point to transform
  43292. * @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.
  43293. * @param res an allocated Vector2 that will receive the transformed content
  43294. */
  43295. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  43296. var actualSize = this.actualSize;
  43297. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  43298. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  43299. };
  43300. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  43301. this.transformPointWithOriginByRef(p, originOffset, res);
  43302. return res;
  43303. };
  43304. /**
  43305. * Get the info for a given effect based on the dataPart metadata
  43306. * @param dataPartId partId in part list to get the info
  43307. * @param vertexBufferAttributes vertex buffer attributes to manually add
  43308. * @param uniforms uniforms to manually add
  43309. * @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
  43310. */
  43311. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  43312. if (uniforms === void 0) { uniforms = null; }
  43313. if (useInstanced === void 0) { useInstanced = null; }
  43314. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  43315. if (!dataPart) {
  43316. return null;
  43317. }
  43318. var instancedArray = this.owner.supportInstancedArray;
  43319. if (useInstanced != null) {
  43320. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  43321. if (useInstanced && instancedArray === false) {
  43322. return null;
  43323. }
  43324. // Use the caller's setting
  43325. instancedArray = useInstanced;
  43326. }
  43327. var cti = dataPart.getClassTreeInfo();
  43328. var categories = this.getUsedShaderCategories(dataPart);
  43329. var att = cti.classContent.getShaderAttributes(categories);
  43330. var defines = "";
  43331. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  43332. if (instancedArray) {
  43333. defines += "#define Instanced\n";
  43334. }
  43335. return {
  43336. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  43337. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  43338. defines: defines
  43339. };
  43340. };
  43341. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  43342. get: function () {
  43343. return this._modelRenderCache;
  43344. },
  43345. enumerable: true,
  43346. configurable: true
  43347. });
  43348. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  43349. return null;
  43350. };
  43351. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43352. };
  43353. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  43354. return null;
  43355. };
  43356. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  43357. return [];
  43358. };
  43359. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  43360. };
  43361. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  43362. };
  43363. RenderablePrim2D.prototype.applyActualScaleOnTransform = function () {
  43364. return true;
  43365. };
  43366. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  43367. if (!this.isVisible) {
  43368. return false;
  43369. }
  43370. part.isVisible = this.isVisible;
  43371. // 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)
  43372. if (part.dataElementCount === 1) {
  43373. part.curElement = 0;
  43374. this.updateInstanceDataPart(part);
  43375. }
  43376. return true;
  43377. };
  43378. /**
  43379. * Update the instanceDataBase level properties of a part
  43380. * @param part the part to update
  43381. * @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).
  43382. */
  43383. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  43384. if (positionOffset === void 0) { positionOffset = null; }
  43385. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform); // Compute the transformation into the renderGroup's space
  43386. var rgScale = this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? RenderablePrim2D._uV : this.renderGroup.actualScale; // We still need to apply the scale of the renderGroup to our rendering, so get it.
  43387. var size = this.renderGroup.viewportSize;
  43388. var zBias = this.actualZOffset;
  43389. var offX = 0;
  43390. var offY = 0;
  43391. // If there's an offset, apply the global transformation matrix on it to get a global offset
  43392. if (positionOffset) {
  43393. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  43394. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  43395. }
  43396. // 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
  43397. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  43398. // So for X:
  43399. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  43400. // - 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].
  43401. // At last we don't forget to apply the actualScale of the Render Group to tx[0] and ty[1] to propagate scaling correctly
  43402. var w = size.width;
  43403. var h = size.height;
  43404. var invZBias = 1 / zBias;
  43405. var tx = new BABYLON.Vector4(t.m[0] * rgScale.x * 2 / w, t.m[4] * 2 / w, 0 /*t.m[8]*/, ((t.m[12] + offX) * rgScale.x * 2 / w) - 1);
  43406. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * rgScale.y * 2 / h, 0 /*t.m[9]*/, ((t.m[13] + offY) * rgScale.y * 2 / h) - 1);
  43407. if (!this.applyActualScaleOnTransform()) {
  43408. var las = this.actualScale;
  43409. tx.x /= las.x;
  43410. ty.y /= las.y;
  43411. }
  43412. part.transformX = tx;
  43413. part.transformY = ty;
  43414. part.opacity = this.actualOpacity;
  43415. // 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)
  43416. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  43417. };
  43418. RenderablePrim2D.prototype._updateRenderMode = function () {
  43419. if (this.isTransparent) {
  43420. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  43421. }
  43422. else if (this.isAlphaTest) {
  43423. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  43424. }
  43425. else {
  43426. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  43427. }
  43428. };
  43429. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  43430. RenderablePrim2D._uV = new BABYLON.Vector2(1, 1);
  43431. __decorate([
  43432. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  43433. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  43434. __decorate([
  43435. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  43436. ], RenderablePrim2D.prototype, "isTransparent", null);
  43437. RenderablePrim2D = __decorate([
  43438. BABYLON.className("RenderablePrim2D")
  43439. ], RenderablePrim2D);
  43440. return RenderablePrim2D;
  43441. })(BABYLON.Prim2DBase);
  43442. BABYLON.RenderablePrim2D = RenderablePrim2D;
  43443. })(BABYLON || (BABYLON = {}));
  43444. var BABYLON;
  43445. (function (BABYLON) {
  43446. var Shape2D = (function (_super) {
  43447. __extends(Shape2D, _super);
  43448. function Shape2D(settings) {
  43449. _super.call(this, settings);
  43450. if (!settings) {
  43451. settings = {};
  43452. }
  43453. var borderBrush = null;
  43454. if (settings.border) {
  43455. if (typeof (settings.border) === "string") {
  43456. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  43457. }
  43458. else {
  43459. borderBrush = settings.border;
  43460. }
  43461. }
  43462. var fillBrush = null;
  43463. if (settings.fill) {
  43464. if (typeof (settings.fill) === "string") {
  43465. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  43466. }
  43467. else {
  43468. fillBrush = settings.fill;
  43469. }
  43470. }
  43471. this._isTransparent = false;
  43472. this._oldTransparent = false;
  43473. this.border = borderBrush;
  43474. this.fill = fillBrush;
  43475. this._updateTransparencyStatus();
  43476. this.borderThickness = settings.borderThickness;
  43477. }
  43478. Object.defineProperty(Shape2D.prototype, "border", {
  43479. get: function () {
  43480. return this._border;
  43481. },
  43482. set: function (value) {
  43483. this._border = value;
  43484. this._updateTransparencyStatus();
  43485. },
  43486. enumerable: true,
  43487. configurable: true
  43488. });
  43489. Object.defineProperty(Shape2D.prototype, "fill", {
  43490. /**
  43491. * Get/set the brush to render the Fill part of the Primitive
  43492. */
  43493. get: function () {
  43494. return this._fill;
  43495. },
  43496. set: function (value) {
  43497. this._fill = value;
  43498. this._updateTransparencyStatus();
  43499. },
  43500. enumerable: true,
  43501. configurable: true
  43502. });
  43503. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  43504. get: function () {
  43505. return this._borderThickness;
  43506. },
  43507. set: function (value) {
  43508. this._borderThickness = value;
  43509. },
  43510. enumerable: true,
  43511. configurable: true
  43512. });
  43513. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  43514. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  43515. // Fill Part
  43516. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  43517. var fill = this.fill;
  43518. if (fill instanceof BABYLON.SolidColorBrush2D) {
  43519. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  43520. }
  43521. if (fill instanceof BABYLON.GradientColorBrush2D) {
  43522. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  43523. }
  43524. }
  43525. // Border Part
  43526. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  43527. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  43528. var border = this.border;
  43529. if (border instanceof BABYLON.SolidColorBrush2D) {
  43530. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  43531. }
  43532. if (border instanceof BABYLON.GradientColorBrush2D) {
  43533. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  43534. }
  43535. }
  43536. return cat;
  43537. };
  43538. Shape2D.prototype.applyActualScaleOnTransform = function () {
  43539. return false;
  43540. };
  43541. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  43542. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43543. return false;
  43544. }
  43545. // Fill Part
  43546. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  43547. var d = part;
  43548. if (this.fill) {
  43549. var fill = this.fill;
  43550. if (fill instanceof BABYLON.SolidColorBrush2D) {
  43551. d.fillSolidColor = fill.color;
  43552. }
  43553. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  43554. d.fillGradientColor1 = fill.color1;
  43555. d.fillGradientColor2 = fill.color2;
  43556. 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));
  43557. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  43558. d.fillGradientTY = ty;
  43559. }
  43560. }
  43561. }
  43562. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  43563. var d = part;
  43564. if (this.border) {
  43565. d.borderThickness = this.borderThickness;
  43566. var border = this.border;
  43567. if (border instanceof BABYLON.SolidColorBrush2D) {
  43568. d.borderSolidColor = border.color;
  43569. }
  43570. else if (border instanceof BABYLON.GradientColorBrush2D) {
  43571. d.borderGradientColor1 = border.color1;
  43572. d.borderGradientColor2 = border.color2;
  43573. 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));
  43574. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  43575. d.borderGradientTY = ty;
  43576. }
  43577. }
  43578. }
  43579. return true;
  43580. };
  43581. Shape2D.prototype._updateTransparencyStatus = function () {
  43582. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  43583. if (this._isTransparent !== this._oldTransparent) {
  43584. this._oldTransparent = this._isTransparent;
  43585. this._updateRenderMode();
  43586. }
  43587. };
  43588. Shape2D.prototype._mustUpdateInstance = function () {
  43589. var res = this._oldTransparent !== this._isTransparent;
  43590. if (res) {
  43591. this._updateRenderMode();
  43592. this._oldTransparent = this._isTransparent;
  43593. }
  43594. return res;
  43595. };
  43596. Shape2D.prototype._isPrimTransparent = function () {
  43597. return this._isTransparent;
  43598. };
  43599. Shape2D.SHAPE2D_BORDERPARTID = 1;
  43600. Shape2D.SHAPE2D_FILLPARTID = 2;
  43601. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  43602. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  43603. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  43604. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  43605. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  43606. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  43607. __decorate([
  43608. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  43609. ], Shape2D.prototype, "border", null);
  43610. __decorate([
  43611. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  43612. ], Shape2D.prototype, "fill", null);
  43613. __decorate([
  43614. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  43615. ], Shape2D.prototype, "borderThickness", null);
  43616. Shape2D = __decorate([
  43617. BABYLON.className("Shape2D")
  43618. ], Shape2D);
  43619. return Shape2D;
  43620. })(BABYLON.RenderablePrim2D);
  43621. BABYLON.Shape2D = Shape2D;
  43622. var Shape2DInstanceData = (function (_super) {
  43623. __extends(Shape2DInstanceData, _super);
  43624. function Shape2DInstanceData() {
  43625. _super.apply(this, arguments);
  43626. }
  43627. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  43628. // FILL ATTRIBUTES
  43629. get: function () {
  43630. return null;
  43631. },
  43632. enumerable: true,
  43633. configurable: true
  43634. });
  43635. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  43636. get: function () {
  43637. return null;
  43638. },
  43639. enumerable: true,
  43640. configurable: true
  43641. });
  43642. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  43643. get: function () {
  43644. return null;
  43645. },
  43646. enumerable: true,
  43647. configurable: true
  43648. });
  43649. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  43650. get: function () {
  43651. return null;
  43652. },
  43653. enumerable: true,
  43654. configurable: true
  43655. });
  43656. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  43657. // BORDER ATTRIBUTES
  43658. get: function () {
  43659. return null;
  43660. },
  43661. enumerable: true,
  43662. configurable: true
  43663. });
  43664. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  43665. get: function () {
  43666. return null;
  43667. },
  43668. enumerable: true,
  43669. configurable: true
  43670. });
  43671. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  43672. get: function () {
  43673. return null;
  43674. },
  43675. enumerable: true,
  43676. configurable: true
  43677. });
  43678. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  43679. get: function () {
  43680. return null;
  43681. },
  43682. enumerable: true,
  43683. configurable: true
  43684. });
  43685. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  43686. get: function () {
  43687. return null;
  43688. },
  43689. enumerable: true,
  43690. configurable: true
  43691. });
  43692. __decorate([
  43693. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  43694. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  43695. __decorate([
  43696. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43697. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  43698. __decorate([
  43699. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43700. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  43701. __decorate([
  43702. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43703. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  43704. __decorate([
  43705. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  43706. ], Shape2DInstanceData.prototype, "borderThickness", null);
  43707. __decorate([
  43708. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  43709. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  43710. __decorate([
  43711. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43712. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  43713. __decorate([
  43714. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43715. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  43716. __decorate([
  43717. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43718. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  43719. return Shape2DInstanceData;
  43720. })(BABYLON.InstanceDataBase);
  43721. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  43722. })(BABYLON || (BABYLON = {}));
  43723. var BABYLON;
  43724. (function (BABYLON) {
  43725. var Group2D = (function (_super) {
  43726. __extends(Group2D, _super);
  43727. /**
  43728. * Create an Logical or Renderable Group.
  43729. * @param settings a combination of settings, possible ones are
  43730. * - 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)
  43731. * - children: an array of direct children
  43732. * - id a text identifier, for information purpose
  43733. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43734. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43735. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  43736. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  43737. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43738. * - zOrder: override the zOrder with the specified value
  43739. * - origin: define the normalized origin point location, default [0.5;0.5]
  43740. * - 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.
  43741. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  43742. * - 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).
  43743. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  43744. * - 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.
  43745. * - 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.
  43746. * - 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!
  43747. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43748. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43749. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43750. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43751. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43752. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43753. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43754. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43755. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43756. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43757. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43758. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43759. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43760. */
  43761. function Group2D(settings) {
  43762. if (settings == null) {
  43763. settings = {};
  43764. }
  43765. if (settings.origin == null) {
  43766. settings.origin = new BABYLON.Vector2(0, 0);
  43767. }
  43768. _super.call(this, settings);
  43769. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  43770. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  43771. if (this._trackedNode && this.owner) {
  43772. this.owner._registerTrackedNode(this);
  43773. }
  43774. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  43775. var rd = this._renderableData;
  43776. if (rd) {
  43777. rd._noResizeOnScale = (this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  43778. }
  43779. this.size = size;
  43780. this._viewportPosition = BABYLON.Vector2.Zero();
  43781. this._viewportSize = BABYLON.Size.Zero();
  43782. }
  43783. Group2D._createCachedCanvasGroup = function (owner) {
  43784. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true, isPickable: false, dontInheritParentScale: true });
  43785. return g;
  43786. };
  43787. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  43788. this._bindCacheTarget();
  43789. if (vertexData) {
  43790. var uv = vertexData.uvs;
  43791. var nodeuv = this._renderableData._cacheNodeUVs;
  43792. for (var i = 0; i < 4; i++) {
  43793. uv[i * 2 + 0] = nodeuv[i].x;
  43794. uv[i * 2 + 1] = nodeuv[i].y;
  43795. }
  43796. }
  43797. if (material) {
  43798. material.diffuseTexture = this._renderableData._cacheTexture;
  43799. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  43800. }
  43801. this._renderableData._cacheTexture.hasAlpha = true;
  43802. this._unbindCacheTarget();
  43803. };
  43804. Object.defineProperty(Group2D.prototype, "cachedRect", {
  43805. /**
  43806. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  43807. * 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.
  43808. */
  43809. get: function () {
  43810. if (!this._renderableData) {
  43811. return null;
  43812. }
  43813. return this._renderableData._cacheNode;
  43814. },
  43815. enumerable: true,
  43816. configurable: true
  43817. });
  43818. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  43819. /**
  43820. * The UVs into the MapTexture that map the cached group
  43821. */
  43822. get: function () {
  43823. if (!this._renderableData) {
  43824. return null;
  43825. }
  43826. return this._renderableData._cacheNodeUVs;
  43827. },
  43828. enumerable: true,
  43829. configurable: true
  43830. });
  43831. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  43832. get: function () {
  43833. if (!this._renderableData) {
  43834. return null;
  43835. }
  43836. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  43837. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  43838. }
  43839. return this._renderableData._cacheNodeUVsChangedObservable;
  43840. },
  43841. enumerable: true,
  43842. configurable: true
  43843. });
  43844. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  43845. /**
  43846. * Access the texture that maintains a cached version of the Group2D.
  43847. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  43848. */
  43849. get: function () {
  43850. if (!this._renderableData) {
  43851. return null;
  43852. }
  43853. return this._renderableData._cacheTexture;
  43854. },
  43855. enumerable: true,
  43856. configurable: true
  43857. });
  43858. /**
  43859. * Call this method to remove this Group and its children from the Canvas
  43860. */
  43861. Group2D.prototype.dispose = function () {
  43862. if (!_super.prototype.dispose.call(this)) {
  43863. return false;
  43864. }
  43865. if (this._trackedNode != null) {
  43866. this.owner._unregisterTrackedNode(this);
  43867. this._trackedNode = null;
  43868. }
  43869. if (this._renderableData) {
  43870. this._renderableData.dispose(this.owner);
  43871. this._renderableData = null;
  43872. }
  43873. return true;
  43874. };
  43875. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  43876. /**
  43877. * @returns Returns true if the Group render content, false if it's a logical group only
  43878. */
  43879. get: function () {
  43880. return this._isRenderableGroup;
  43881. },
  43882. enumerable: true,
  43883. configurable: true
  43884. });
  43885. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  43886. /**
  43887. * @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
  43888. */
  43889. get: function () {
  43890. return this._isCachedGroup;
  43891. },
  43892. enumerable: true,
  43893. configurable: true
  43894. });
  43895. Object.defineProperty(Group2D.prototype, "size", {
  43896. get: function () {
  43897. return this._size;
  43898. },
  43899. /**
  43900. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  43901. * 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.
  43902. */
  43903. set: function (val) {
  43904. this._size = val;
  43905. },
  43906. enumerable: true,
  43907. configurable: true
  43908. });
  43909. Object.defineProperty(Group2D.prototype, "viewportSize", {
  43910. get: function () {
  43911. return this._viewportSize;
  43912. },
  43913. enumerable: true,
  43914. configurable: true
  43915. });
  43916. Object.defineProperty(Group2D.prototype, "actualSize", {
  43917. get: function () {
  43918. // The computed size will be floor on both width and height
  43919. var actualSize;
  43920. // Return the size if set by the user
  43921. if (this._size) {
  43922. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  43923. }
  43924. else {
  43925. var m = this.boundingInfo.max();
  43926. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  43927. }
  43928. // 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)
  43929. if (!actualSize.equals(this._actualSize)) {
  43930. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  43931. this._actualSize = actualSize;
  43932. this.handleGroupChanged(Group2D.actualSizeProperty);
  43933. }
  43934. return actualSize;
  43935. },
  43936. enumerable: true,
  43937. configurable: true
  43938. });
  43939. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  43940. /**
  43941. * 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.
  43942. * GROUPCACHEBEHAVIOR_NORESIZEONSCALE can also be set if you set it at creation time.
  43943. * 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.
  43944. */
  43945. get: function () {
  43946. return this._cacheBehavior;
  43947. },
  43948. enumerable: true,
  43949. configurable: true
  43950. });
  43951. Group2D.prototype._addPrimToDirtyList = function (prim) {
  43952. this._renderableData._primDirtyList.push(prim);
  43953. };
  43954. Group2D.prototype._renderCachedCanvas = function () {
  43955. this.owner._addGroupRenderCount(1);
  43956. this.updateCachedStates(true);
  43957. var context = new BABYLON.PrepareRender2DContext();
  43958. this._prepareGroupRender(context);
  43959. this._groupRender();
  43960. };
  43961. Object.defineProperty(Group2D.prototype, "trackedNode", {
  43962. /**
  43963. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  43964. */
  43965. get: function () {
  43966. return this._trackedNode;
  43967. },
  43968. set: function (val) {
  43969. if (val != null) {
  43970. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  43971. this.owner._registerTrackedNode(this);
  43972. }
  43973. this._trackedNode = val;
  43974. }
  43975. else {
  43976. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  43977. this.owner._unregisterTrackedNode(this);
  43978. }
  43979. this._trackedNode = null;
  43980. }
  43981. },
  43982. enumerable: true,
  43983. configurable: true
  43984. });
  43985. Group2D.prototype.levelIntersect = function (intersectInfo) {
  43986. // 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
  43987. return true;
  43988. };
  43989. Group2D.prototype.updateLevelBoundingInfo = function () {
  43990. var size;
  43991. // If the size is set by the user, the boundingInfo is computed from this value
  43992. if (this.size) {
  43993. size = this.size;
  43994. }
  43995. else {
  43996. size = new BABYLON.Size(0, 0);
  43997. }
  43998. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  43999. };
  44000. // Method called only on renderable groups to prepare the rendering
  44001. Group2D.prototype._prepareGroupRender = function (context) {
  44002. var sortedDirtyList = null;
  44003. // Update the Global Transformation and visibility status of the changed primitives
  44004. var rd = this._renderableData;
  44005. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  44006. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  44007. this.updateCachedStatesOf(sortedDirtyList, true);
  44008. }
  44009. var s = this.actualSize;
  44010. var a = this.actualScale;
  44011. var sw = Math.ceil(s.width * a.x);
  44012. var sh = Math.ceil(s.height * a.y);
  44013. // The dimension must be overridden when using the designSize feature, the ratio is maintain to compute a uniform scale, which is mandatory but if the designSize's ratio is different from the rendering surface's ratio, content will be clipped in some cases.
  44014. // So we set the width/height to the rendering's one because that's what we want for the viewport!
  44015. if (this instanceof BABYLON.Canvas2D) {
  44016. var c = this;
  44017. if (c.designSize != null) {
  44018. sw = this.owner.engine.getRenderWidth();
  44019. sh = this.owner.engine.getRenderHeight();
  44020. }
  44021. }
  44022. // Setup the size of the rendering viewport
  44023. // 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
  44024. if (!this._isCachedGroup) {
  44025. // Compute the WebGL viewport's location/size
  44026. var t = this._globalTransform.getTranslation();
  44027. var rs = this.owner._renderingSize;
  44028. sh = Math.min(sh, rs.height - t.y);
  44029. sw = Math.min(sw, rs.width - t.x);
  44030. var x = t.x;
  44031. var y = t.y;
  44032. // 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
  44033. this._viewportPosition.x = x;
  44034. this._viewportPosition.y = y;
  44035. }
  44036. // For a cachedGroup we also check of the group's actualSize is changing, if it's the case then the rendering zone will be change so we also have to dirty all primitives to prepare them again.
  44037. if (this._viewportSize.width !== sw || this._viewportSize.height !== sh) {
  44038. context.forceRefreshPrimitive = true;
  44039. this._viewportSize.width = sw;
  44040. this._viewportSize.height = sh;
  44041. }
  44042. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  44043. // If the group is cached, set the dirty flag to true because of the incoming changes
  44044. this._cacheGroupDirty = this._isCachedGroup;
  44045. rd._primNewDirtyList.splice(0);
  44046. // If it's a force refresh, prepare all the children
  44047. if (context.forceRefreshPrimitive) {
  44048. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  44049. var p = _a[_i];
  44050. p._prepareRender(context);
  44051. }
  44052. }
  44053. else {
  44054. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  44055. // the hierarchyDepth in order to prepare primitives from top to bottom
  44056. if (!sortedDirtyList) {
  44057. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  44058. }
  44059. sortedDirtyList.forEach(function (p) {
  44060. // 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.
  44061. // 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.
  44062. if (!p.isDisposed && p._needPrepare()) {
  44063. p._prepareRender(context);
  44064. }
  44065. });
  44066. }
  44067. // Everything is updated, clear the dirty list
  44068. rd._primDirtyList.forEach(function (p) {
  44069. if (rd._primNewDirtyList.indexOf(p) === -1) {
  44070. p._resetPropertiesDirty();
  44071. }
  44072. else {
  44073. p._setFlags(BABYLON.SmartPropertyPrim.flagNeedRefresh);
  44074. }
  44075. });
  44076. rd._primDirtyList.splice(0);
  44077. rd._primDirtyList = rd._primDirtyList.concat(rd._primNewDirtyList);
  44078. }
  44079. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  44080. rd._childrenRenderableGroups.forEach(function (g) {
  44081. g._prepareGroupRender(context);
  44082. });
  44083. };
  44084. Group2D.prototype._groupRender = function () {
  44085. var _this = this;
  44086. var engine = this.owner.engine;
  44087. var failedCount = 0;
  44088. // First recurse to children render group to render them (in their cache or on screen)
  44089. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  44090. var childGroup = _a[_i];
  44091. childGroup._groupRender();
  44092. }
  44093. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  44094. if (!this.isCachedGroup || this._cacheGroupDirty) {
  44095. this.owner._addGroupRenderCount(1);
  44096. if (this.isCachedGroup) {
  44097. this._bindCacheTarget();
  44098. }
  44099. else {
  44100. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  44101. }
  44102. var curAlphaTest = engine.getAlphaTesting() === true;
  44103. var curDepthWrite = engine.getDepthWrite() === true;
  44104. // ===================================================================
  44105. // First pass, update the InstancedArray and render Opaque primitives
  44106. // Disable Alpha Testing, Enable Depth Write
  44107. engine.setAlphaTesting(false);
  44108. engine.setDepthWrite(true);
  44109. // For each different model of primitive to render
  44110. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  44111. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  44112. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  44113. var renderCount = _this._prepareContext(engine, context, v);
  44114. // If null is returned, there's no opaque data to render
  44115. if (renderCount === null) {
  44116. return;
  44117. }
  44118. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  44119. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  44120. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  44121. var renderFailed = !v.modelRenderCache.render(v, context);
  44122. // Update dirty flag/related
  44123. v.opaqueDirty = renderFailed;
  44124. failedCount += renderFailed ? 1 : 0;
  44125. }
  44126. });
  44127. // =======================================================================
  44128. // Second pass, update the InstancedArray and render AlphaTest primitives
  44129. // Enable Alpha Testing, Enable Depth Write
  44130. engine.setAlphaTesting(true);
  44131. engine.setDepthWrite(true);
  44132. // For each different model of primitive to render
  44133. context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  44134. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  44135. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  44136. var renderCount = _this._prepareContext(engine, context, v);
  44137. // If null is returned, there's no opaque data to render
  44138. if (renderCount === null) {
  44139. return;
  44140. }
  44141. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  44142. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  44143. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  44144. var renderFailed = !v.modelRenderCache.render(v, context);
  44145. // Update dirty flag/related
  44146. v.opaqueDirty = renderFailed;
  44147. failedCount += renderFailed ? 1 : 0;
  44148. }
  44149. });
  44150. // =======================================================================
  44151. // Third pass, transparent primitive rendering
  44152. // Enable Alpha Testing, Disable Depth Write
  44153. engine.setAlphaTesting(true);
  44154. engine.setDepthWrite(false);
  44155. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  44156. if (this._renderableData._transparentListChanged) {
  44157. this._updateTransparentData();
  44158. }
  44159. // From this point on we have up to date data to render, so let's go
  44160. failedCount += this._renderTransparentData();
  44161. // =======================================================================
  44162. // Unbind target/restore viewport setting, clear dirty flag, and quit
  44163. // The group's content is no longer dirty
  44164. this._cacheGroupDirty = failedCount !== 0;
  44165. if (this.isCachedGroup) {
  44166. this._unbindCacheTarget();
  44167. }
  44168. else {
  44169. if (curVP) {
  44170. engine.setViewport(curVP);
  44171. }
  44172. }
  44173. // Restore saved states
  44174. engine.setAlphaTesting(curAlphaTest);
  44175. engine.setDepthWrite(curDepthWrite);
  44176. }
  44177. };
  44178. Group2D.prototype._setCacheGroupDirty = function () {
  44179. this._cacheGroupDirty = true;
  44180. };
  44181. Group2D.prototype._updateTransparentData = function () {
  44182. this.owner._addUpdateTransparentDataCount(1);
  44183. var rd = this._renderableData;
  44184. // Sort all the primitive from their depth, max (bottom) to min (top)
  44185. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  44186. var checkAndAddPrimInSegment = function (seg, tpiI) {
  44187. var tpi = rd._transparentPrimitives[tpiI];
  44188. // Fast rejection: if gii are different
  44189. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  44190. return false;
  44191. }
  44192. //let tpiZ = tpi._primitive.actualZOffset;
  44193. // We've made it so far, the tpi can be part of the segment, add it
  44194. tpi._transparentSegment = seg;
  44195. tpi._primitive._updateTransparentSegmentIndices(seg);
  44196. return true;
  44197. };
  44198. // Free the existing TransparentSegments
  44199. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  44200. var ts = _a[_i];
  44201. ts.dispose(this.owner.engine);
  44202. }
  44203. rd._transparentSegments.splice(0);
  44204. var prevSeg = null;
  44205. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  44206. var tpi = rd._transparentPrimitives[tpiI];
  44207. // Check if the Data in which the primitive is stored is not sorted properly
  44208. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  44209. tpi._groupInstanceInfo.sortTransparentData();
  44210. }
  44211. // Reset the segment, we have to create/rebuild it
  44212. tpi._transparentSegment = null;
  44213. // If there's a previous valid segment, check if this prim can be part of it
  44214. if (prevSeg) {
  44215. checkAndAddPrimInSegment(prevSeg, tpiI);
  44216. }
  44217. // If we couldn't insert in the adjacent segments, he have to create one
  44218. if (!tpi._transparentSegment) {
  44219. var ts = new BABYLON.TransparentSegment();
  44220. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  44221. var prim = tpi._primitive;
  44222. ts.startZ = prim.actualZOffset;
  44223. prim._updateTransparentSegmentIndices(ts);
  44224. ts.endZ = ts.startZ;
  44225. tpi._transparentSegment = ts;
  44226. rd._transparentSegments.push(ts);
  44227. }
  44228. // Update prevSeg
  44229. prevSeg = tpi._transparentSegment;
  44230. }
  44231. //rd._firstChangedPrim = null;
  44232. rd._transparentListChanged = false;
  44233. };
  44234. Group2D.prototype._renderTransparentData = function () {
  44235. var failedCount = 0;
  44236. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  44237. var rd = this._renderableData;
  44238. var useInstanced = this.owner.supportInstancedArray;
  44239. var length = rd._transparentSegments.length;
  44240. for (var i = 0; i < length; i++) {
  44241. context.instancedBuffers = null;
  44242. var ts = rd._transparentSegments[i];
  44243. var gii = ts.groupInsanceInfo;
  44244. var mrc = gii.modelRenderCache;
  44245. var engine = this.owner.engine;
  44246. var count = ts.endDataIndex - ts.startDataIndex;
  44247. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  44248. // We don't want to create an Instanced Buffer for less that 5 prims
  44249. if (useInstanced && count >= 5) {
  44250. if (!ts.partBuffers) {
  44251. var buffers = new Array();
  44252. for (var j = 0; j < gii.transparentData.length; j++) {
  44253. var gitd = gii.transparentData[j];
  44254. var dfa = gitd._partData;
  44255. var data = dfa.pack();
  44256. var stride = dfa.stride;
  44257. var neededSize = count * stride * 4;
  44258. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  44259. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  44260. engine.updateArrayBuffer(segData);
  44261. buffers.push(buffer);
  44262. }
  44263. ts.partBuffers = buffers;
  44264. }
  44265. else if (gii.transparentDirty) {
  44266. for (var j = 0; j < gii.transparentData.length; j++) {
  44267. var gitd = gii.transparentData[j];
  44268. var dfa = gitd._partData;
  44269. var data = dfa.pack();
  44270. var stride = dfa.stride;
  44271. var buffer = ts.partBuffers[j];
  44272. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  44273. engine.bindArrayBuffer(buffer);
  44274. engine.updateArrayBuffer(segData);
  44275. }
  44276. }
  44277. context.useInstancing = true;
  44278. context.instancesCount = count;
  44279. context.instancedBuffers = ts.partBuffers;
  44280. context.groupInfoPartData = gii.transparentData;
  44281. var renderFailed = !mrc.render(gii, context);
  44282. failedCount += renderFailed ? 1 : 0;
  44283. }
  44284. else {
  44285. context.useInstancing = false;
  44286. context.partDataStartIndex = ts.startDataIndex;
  44287. context.partDataEndIndex = ts.endDataIndex;
  44288. context.groupInfoPartData = gii.transparentData;
  44289. var renderFailed = !mrc.render(gii, context);
  44290. failedCount += renderFailed ? 1 : 0;
  44291. }
  44292. }
  44293. return failedCount;
  44294. };
  44295. Group2D.prototype._prepareContext = function (engine, context, gii) {
  44296. var gipd = null;
  44297. var setDirty;
  44298. var getDirty;
  44299. // Render Mode specifics
  44300. switch (context.renderMode) {
  44301. case BABYLON.Render2DContext.RenderModeOpaque:
  44302. {
  44303. if (!gii.hasOpaqueData) {
  44304. return null;
  44305. }
  44306. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  44307. getDirty = function () { return gii.opaqueDirty; };
  44308. context.groupInfoPartData = gii.opaqueData;
  44309. gipd = gii.opaqueData;
  44310. break;
  44311. }
  44312. case BABYLON.Render2DContext.RenderModeAlphaTest:
  44313. {
  44314. if (!gii.hasAlphaTestData) {
  44315. return null;
  44316. }
  44317. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  44318. getDirty = function () { return gii.alphaTestDirty; };
  44319. context.groupInfoPartData = gii.alphaTestData;
  44320. gipd = gii.alphaTestData;
  44321. break;
  44322. }
  44323. default:
  44324. throw new Error("_prepareContext is only for opaque or alphaTest");
  44325. }
  44326. var renderCount = 0;
  44327. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  44328. // Skip it if instanced arrays are not supported
  44329. if (this.owner.supportInstancedArray) {
  44330. // Flag for instancing
  44331. context.useInstancing = true;
  44332. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  44333. for (var i = 0; i < gipd.length; i++) {
  44334. var pid = gipd[i];
  44335. // If the instances of the model was changed, pack the data
  44336. var array = pid._partData;
  44337. var instanceData_1 = array.pack();
  44338. renderCount += array.usedElementCount;
  44339. // Compute the size the instance buffer should have
  44340. var neededSize = array.usedElementCount * array.stride * 4;
  44341. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  44342. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  44343. if (pid._partBuffer) {
  44344. engine.deleteInstancesBuffer(pid._partBuffer);
  44345. }
  44346. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  44347. pid._partBufferSize = neededSize;
  44348. setDirty(false);
  44349. // Update the WebGL buffer to match the new content of the instances data
  44350. engine.updateArrayBuffer(instanceData_1);
  44351. }
  44352. else if (getDirty()) {
  44353. // Update the WebGL buffer to match the new content of the instances data
  44354. engine.bindArrayBuffer(pid._partBuffer);
  44355. engine.updateArrayBuffer(instanceData_1);
  44356. }
  44357. }
  44358. setDirty(false);
  44359. }
  44360. else {
  44361. context.partDataStartIndex = 0;
  44362. // Find the first valid object to get the count
  44363. if (context.groupInfoPartData.length > 0) {
  44364. var i = 0;
  44365. while (!context.groupInfoPartData[i]) {
  44366. i++;
  44367. }
  44368. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  44369. }
  44370. }
  44371. return renderCount;
  44372. };
  44373. Group2D.prototype._setRenderingScale = function (scale) {
  44374. if (this._renderableData._renderingScale === scale) {
  44375. return;
  44376. }
  44377. this._renderableData._renderingScale = scale;
  44378. };
  44379. Group2D.prototype._bindCacheTarget = function () {
  44380. var curWidth;
  44381. var curHeight;
  44382. var rd = this._renderableData;
  44383. var rs = rd._renderingScale;
  44384. var noResizeScale = rd._noResizeOnScale;
  44385. var isCanvas = this.parent == null;
  44386. var scale;
  44387. if (noResizeScale) {
  44388. scale = isCanvas ? Group2D._uV : this.parent.actualScale;
  44389. }
  44390. else {
  44391. scale = this.actualScale;
  44392. }
  44393. Group2D._s.width = Math.ceil(this.actualSize.width * scale.x * rs);
  44394. Group2D._s.height = Math.ceil(this.actualSize.height * scale.y * rs);
  44395. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  44396. if (rd._cacheNode) {
  44397. var size = rd._cacheNode.contentSize;
  44398. // Check if we have to deallocate because the size is too small
  44399. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  44400. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  44401. // For World space: no over-provisioning
  44402. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  44403. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  44404. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  44405. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  44406. rd._cacheTexture.freeRect(rd._cacheNode);
  44407. rd._cacheNode = null;
  44408. }
  44409. }
  44410. if (!rd._cacheNode) {
  44411. // Check if we have to allocate a rendering zone in the global cache texture
  44412. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  44413. rd._cacheNode = res.node;
  44414. rd._cacheTexture = res.texture;
  44415. rd._cacheRenderSprite = res.sprite;
  44416. sizeChanged = true;
  44417. }
  44418. if (sizeChanged) {
  44419. rd._cacheSize.copyFrom(Group2D._s);
  44420. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  44421. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  44422. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  44423. }
  44424. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  44425. }
  44426. var n = rd._cacheNode;
  44427. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  44428. };
  44429. Group2D.prototype._unbindCacheTarget = function () {
  44430. if (this._renderableData._cacheTexture) {
  44431. this._renderableData._cacheTexture.unbindTexture();
  44432. }
  44433. };
  44434. Group2D.prototype.handleGroupChanged = function (prop) {
  44435. // This method is only for cachedGroup
  44436. var rd = this._renderableData;
  44437. if (!rd) {
  44438. return;
  44439. }
  44440. var cachedSprite = rd._cacheRenderSprite;
  44441. if (!this.isCachedGroup || !cachedSprite) {
  44442. return;
  44443. }
  44444. // For now we only support these property changes
  44445. // TODO: add more! :)
  44446. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  44447. cachedSprite.actualPosition = this.actualPosition.clone();
  44448. if (cachedSprite.position != null) {
  44449. cachedSprite.position = cachedSprite.actualPosition.clone();
  44450. }
  44451. }
  44452. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  44453. cachedSprite.rotation = this.rotation;
  44454. }
  44455. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  44456. cachedSprite.scale = this.scale;
  44457. }
  44458. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  44459. cachedSprite.origin = this.origin.clone();
  44460. }
  44461. else if (prop.id === Group2D.actualSizeProperty.id) {
  44462. cachedSprite.size = this.actualSize.clone();
  44463. }
  44464. };
  44465. Group2D.prototype.detectGroupStates = function () {
  44466. var isCanvas = this instanceof BABYLON.Canvas2D;
  44467. var canvasStrat = this.owner.cachingStrategy;
  44468. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  44469. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  44470. this._isRenderableGroup = isCanvas;
  44471. this._isCachedGroup = false;
  44472. }
  44473. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  44474. if (isCanvas) {
  44475. this._isRenderableGroup = true;
  44476. this._isCachedGroup = true;
  44477. }
  44478. else {
  44479. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  44480. this._isCachedGroup = false;
  44481. }
  44482. }
  44483. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  44484. if (isCanvas) {
  44485. this._isRenderableGroup = true;
  44486. this._isCachedGroup = false;
  44487. }
  44488. else {
  44489. if (this.hierarchyDepth === 1) {
  44490. this._isRenderableGroup = true;
  44491. this._isCachedGroup = true;
  44492. }
  44493. else {
  44494. this._isRenderableGroup = false;
  44495. this._isCachedGroup = false;
  44496. }
  44497. }
  44498. }
  44499. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  44500. var gcb = this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK;
  44501. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  44502. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  44503. this._isCachedGroup = false;
  44504. }
  44505. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  44506. this._isRenderableGroup = true;
  44507. this._isCachedGroup = true;
  44508. }
  44509. }
  44510. if (this._isRenderableGroup) {
  44511. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  44512. if (!this._renderableData) {
  44513. this._renderableData = new RenderableGroupData();
  44514. }
  44515. }
  44516. // If the group is tagged as renderable we add it to the renderable tree
  44517. if (this._isCachedGroup) {
  44518. this._renderableData._noResizeOnScale = (this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  44519. var cur = this.parent;
  44520. while (cur) {
  44521. if (cur instanceof Group2D && cur._isRenderableGroup) {
  44522. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  44523. cur._renderableData._childrenRenderableGroups.push(this);
  44524. }
  44525. break;
  44526. }
  44527. cur = cur.parent;
  44528. }
  44529. }
  44530. };
  44531. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  44532. /**
  44533. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  44534. */
  44535. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  44536. /**
  44537. * When used, this group's content won't be cached, no matter which strategy used.
  44538. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  44539. */
  44540. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  44541. /**
  44542. * When used, the group's content will be cached in the nearest cached parent group/canvas
  44543. */
  44544. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  44545. /**
  44546. * You can specify this behavior to any cached Group2D to indicate that you don't want the cached content to be resized when the Group's actualScale is changing. It will draw the content stretched or shrink which is faster than a resize. This setting is obviously for performance consideration, don't use it if you want the best rendering quality
  44547. */
  44548. Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE = 0x100;
  44549. Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK = 0xFF;
  44550. Group2D._uV = new BABYLON.Vector2(1, 1);
  44551. Group2D._s = BABYLON.Size.Zero();
  44552. __decorate([
  44553. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  44554. ], Group2D.prototype, "size", null);
  44555. __decorate([
  44556. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  44557. ], Group2D.prototype, "actualSize", null);
  44558. Group2D = __decorate([
  44559. BABYLON.className("Group2D")
  44560. ], Group2D);
  44561. return Group2D;
  44562. })(BABYLON.Prim2DBase);
  44563. BABYLON.Group2D = Group2D;
  44564. var RenderableGroupData = (function () {
  44565. function RenderableGroupData() {
  44566. this._primDirtyList = new Array();
  44567. this._primNewDirtyList = new Array();
  44568. this._childrenRenderableGroups = new Array();
  44569. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  44570. this._transparentPrimitives = new Array();
  44571. this._transparentSegments = new Array();
  44572. this._transparentListChanged = false;
  44573. this._cacheNode = null;
  44574. this._cacheTexture = null;
  44575. this._cacheRenderSprite = null;
  44576. this._renderingScale = 1;
  44577. this._cacheNodeUVs = null;
  44578. this._cacheNodeUVsChangedObservable = null;
  44579. this._cacheSize = BABYLON.Size.Zero();
  44580. this._useMipMap = false;
  44581. this._anisotropicLevel = 1;
  44582. this._noResizeOnScale = false;
  44583. }
  44584. RenderableGroupData.prototype.dispose = function (owner) {
  44585. var engine = owner.engine;
  44586. if (this._cacheRenderSprite) {
  44587. this._cacheRenderSprite.dispose();
  44588. this._cacheRenderSprite = null;
  44589. }
  44590. if (this._cacheTexture && this._cacheNode) {
  44591. this._cacheTexture.freeRect(this._cacheNode);
  44592. this._cacheTexture = null;
  44593. this._cacheNode = null;
  44594. }
  44595. if (this._primDirtyList) {
  44596. this._primDirtyList.splice(0);
  44597. this._primDirtyList = null;
  44598. }
  44599. if (this._renderGroupInstancesInfo) {
  44600. this._renderGroupInstancesInfo.forEach(function (k, v) {
  44601. v.dispose();
  44602. });
  44603. this._renderGroupInstancesInfo = null;
  44604. }
  44605. if (this._cacheNodeUVsChangedObservable) {
  44606. this._cacheNodeUVsChangedObservable.clear();
  44607. this._cacheNodeUVsChangedObservable = null;
  44608. }
  44609. if (this._transparentSegments) {
  44610. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  44611. var ts = _a[_i];
  44612. ts.dispose(engine);
  44613. }
  44614. this._transparentSegments.splice(0);
  44615. this._transparentSegments = null;
  44616. }
  44617. };
  44618. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  44619. var tpi = new TransparentPrimitiveInfo();
  44620. tpi._primitive = prim;
  44621. tpi._groupInstanceInfo = gii;
  44622. tpi._transparentSegment = null;
  44623. this._transparentPrimitives.push(tpi);
  44624. this._transparentListChanged = true;
  44625. return tpi;
  44626. };
  44627. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  44628. var index = this._transparentPrimitives.indexOf(tpi);
  44629. if (index !== -1) {
  44630. this._transparentPrimitives.splice(index, 1);
  44631. this._transparentListChanged = true;
  44632. }
  44633. };
  44634. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  44635. this._transparentListChanged = true;
  44636. //this.updateSmallestZChangedPrim(tpi);
  44637. };
  44638. return RenderableGroupData;
  44639. })();
  44640. BABYLON.RenderableGroupData = RenderableGroupData;
  44641. var TransparentPrimitiveInfo = (function () {
  44642. function TransparentPrimitiveInfo() {
  44643. }
  44644. return TransparentPrimitiveInfo;
  44645. })();
  44646. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  44647. })(BABYLON || (BABYLON = {}));
  44648. var BABYLON;
  44649. (function (BABYLON) {
  44650. var Rectangle2DRenderCache = (function (_super) {
  44651. __extends(Rectangle2DRenderCache, _super);
  44652. function Rectangle2DRenderCache(engine, modelKey) {
  44653. _super.call(this, engine, modelKey);
  44654. this.effectsReady = false;
  44655. this.fillVB = null;
  44656. this.fillIB = null;
  44657. this.fillIndicesCount = 0;
  44658. this.instancingFillAttributes = null;
  44659. this.effectFill = null;
  44660. this.effectFillInstanced = null;
  44661. this.borderVB = null;
  44662. this.borderIB = null;
  44663. this.borderIndicesCount = 0;
  44664. this.instancingBorderAttributes = null;
  44665. this.effectBorder = null;
  44666. this.effectBorderInstanced = null;
  44667. }
  44668. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  44669. // Do nothing if the shader is still loading/preparing
  44670. if (!this.effectsReady) {
  44671. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44672. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44673. return false;
  44674. }
  44675. this.effectsReady = true;
  44676. }
  44677. var canvas = instanceInfo.owner.owner;
  44678. var engine = canvas.engine;
  44679. var depthFunction = 0;
  44680. if (this.effectFill && this.effectBorder) {
  44681. depthFunction = engine.getDepthFunction();
  44682. engine.setDepthFunctionToLessOrEqual();
  44683. }
  44684. var curAlphaMode = engine.getAlphaMode();
  44685. if (this.effectFill) {
  44686. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44687. var pid = context.groupInfoPartData[partIndex];
  44688. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44689. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44690. }
  44691. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44692. engine.enableEffect(effect);
  44693. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  44694. if (context.useInstancing) {
  44695. if (!this.instancingFillAttributes) {
  44696. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44697. }
  44698. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44699. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44700. canvas._addDrawCallCount(1, context.renderMode);
  44701. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44702. engine.draw(true, 0, this.fillIndicesCount, count);
  44703. engine.unbindInstanceAttributes();
  44704. }
  44705. else {
  44706. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44707. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44708. this.setupUniforms(effect, partIndex, pid._partData, i);
  44709. engine.draw(true, 0, this.fillIndicesCount);
  44710. }
  44711. }
  44712. }
  44713. if (this.effectBorder) {
  44714. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44715. var pid = context.groupInfoPartData[partIndex];
  44716. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44717. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44718. }
  44719. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44720. engine.enableEffect(effect);
  44721. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  44722. if (context.useInstancing) {
  44723. if (!this.instancingBorderAttributes) {
  44724. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44725. }
  44726. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44727. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44728. canvas._addDrawCallCount(1, context.renderMode);
  44729. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44730. engine.draw(true, 0, this.borderIndicesCount, count);
  44731. engine.unbindInstanceAttributes();
  44732. }
  44733. else {
  44734. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44735. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44736. this.setupUniforms(effect, partIndex, pid._partData, i);
  44737. engine.draw(true, 0, this.borderIndicesCount);
  44738. }
  44739. }
  44740. }
  44741. engine.setAlphaMode(curAlphaMode, true);
  44742. if (this.effectFill && this.effectBorder) {
  44743. engine.setDepthFunction(depthFunction);
  44744. }
  44745. return true;
  44746. };
  44747. Rectangle2DRenderCache.prototype.dispose = function () {
  44748. if (!_super.prototype.dispose.call(this)) {
  44749. return false;
  44750. }
  44751. if (this.fillVB) {
  44752. this._engine._releaseBuffer(this.fillVB);
  44753. this.fillVB = null;
  44754. }
  44755. if (this.fillIB) {
  44756. this._engine._releaseBuffer(this.fillIB);
  44757. this.fillIB = null;
  44758. }
  44759. this.effectFill = null;
  44760. this.effectFillInstanced = null;
  44761. this.effectBorder = null;
  44762. this.effectBorderInstanced = null;
  44763. if (this.borderVB) {
  44764. this._engine._releaseBuffer(this.borderVB);
  44765. this.borderVB = null;
  44766. }
  44767. if (this.borderIB) {
  44768. this._engine._releaseBuffer(this.borderIB);
  44769. this.borderIB = null;
  44770. }
  44771. return true;
  44772. };
  44773. return Rectangle2DRenderCache;
  44774. })(BABYLON.ModelRenderCache);
  44775. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  44776. var Rectangle2DInstanceData = (function (_super) {
  44777. __extends(Rectangle2DInstanceData, _super);
  44778. function Rectangle2DInstanceData(partId) {
  44779. _super.call(this, partId, 1);
  44780. }
  44781. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  44782. get: function () {
  44783. return null;
  44784. },
  44785. enumerable: true,
  44786. configurable: true
  44787. });
  44788. __decorate([
  44789. BABYLON.instanceData()
  44790. ], Rectangle2DInstanceData.prototype, "properties", null);
  44791. return Rectangle2DInstanceData;
  44792. })(BABYLON.Shape2DInstanceData);
  44793. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  44794. var Rectangle2D = (function (_super) {
  44795. __extends(Rectangle2D, _super);
  44796. /**
  44797. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  44798. * @param settings a combination of settings, possible ones are
  44799. * - 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)
  44800. * - children: an array of direct children
  44801. * - id a text identifier, for information purpose
  44802. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  44803. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44804. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44805. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  44806. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44807. * - zOrder: override the zOrder with the specified value
  44808. * - origin: define the normalized origin point location, default [0.5;0.5]
  44809. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  44810. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  44811. * - 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)
  44812. * - 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)
  44813. * - borderThickness: the thickness of the drawn border, default is 1.
  44814. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  44815. * - 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.
  44816. * - 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.
  44817. * - 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!
  44818. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44819. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44820. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44821. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44822. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44823. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44824. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44825. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44826. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44827. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44828. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44829. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44830. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44831. */
  44832. function Rectangle2D(settings) {
  44833. // Avoid checking every time if the object exists
  44834. if (settings == null) {
  44835. settings = {};
  44836. }
  44837. _super.call(this, settings);
  44838. if (settings.size != null) {
  44839. this.size = settings.size;
  44840. }
  44841. else if (settings.width || settings.height) {
  44842. var size = new BABYLON.Size(settings.width, settings.height);
  44843. this.size = size;
  44844. }
  44845. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  44846. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  44847. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  44848. //this.size = size;
  44849. this.roundRadius = roundRadius;
  44850. this.borderThickness = borderThickness;
  44851. }
  44852. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  44853. get: function () {
  44854. if (this._actualSize) {
  44855. return this._actualSize;
  44856. }
  44857. return this.size;
  44858. },
  44859. set: function (value) {
  44860. this._actualSize = value;
  44861. },
  44862. enumerable: true,
  44863. configurable: true
  44864. });
  44865. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  44866. get: function () {
  44867. return this._notRounded;
  44868. },
  44869. set: function (value) {
  44870. this._notRounded = value;
  44871. },
  44872. enumerable: true,
  44873. configurable: true
  44874. });
  44875. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  44876. get: function () {
  44877. return this._roundRadius;
  44878. },
  44879. set: function (value) {
  44880. this._roundRadius = value;
  44881. this.notRounded = value === 0;
  44882. this._positioningDirty();
  44883. },
  44884. enumerable: true,
  44885. configurable: true
  44886. });
  44887. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  44888. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  44889. if (this.notRounded) {
  44890. return true;
  44891. }
  44892. // 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.
  44893. // 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)
  44894. // 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.
  44895. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  44896. var size = this.size;
  44897. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  44898. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  44899. var rr = this.roundRadius;
  44900. var rrs = rr * rr;
  44901. // Check if the point is in the bottom/left quarter area
  44902. Rectangle2D._i1.x = rr;
  44903. Rectangle2D._i1.y = rr;
  44904. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  44905. // Compute the intersection point in the quarter local space
  44906. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44907. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44908. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44909. return Rectangle2D._i2.lengthSquared() <= rrs;
  44910. }
  44911. // Check if the point is in the top/left quarter area
  44912. Rectangle2D._i1.x = rr;
  44913. Rectangle2D._i1.y = size.height - rr;
  44914. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  44915. // Compute the intersection point in the quarter local space
  44916. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44917. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44918. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44919. return Rectangle2D._i2.lengthSquared() <= rrs;
  44920. }
  44921. // Check if the point is in the top/right quarter area
  44922. Rectangle2D._i1.x = size.width - rr;
  44923. Rectangle2D._i1.y = size.height - rr;
  44924. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  44925. // Compute the intersection point in the quarter local space
  44926. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44927. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44928. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44929. return Rectangle2D._i2.lengthSquared() <= rrs;
  44930. }
  44931. // Check if the point is in the bottom/right quarter area
  44932. Rectangle2D._i1.x = size.width - rr;
  44933. Rectangle2D._i1.y = rr;
  44934. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  44935. // Compute the intersection point in the quarter local space
  44936. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44937. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44938. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44939. return Rectangle2D._i2.lengthSquared() <= rrs;
  44940. }
  44941. // At any other locations the point is guarantied to be inside
  44942. return true;
  44943. };
  44944. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  44945. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44946. };
  44947. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  44948. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  44949. return renderCache;
  44950. };
  44951. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44952. var renderCache = modelRenderCache;
  44953. var engine = this.owner.engine;
  44954. // Need to create WebGL resources for fill part?
  44955. if (this.fill) {
  44956. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  44957. var vb = new Float32Array(vbSize);
  44958. for (var i = 0; i < vbSize; i++) {
  44959. vb[i] = i;
  44960. }
  44961. renderCache.fillVB = engine.createVertexBuffer(vb);
  44962. var triCount = vbSize - 1;
  44963. var ib = new Float32Array(triCount * 3);
  44964. for (var i = 0; i < triCount; i++) {
  44965. ib[i * 3 + 0] = 0;
  44966. ib[i * 3 + 2] = i + 1;
  44967. ib[i * 3 + 1] = i + 2;
  44968. }
  44969. ib[triCount * 3 - 2] = 1;
  44970. renderCache.fillIB = engine.createIndexBuffer(ib);
  44971. renderCache.fillIndicesCount = triCount * 3;
  44972. // 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
  44973. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  44974. if (ei) {
  44975. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44976. }
  44977. // Get the non instanced version
  44978. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  44979. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44980. }
  44981. // Need to create WebGL resource for border part?
  44982. if (this.border) {
  44983. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  44984. var vb = new Float32Array(vbSize);
  44985. for (var i = 0; i < vbSize; i++) {
  44986. vb[i] = i;
  44987. }
  44988. renderCache.borderVB = engine.createVertexBuffer(vb);
  44989. var triCount = vbSize;
  44990. var rs = triCount / 2;
  44991. var ib = new Float32Array(triCount * 3);
  44992. for (var i = 0; i < rs; i++) {
  44993. var r0 = i;
  44994. var r1 = (i + 1) % rs;
  44995. ib[i * 6 + 0] = rs + r1;
  44996. ib[i * 6 + 1] = rs + r0;
  44997. ib[i * 6 + 2] = r0;
  44998. ib[i * 6 + 3] = r1;
  44999. ib[i * 6 + 4] = rs + r1;
  45000. ib[i * 6 + 5] = r0;
  45001. }
  45002. renderCache.borderIB = engine.createIndexBuffer(ib);
  45003. renderCache.borderIndicesCount = triCount * 3;
  45004. // 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
  45005. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  45006. if (ei) {
  45007. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45008. }
  45009. // Get the non instanced version
  45010. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  45011. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45012. }
  45013. return renderCache;
  45014. };
  45015. // 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
  45016. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  45017. // Fall back to default implementation if there's no round Radius
  45018. if (this._notRounded) {
  45019. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  45020. }
  45021. else {
  45022. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  45023. initialContentPosition.x = initialContentPosition.y = rr;
  45024. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  45025. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  45026. }
  45027. };
  45028. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  45029. // Fall back to default implementation if there's no round Radius
  45030. if (this._notRounded) {
  45031. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  45032. }
  45033. else {
  45034. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  45035. newPrimSize.copyFrom(primSize);
  45036. newPrimSize.width += rr * 2;
  45037. newPrimSize.height += rr * 2;
  45038. }
  45039. };
  45040. Rectangle2D.prototype.createInstanceDataParts = function () {
  45041. var res = new Array();
  45042. if (this.border) {
  45043. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  45044. }
  45045. if (this.fill) {
  45046. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  45047. }
  45048. return res;
  45049. };
  45050. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  45051. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45052. return false;
  45053. }
  45054. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  45055. var d = part;
  45056. var size = this.actualSize;
  45057. var s = this.actualScale;
  45058. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  45059. }
  45060. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  45061. var d = part;
  45062. var size = this.actualSize;
  45063. var s = this.actualScale;
  45064. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  45065. }
  45066. return true;
  45067. };
  45068. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  45069. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  45070. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  45071. Rectangle2D.roundSubdivisions = 16;
  45072. __decorate([
  45073. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  45074. ], Rectangle2D.prototype, "actualSize", null);
  45075. __decorate([
  45076. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  45077. ], Rectangle2D.prototype, "notRounded", null);
  45078. __decorate([
  45079. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  45080. ], Rectangle2D.prototype, "roundRadius", null);
  45081. Rectangle2D = __decorate([
  45082. BABYLON.className("Rectangle2D")
  45083. ], Rectangle2D);
  45084. return Rectangle2D;
  45085. })(BABYLON.Shape2D);
  45086. BABYLON.Rectangle2D = Rectangle2D;
  45087. })(BABYLON || (BABYLON = {}));
  45088. var BABYLON;
  45089. (function (BABYLON) {
  45090. var Ellipse2DRenderCache = (function (_super) {
  45091. __extends(Ellipse2DRenderCache, _super);
  45092. function Ellipse2DRenderCache(engine, modelKey) {
  45093. _super.call(this, engine, modelKey);
  45094. this.effectsReady = false;
  45095. this.fillVB = null;
  45096. this.fillIB = null;
  45097. this.fillIndicesCount = 0;
  45098. this.instancingFillAttributes = null;
  45099. this.effectFillInstanced = null;
  45100. this.effectFill = null;
  45101. this.borderVB = null;
  45102. this.borderIB = null;
  45103. this.borderIndicesCount = 0;
  45104. this.instancingBorderAttributes = null;
  45105. this.effectBorderInstanced = null;
  45106. this.effectBorder = null;
  45107. }
  45108. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  45109. // Do nothing if the shader is still loading/preparing
  45110. if (!this.effectsReady) {
  45111. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  45112. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  45113. return false;
  45114. }
  45115. this.effectsReady = true;
  45116. }
  45117. var canvas = instanceInfo.owner.owner;
  45118. var engine = canvas.engine;
  45119. var depthFunction = 0;
  45120. if (this.effectFill && this.effectBorder) {
  45121. depthFunction = engine.getDepthFunction();
  45122. engine.setDepthFunctionToLessOrEqual();
  45123. }
  45124. var curAlphaMode = engine.getAlphaMode();
  45125. if (this.effectFill) {
  45126. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  45127. var pid = context.groupInfoPartData[partIndex];
  45128. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45129. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45130. }
  45131. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  45132. engine.enableEffect(effect);
  45133. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  45134. if (context.useInstancing) {
  45135. if (!this.instancingFillAttributes) {
  45136. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  45137. }
  45138. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45139. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45140. canvas._addDrawCallCount(1, context.renderMode);
  45141. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  45142. engine.draw(true, 0, this.fillIndicesCount, count);
  45143. engine.unbindInstanceAttributes();
  45144. }
  45145. else {
  45146. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45147. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45148. this.setupUniforms(effect, partIndex, pid._partData, i);
  45149. engine.draw(true, 0, this.fillIndicesCount);
  45150. }
  45151. }
  45152. }
  45153. if (this.effectBorder) {
  45154. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  45155. var pid = context.groupInfoPartData[partIndex];
  45156. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45157. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45158. }
  45159. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  45160. engine.enableEffect(effect);
  45161. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  45162. if (context.useInstancing) {
  45163. if (!this.instancingBorderAttributes) {
  45164. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  45165. }
  45166. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45167. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45168. canvas._addDrawCallCount(1, context.renderMode);
  45169. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  45170. engine.draw(true, 0, this.borderIndicesCount, count);
  45171. engine.unbindInstanceAttributes();
  45172. }
  45173. else {
  45174. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45175. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45176. this.setupUniforms(effect, partIndex, pid._partData, i);
  45177. engine.draw(true, 0, this.borderIndicesCount);
  45178. }
  45179. }
  45180. }
  45181. engine.setAlphaMode(curAlphaMode, true);
  45182. if (this.effectFill && this.effectBorder) {
  45183. engine.setDepthFunction(depthFunction);
  45184. }
  45185. return true;
  45186. };
  45187. Ellipse2DRenderCache.prototype.dispose = function () {
  45188. if (!_super.prototype.dispose.call(this)) {
  45189. return false;
  45190. }
  45191. if (this.fillVB) {
  45192. this._engine._releaseBuffer(this.fillVB);
  45193. this.fillVB = null;
  45194. }
  45195. if (this.fillIB) {
  45196. this._engine._releaseBuffer(this.fillIB);
  45197. this.fillIB = null;
  45198. }
  45199. this.effectFill = null;
  45200. this.effectFillInstanced = null;
  45201. this.effectBorder = null;
  45202. this.effectBorderInstanced = null;
  45203. if (this.borderVB) {
  45204. this._engine._releaseBuffer(this.borderVB);
  45205. this.borderVB = null;
  45206. }
  45207. if (this.borderIB) {
  45208. this._engine._releaseBuffer(this.borderIB);
  45209. this.borderIB = null;
  45210. }
  45211. return true;
  45212. };
  45213. return Ellipse2DRenderCache;
  45214. })(BABYLON.ModelRenderCache);
  45215. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  45216. var Ellipse2DInstanceData = (function (_super) {
  45217. __extends(Ellipse2DInstanceData, _super);
  45218. function Ellipse2DInstanceData(partId) {
  45219. _super.call(this, partId, 1);
  45220. }
  45221. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  45222. get: function () {
  45223. return null;
  45224. },
  45225. enumerable: true,
  45226. configurable: true
  45227. });
  45228. __decorate([
  45229. BABYLON.instanceData()
  45230. ], Ellipse2DInstanceData.prototype, "properties", null);
  45231. return Ellipse2DInstanceData;
  45232. })(BABYLON.Shape2DInstanceData);
  45233. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  45234. var Ellipse2D = (function (_super) {
  45235. __extends(Ellipse2D, _super);
  45236. /**
  45237. * Create an Ellipse 2D Shape primitive
  45238. * @param settings a combination of settings, possible ones are
  45239. * - 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)
  45240. * - children: an array of direct children
  45241. * - id: a text identifier, for information purpose
  45242. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45243. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45244. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45245. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  45246. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45247. * - zOrder: override the zOrder with the specified value
  45248. * - origin: define the normalized origin point location, default [0.5;0.5]
  45249. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  45250. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  45251. * - 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)
  45252. * - 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)
  45253. * - borderThickness: the thickness of the drawn border, default is 1.
  45254. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  45255. * - 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.
  45256. * - 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.
  45257. * - 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!
  45258. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45259. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45260. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45261. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45262. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45263. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45264. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45265. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45266. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45267. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45268. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45269. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45270. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45271. */
  45272. function Ellipse2D(settings) {
  45273. // Avoid checking every time if the object exists
  45274. if (settings == null) {
  45275. settings = {};
  45276. }
  45277. _super.call(this, settings);
  45278. if (settings.size != null) {
  45279. this.size = settings.size;
  45280. }
  45281. else if (settings.width || settings.height) {
  45282. var size = new BABYLON.Size(settings.width, settings.height);
  45283. this.size = size;
  45284. }
  45285. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  45286. this.subdivisions = sub;
  45287. }
  45288. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  45289. get: function () {
  45290. if (this._actualSize) {
  45291. return this._actualSize;
  45292. }
  45293. return this.size;
  45294. },
  45295. set: function (value) {
  45296. this._actualSize = value;
  45297. },
  45298. enumerable: true,
  45299. configurable: true
  45300. });
  45301. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  45302. get: function () {
  45303. return this._subdivisions;
  45304. },
  45305. set: function (value) {
  45306. this._subdivisions = value;
  45307. },
  45308. enumerable: true,
  45309. configurable: true
  45310. });
  45311. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  45312. var w = this.size.width / 2;
  45313. var h = this.size.height / 2;
  45314. var x = intersectInfo._localPickPosition.x - w;
  45315. var y = intersectInfo._localPickPosition.y - h;
  45316. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  45317. };
  45318. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  45319. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  45320. };
  45321. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  45322. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  45323. return renderCache;
  45324. };
  45325. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45326. var renderCache = modelRenderCache;
  45327. var engine = this.owner.engine;
  45328. // Need to create WebGL resources for fill part?
  45329. if (this.fill) {
  45330. var vbSize = this.subdivisions + 1;
  45331. var vb = new Float32Array(vbSize);
  45332. for (var i = 0; i < vbSize; i++) {
  45333. vb[i] = i;
  45334. }
  45335. renderCache.fillVB = engine.createVertexBuffer(vb);
  45336. var triCount = vbSize - 1;
  45337. var ib = new Float32Array(triCount * 3);
  45338. for (var i = 0; i < triCount; i++) {
  45339. ib[i * 3 + 0] = 0;
  45340. ib[i * 3 + 2] = i + 1;
  45341. ib[i * 3 + 1] = i + 2;
  45342. }
  45343. ib[triCount * 3 - 2] = 1;
  45344. renderCache.fillIB = engine.createIndexBuffer(ib);
  45345. renderCache.fillIndicesCount = triCount * 3;
  45346. // 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
  45347. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  45348. if (ei) {
  45349. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45350. }
  45351. // Get the non instanced version
  45352. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  45353. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45354. }
  45355. // Need to create WebGL resource for border part?
  45356. if (this.border) {
  45357. var vbSize = this.subdivisions * 2;
  45358. var vb = new Float32Array(vbSize);
  45359. for (var i = 0; i < vbSize; i++) {
  45360. vb[i] = i;
  45361. }
  45362. renderCache.borderVB = engine.createVertexBuffer(vb);
  45363. var triCount = vbSize;
  45364. var rs = triCount / 2;
  45365. var ib = new Float32Array(triCount * 3);
  45366. for (var i = 0; i < rs; i++) {
  45367. var r0 = i;
  45368. var r1 = (i + 1) % rs;
  45369. ib[i * 6 + 0] = rs + r1;
  45370. ib[i * 6 + 1] = rs + r0;
  45371. ib[i * 6 + 2] = r0;
  45372. ib[i * 6 + 3] = r1;
  45373. ib[i * 6 + 4] = rs + r1;
  45374. ib[i * 6 + 5] = r0;
  45375. }
  45376. renderCache.borderIB = engine.createIndexBuffer(ib);
  45377. renderCache.borderIndicesCount = (triCount * 3);
  45378. // 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
  45379. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  45380. if (ei) {
  45381. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45382. }
  45383. // Get the non instanced version
  45384. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  45385. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45386. }
  45387. return renderCache;
  45388. };
  45389. Ellipse2D.prototype.createInstanceDataParts = function () {
  45390. var res = new Array();
  45391. if (this.border) {
  45392. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  45393. }
  45394. if (this.fill) {
  45395. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  45396. }
  45397. return res;
  45398. };
  45399. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  45400. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45401. return false;
  45402. }
  45403. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  45404. var d = part;
  45405. var size = this.actualSize;
  45406. var s = this.actualScale;
  45407. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  45408. }
  45409. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  45410. var d = part;
  45411. var size = this.actualSize;
  45412. var s = this.actualScale;
  45413. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  45414. }
  45415. return true;
  45416. };
  45417. __decorate([
  45418. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  45419. ], Ellipse2D.prototype, "actualSize", null);
  45420. __decorate([
  45421. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  45422. ], Ellipse2D.prototype, "subdivisions", null);
  45423. Ellipse2D = __decorate([
  45424. BABYLON.className("Ellipse2D")
  45425. ], Ellipse2D);
  45426. return Ellipse2D;
  45427. })(BABYLON.Shape2D);
  45428. BABYLON.Ellipse2D = Ellipse2D;
  45429. })(BABYLON || (BABYLON = {}));
  45430. var BABYLON;
  45431. (function (BABYLON) {
  45432. var Sprite2DRenderCache = (function (_super) {
  45433. __extends(Sprite2DRenderCache, _super);
  45434. function Sprite2DRenderCache() {
  45435. _super.apply(this, arguments);
  45436. this.effectsReady = false;
  45437. this.vb = null;
  45438. this.ib = null;
  45439. this.instancingAttributes = null;
  45440. this.texture = null;
  45441. this.effect = null;
  45442. this.effectInstanced = null;
  45443. }
  45444. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  45445. // Do nothing if the shader is still loading/preparing
  45446. if (!this.effectsReady) {
  45447. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  45448. return false;
  45449. }
  45450. this.effectsReady = true;
  45451. }
  45452. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  45453. var canvas = instanceInfo.owner.owner;
  45454. var engine = canvas.engine;
  45455. var cur = engine.getAlphaMode();
  45456. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  45457. engine.enableEffect(effect);
  45458. effect.setTexture("diffuseSampler", this.texture);
  45459. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  45460. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45461. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45462. }
  45463. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  45464. var pid = context.groupInfoPartData[0];
  45465. if (context.useInstancing) {
  45466. if (!this.instancingAttributes) {
  45467. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  45468. }
  45469. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  45470. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45471. canvas._addDrawCallCount(1, context.renderMode);
  45472. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  45473. engine.draw(true, 0, 6, count);
  45474. engine.unbindInstanceAttributes();
  45475. }
  45476. else {
  45477. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45478. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45479. this.setupUniforms(effect, 0, pid._partData, i);
  45480. engine.draw(true, 0, 6);
  45481. }
  45482. }
  45483. engine.setAlphaMode(cur, true);
  45484. return true;
  45485. };
  45486. Sprite2DRenderCache.prototype.dispose = function () {
  45487. if (!_super.prototype.dispose.call(this)) {
  45488. return false;
  45489. }
  45490. if (this.vb) {
  45491. this._engine._releaseBuffer(this.vb);
  45492. this.vb = null;
  45493. }
  45494. if (this.ib) {
  45495. this._engine._releaseBuffer(this.ib);
  45496. this.ib = null;
  45497. }
  45498. //if (this.texture) {
  45499. // this.texture.dispose();
  45500. // this.texture = null;
  45501. //}
  45502. this.effect = null;
  45503. this.effectInstanced = null;
  45504. return true;
  45505. };
  45506. return Sprite2DRenderCache;
  45507. })(BABYLON.ModelRenderCache);
  45508. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  45509. var Sprite2DInstanceData = (function (_super) {
  45510. __extends(Sprite2DInstanceData, _super);
  45511. function Sprite2DInstanceData(partId) {
  45512. _super.call(this, partId, 1);
  45513. }
  45514. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  45515. get: function () {
  45516. return null;
  45517. },
  45518. enumerable: true,
  45519. configurable: true
  45520. });
  45521. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  45522. get: function () {
  45523. return null;
  45524. },
  45525. enumerable: true,
  45526. configurable: true
  45527. });
  45528. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  45529. get: function () {
  45530. return null;
  45531. },
  45532. enumerable: true,
  45533. configurable: true
  45534. });
  45535. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  45536. get: function () {
  45537. return null;
  45538. },
  45539. enumerable: true,
  45540. configurable: true
  45541. });
  45542. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  45543. // 3 floats being:
  45544. // - x: frame number to display
  45545. // - y: invertY setting
  45546. // - z: alignToPixel setting
  45547. get: function () {
  45548. return null;
  45549. },
  45550. enumerable: true,
  45551. configurable: true
  45552. });
  45553. __decorate([
  45554. BABYLON.instanceData()
  45555. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  45556. __decorate([
  45557. BABYLON.instanceData()
  45558. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  45559. __decorate([
  45560. BABYLON.instanceData()
  45561. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  45562. __decorate([
  45563. BABYLON.instanceData()
  45564. ], Sprite2DInstanceData.prototype, "textureSize", null);
  45565. __decorate([
  45566. BABYLON.instanceData()
  45567. ], Sprite2DInstanceData.prototype, "properties", null);
  45568. return Sprite2DInstanceData;
  45569. })(BABYLON.InstanceDataBase);
  45570. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  45571. var Sprite2D = (function (_super) {
  45572. __extends(Sprite2D, _super);
  45573. /**
  45574. * Create an 2D Sprite primitive
  45575. * @param texture the texture that stores the sprite to render
  45576. * @param settings a combination of settings, possible ones are
  45577. * - 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)
  45578. * - children: an array of direct children
  45579. * - id a text identifier, for information purpose
  45580. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45581. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45582. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45583. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  45584. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45585. * - zOrder: override the zOrder with the specified value
  45586. * - origin: define the normalized origin point location, default [0.5;0.5]
  45587. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  45588. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  45589. * - 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.
  45590. * - invertY: if true the texture Y will be inverted, default is false.
  45591. * - 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.
  45592. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  45593. * - 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.
  45594. * - 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.
  45595. * - 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!
  45596. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45597. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45598. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45599. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45600. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45601. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45602. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45603. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45604. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45605. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45606. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45607. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45608. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45609. */
  45610. function Sprite2D(texture, settings) {
  45611. var _this = this;
  45612. if (!settings) {
  45613. settings = {};
  45614. }
  45615. _super.call(this, settings);
  45616. this.texture = texture;
  45617. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45618. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45619. this.size = settings.spriteSize;
  45620. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  45621. this.spriteScaleFactor = settings.spriteScaleFactor || new BABYLON.Vector2(1, 1);
  45622. this.spriteFrame = 0;
  45623. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  45624. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  45625. this.useAlphaFromTexture = true;
  45626. if (settings.spriteSize == null || !texture.isReady()) {
  45627. if (texture.isReady()) {
  45628. this.size = texture.getBaseSize();
  45629. }
  45630. else {
  45631. texture.onLoadObservable.add(function () {
  45632. if (settings.spriteSize == null) {
  45633. _this.size = texture.getBaseSize();
  45634. }
  45635. _this._positioningDirty();
  45636. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D.textureProperty.flagId; // To make sure the sprite is issued again for render
  45637. });
  45638. }
  45639. }
  45640. }
  45641. Object.defineProperty(Sprite2D.prototype, "texture", {
  45642. get: function () {
  45643. return this._texture;
  45644. },
  45645. set: function (value) {
  45646. this._texture = value;
  45647. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  45648. },
  45649. enumerable: true,
  45650. configurable: true
  45651. });
  45652. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  45653. get: function () {
  45654. return this._useAlphaFromTexture;
  45655. },
  45656. set: function (value) {
  45657. if (this._useAlphaFromTexture === value) {
  45658. return;
  45659. }
  45660. this._useAlphaFromTexture = value;
  45661. this._updateRenderMode();
  45662. },
  45663. enumerable: true,
  45664. configurable: true
  45665. });
  45666. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  45667. get: function () {
  45668. if (this._actualSize) {
  45669. return this._actualSize;
  45670. }
  45671. return this.size;
  45672. },
  45673. set: function (value) {
  45674. this._actualSize = value;
  45675. },
  45676. enumerable: true,
  45677. configurable: true
  45678. });
  45679. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  45680. get: function () {
  45681. return this._location;
  45682. },
  45683. set: function (value) {
  45684. this._location = value;
  45685. },
  45686. enumerable: true,
  45687. configurable: true
  45688. });
  45689. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  45690. get: function () {
  45691. return this._spriteFrame;
  45692. },
  45693. set: function (value) {
  45694. this._spriteFrame = value;
  45695. },
  45696. enumerable: true,
  45697. configurable: true
  45698. });
  45699. Object.defineProperty(Sprite2D.prototype, "invertY", {
  45700. get: function () {
  45701. return this._invertY;
  45702. },
  45703. set: function (value) {
  45704. this._invertY = value;
  45705. },
  45706. enumerable: true,
  45707. configurable: true
  45708. });
  45709. Object.defineProperty(Sprite2D.prototype, "spriteScaleFactor", {
  45710. get: function () {
  45711. return this._spriteScaleFactor;
  45712. },
  45713. set: function (value) {
  45714. this._spriteScaleFactor = value;
  45715. },
  45716. enumerable: true,
  45717. configurable: true
  45718. });
  45719. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  45720. /**
  45721. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  45722. */
  45723. get: function () {
  45724. return this._alignToPixel;
  45725. },
  45726. set: function (value) {
  45727. this._alignToPixel = value;
  45728. },
  45729. enumerable: true,
  45730. configurable: true
  45731. });
  45732. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  45733. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  45734. };
  45735. /**
  45736. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  45737. */
  45738. Sprite2D.prototype.getAnimatables = function () {
  45739. var res = new Array();
  45740. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  45741. res.push(this.texture);
  45742. }
  45743. return res;
  45744. };
  45745. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  45746. // 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
  45747. return true;
  45748. };
  45749. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  45750. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  45751. return sprite;
  45752. };
  45753. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  45754. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  45755. return renderCache;
  45756. };
  45757. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45758. var renderCache = modelRenderCache;
  45759. var engine = this.owner.engine;
  45760. var vb = new Float32Array(4);
  45761. for (var i = 0; i < 4; i++) {
  45762. vb[i] = i;
  45763. }
  45764. renderCache.vb = engine.createVertexBuffer(vb);
  45765. var ib = new Float32Array(6);
  45766. ib[0] = 0;
  45767. ib[1] = 2;
  45768. ib[2] = 1;
  45769. ib[3] = 0;
  45770. ib[4] = 3;
  45771. ib[5] = 2;
  45772. renderCache.ib = engine.createIndexBuffer(ib);
  45773. renderCache.texture = this.texture;
  45774. // 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
  45775. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  45776. if (ei) {
  45777. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45778. }
  45779. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  45780. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45781. return renderCache;
  45782. };
  45783. Sprite2D.prototype.createInstanceDataParts = function () {
  45784. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  45785. };
  45786. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  45787. Sprite2D.layoutConstructMode = true;
  45788. };
  45789. // if obj contains something, we restore the _text property
  45790. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  45791. Sprite2D.layoutConstructMode = false;
  45792. };
  45793. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  45794. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45795. return false;
  45796. }
  45797. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  45798. return false;
  45799. }
  45800. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  45801. var d = this._instanceDataParts[0];
  45802. if (Sprite2D.layoutConstructMode) {
  45803. d.topLeftUV = BABYLON.Vector2.Zero();
  45804. d.sizeUV = BABYLON.Vector2.Zero();
  45805. d.properties = BABYLON.Vector3.Zero();
  45806. d.textureSize = BABYLON.Vector2.Zero();
  45807. d.scaleFactor = BABYLON.Vector2.Zero();
  45808. }
  45809. else {
  45810. var ts = this.texture.getBaseSize();
  45811. var sl = this.spriteLocation;
  45812. var ss = this.actualSize;
  45813. var ssf = this.spriteScaleFactor;
  45814. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  45815. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  45816. d.sizeUV = suv;
  45817. d.scaleFactor = ssf;
  45818. Sprite2D._prop.x = this.spriteFrame;
  45819. Sprite2D._prop.y = this.invertY ? 1 : 0;
  45820. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  45821. d.properties = Sprite2D._prop;
  45822. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  45823. }
  45824. }
  45825. return true;
  45826. };
  45827. Sprite2D.prototype._mustUpdateInstance = function () {
  45828. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  45829. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  45830. if (res) {
  45831. this._updateRenderMode();
  45832. }
  45833. return res;
  45834. };
  45835. Sprite2D.prototype._useTextureAlpha = function () {
  45836. return this.texture != null && this.texture.hasAlpha;
  45837. };
  45838. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  45839. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  45840. };
  45841. Sprite2D.SPRITE2D_MAINPARTID = 1;
  45842. Sprite2D._prop = BABYLON.Vector3.Zero();
  45843. Sprite2D.layoutConstructMode = false;
  45844. __decorate([
  45845. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  45846. ], Sprite2D.prototype, "texture", null);
  45847. __decorate([
  45848. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.useAlphaFromTextureProperty = pi; })
  45849. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  45850. __decorate([
  45851. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  45852. ], Sprite2D.prototype, "actualSize", null);
  45853. __decorate([
  45854. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  45855. ], Sprite2D.prototype, "spriteLocation", null);
  45856. __decorate([
  45857. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  45858. ], Sprite2D.prototype, "spriteFrame", null);
  45859. __decorate([
  45860. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D.invertYProperty = pi; })
  45861. ], Sprite2D.prototype, "invertY", null);
  45862. __decorate([
  45863. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D.spriteScaleFactorProperty = pi; })
  45864. ], Sprite2D.prototype, "spriteScaleFactor", null);
  45865. Sprite2D = __decorate([
  45866. BABYLON.className("Sprite2D")
  45867. ], Sprite2D);
  45868. return Sprite2D;
  45869. })(BABYLON.RenderablePrim2D);
  45870. BABYLON.Sprite2D = Sprite2D;
  45871. })(BABYLON || (BABYLON = {}));
  45872. var BABYLON;
  45873. (function (BABYLON) {
  45874. var Text2DRenderCache = (function (_super) {
  45875. __extends(Text2DRenderCache, _super);
  45876. function Text2DRenderCache() {
  45877. _super.apply(this, arguments);
  45878. this.effectsReady = false;
  45879. this.vb = null;
  45880. this.ib = null;
  45881. this.instancingAttributes = null;
  45882. this.fontTexture = null;
  45883. this.effect = null;
  45884. this.effectInstanced = null;
  45885. }
  45886. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  45887. // Do nothing if the shader is still loading/preparing
  45888. if (!this.effectsReady) {
  45889. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  45890. return false;
  45891. }
  45892. this.effectsReady = true;
  45893. }
  45894. var canvas = instanceInfo.owner.owner;
  45895. var engine = canvas.engine;
  45896. this.fontTexture.update();
  45897. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  45898. engine.enableEffect(effect);
  45899. effect.setTexture("diffuseSampler", this.fontTexture);
  45900. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  45901. var curAlphaMode = engine.getAlphaMode();
  45902. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45903. var pid = context.groupInfoPartData[0];
  45904. if (context.useInstancing) {
  45905. if (!this.instancingAttributes) {
  45906. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  45907. }
  45908. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  45909. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45910. canvas._addDrawCallCount(1, context.renderMode);
  45911. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  45912. engine.draw(true, 0, 6, count);
  45913. engine.unbindInstanceAttributes();
  45914. }
  45915. else {
  45916. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45917. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45918. this.setupUniforms(effect, 0, pid._partData, i);
  45919. engine.draw(true, 0, 6);
  45920. }
  45921. }
  45922. engine.setAlphaMode(curAlphaMode, true);
  45923. return true;
  45924. };
  45925. Text2DRenderCache.prototype.dispose = function () {
  45926. if (!_super.prototype.dispose.call(this)) {
  45927. return false;
  45928. }
  45929. if (this.vb) {
  45930. this._engine._releaseBuffer(this.vb);
  45931. this.vb = null;
  45932. }
  45933. if (this.ib) {
  45934. this._engine._releaseBuffer(this.ib);
  45935. this.ib = null;
  45936. }
  45937. if (this.fontTexture) {
  45938. this.fontTexture.decCachedFontTextureCounter();
  45939. this.fontTexture = null;
  45940. }
  45941. this.effect = null;
  45942. this.effectInstanced = null;
  45943. return true;
  45944. };
  45945. return Text2DRenderCache;
  45946. })(BABYLON.ModelRenderCache);
  45947. BABYLON.Text2DRenderCache = Text2DRenderCache;
  45948. var Text2DInstanceData = (function (_super) {
  45949. __extends(Text2DInstanceData, _super);
  45950. function Text2DInstanceData(partId, dataElementCount) {
  45951. _super.call(this, partId, dataElementCount);
  45952. }
  45953. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  45954. get: function () {
  45955. return null;
  45956. },
  45957. enumerable: true,
  45958. configurable: true
  45959. });
  45960. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  45961. get: function () {
  45962. return null;
  45963. },
  45964. enumerable: true,
  45965. configurable: true
  45966. });
  45967. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  45968. get: function () {
  45969. return null;
  45970. },
  45971. enumerable: true,
  45972. configurable: true
  45973. });
  45974. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  45975. get: function () {
  45976. return null;
  45977. },
  45978. enumerable: true,
  45979. configurable: true
  45980. });
  45981. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  45982. get: function () {
  45983. return null;
  45984. },
  45985. enumerable: true,
  45986. configurable: true
  45987. });
  45988. __decorate([
  45989. BABYLON.instanceData()
  45990. ], Text2DInstanceData.prototype, "topLeftUV", null);
  45991. __decorate([
  45992. BABYLON.instanceData()
  45993. ], Text2DInstanceData.prototype, "sizeUV", null);
  45994. __decorate([
  45995. BABYLON.instanceData()
  45996. ], Text2DInstanceData.prototype, "textureSize", null);
  45997. __decorate([
  45998. BABYLON.instanceData()
  45999. ], Text2DInstanceData.prototype, "color", null);
  46000. __decorate([
  46001. BABYLON.instanceData()
  46002. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  46003. return Text2DInstanceData;
  46004. })(BABYLON.InstanceDataBase);
  46005. BABYLON.Text2DInstanceData = Text2DInstanceData;
  46006. var Text2D = (function (_super) {
  46007. __extends(Text2D, _super);
  46008. /**
  46009. * Create a Text primitive
  46010. * @param text the text to display
  46011. * @param settings a combination of settings, possible ones are
  46012. * - 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)
  46013. * - children: an array of direct children
  46014. * - id a text identifier, for information purpose
  46015. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  46016. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  46017. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  46018. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  46019. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  46020. * - zOrder: override the zOrder with the specified value
  46021. * - origin: define the normalized origin point location, default [0.5;0.5]
  46022. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  46023. * - 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.
  46024. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  46025. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  46026. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  46027. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  46028. * - 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.
  46029. * - 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.
  46030. * - 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!
  46031. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46032. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46033. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46034. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46035. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  46036. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  46037. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  46038. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  46039. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46040. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46041. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46042. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46043. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46044. */
  46045. function Text2D(text, settings) {
  46046. if (!settings) {
  46047. settings = {};
  46048. }
  46049. _super.call(this, settings);
  46050. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  46051. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  46052. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  46053. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  46054. this._textSize = null;
  46055. this.text = text;
  46056. this.size = (settings.size == null) ? null : settings.size;
  46057. this._updateRenderMode();
  46058. }
  46059. Object.defineProperty(Text2D.prototype, "fontName", {
  46060. get: function () {
  46061. return this._fontName;
  46062. },
  46063. set: function (value) {
  46064. if (this._fontName) {
  46065. throw new Error("Font Name change is not supported right now.");
  46066. }
  46067. this._fontName = value;
  46068. },
  46069. enumerable: true,
  46070. configurable: true
  46071. });
  46072. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  46073. get: function () {
  46074. return this._defaultFontColor;
  46075. },
  46076. set: function (value) {
  46077. this._defaultFontColor = value;
  46078. },
  46079. enumerable: true,
  46080. configurable: true
  46081. });
  46082. Object.defineProperty(Text2D.prototype, "text", {
  46083. get: function () {
  46084. return this._text;
  46085. },
  46086. set: function (value) {
  46087. this._text = value;
  46088. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  46089. this._size = null;
  46090. this._updateCharCount();
  46091. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  46092. var s = this.textSize;
  46093. },
  46094. enumerable: true,
  46095. configurable: true
  46096. });
  46097. Object.defineProperty(Text2D.prototype, "size", {
  46098. get: function () {
  46099. if (this._size != null) {
  46100. return this._size;
  46101. }
  46102. return this.textSize;
  46103. },
  46104. set: function (value) {
  46105. this._size = value;
  46106. },
  46107. enumerable: true,
  46108. configurable: true
  46109. });
  46110. Object.defineProperty(Text2D.prototype, "actualSize", {
  46111. /**
  46112. * Get the actual size of the Text2D primitive
  46113. */
  46114. get: function () {
  46115. if (this._actualSize) {
  46116. return this._actualSize;
  46117. }
  46118. return this.size;
  46119. },
  46120. enumerable: true,
  46121. configurable: true
  46122. });
  46123. Object.defineProperty(Text2D.prototype, "textSize", {
  46124. /**
  46125. * Get the area that bounds the text associated to the primitive
  46126. */
  46127. get: function () {
  46128. if (!this._textSize) {
  46129. if (this.owner) {
  46130. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  46131. if (!newSize.equals(this._textSize)) {
  46132. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  46133. this._positioningDirty();
  46134. }
  46135. this._textSize = newSize;
  46136. }
  46137. else {
  46138. return Text2D.nullSize;
  46139. }
  46140. }
  46141. return this._textSize;
  46142. },
  46143. enumerable: true,
  46144. configurable: true
  46145. });
  46146. Object.defineProperty(Text2D.prototype, "fontTexture", {
  46147. get: function () {
  46148. if (this._fontTexture) {
  46149. return this._fontTexture;
  46150. }
  46151. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  46152. return null;
  46153. }
  46154. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  46155. return this._fontTexture;
  46156. },
  46157. enumerable: true,
  46158. configurable: true
  46159. });
  46160. /**
  46161. * Dispose the primitive, remove it from its parent
  46162. */
  46163. Text2D.prototype.dispose = function () {
  46164. if (!_super.prototype.dispose.call(this)) {
  46165. return false;
  46166. }
  46167. if (this._fontTexture) {
  46168. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  46169. this._fontTexture = null;
  46170. }
  46171. return true;
  46172. };
  46173. Text2D.prototype.updateLevelBoundingInfo = function () {
  46174. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  46175. };
  46176. Text2D.prototype.levelIntersect = function (intersectInfo) {
  46177. // 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...
  46178. return true;
  46179. };
  46180. Text2D.prototype.createModelRenderCache = function (modelKey) {
  46181. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  46182. return renderCache;
  46183. };
  46184. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  46185. var renderCache = modelRenderCache;
  46186. var engine = this.owner.engine;
  46187. renderCache.fontTexture = this.fontTexture;
  46188. renderCache.fontTexture.incCachedFontTextureCounter();
  46189. var vb = new Float32Array(4);
  46190. for (var i = 0; i < 4; i++) {
  46191. vb[i] = i;
  46192. }
  46193. renderCache.vb = engine.createVertexBuffer(vb);
  46194. var ib = new Float32Array(6);
  46195. ib[0] = 0;
  46196. ib[1] = 2;
  46197. ib[2] = 1;
  46198. ib[3] = 0;
  46199. ib[4] = 3;
  46200. ib[5] = 2;
  46201. renderCache.ib = engine.createIndexBuffer(ib);
  46202. // 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
  46203. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, true);
  46204. if (ei) {
  46205. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  46206. }
  46207. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, false);
  46208. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  46209. return renderCache;
  46210. };
  46211. Text2D.prototype.createInstanceDataParts = function () {
  46212. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  46213. };
  46214. // Looks like a hack!? Yes! Because that's what it is!
  46215. // 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
  46216. // 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)
  46217. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  46218. if (!this._charCount) {
  46219. var curText = this._text;
  46220. this.text = "A";
  46221. return curText;
  46222. }
  46223. };
  46224. // if obj contains something, we restore the _text property
  46225. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  46226. if (obj !== undefined) {
  46227. this.text = obj;
  46228. }
  46229. };
  46230. Text2D.prototype.refreshInstanceDataPart = function (part) {
  46231. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  46232. return false;
  46233. }
  46234. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  46235. var d = part;
  46236. var texture = this.fontTexture;
  46237. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  46238. var ts = texture.getSize();
  46239. var offset = BABYLON.Vector2.Zero();
  46240. var lh = this.fontTexture.lineHeight;
  46241. 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
  46242. var charxpos = 0;
  46243. d.dataElementCount = this._charCount;
  46244. d.curElement = 0;
  46245. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  46246. var char = _a[_i];
  46247. // Line feed
  46248. if (char === "\n") {
  46249. offset.x = 0;
  46250. offset.y -= texture.lineHeight;
  46251. }
  46252. // Tabulation ?
  46253. if (char === "\t") {
  46254. var nextPos = charxpos + this._tabulationSize;
  46255. nextPos = nextPos - (nextPos % this._tabulationSize);
  46256. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  46257. charxpos = nextPos;
  46258. continue;
  46259. }
  46260. if (char < " ") {
  46261. continue;
  46262. }
  46263. this.updateInstanceDataPart(d, offset);
  46264. var ci = texture.getChar(char);
  46265. offset.x += ci.charWidth;
  46266. d.topLeftUV = ci.topLeftUV;
  46267. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  46268. d.sizeUV = suv;
  46269. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  46270. d.color = this.defaultFontColor;
  46271. d.superSampleFactor = superSampleFactor;
  46272. ++d.curElement;
  46273. }
  46274. }
  46275. return true;
  46276. };
  46277. Text2D.prototype._updateCharCount = function () {
  46278. var count = 0;
  46279. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  46280. var char = _a[_i];
  46281. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  46282. continue;
  46283. }
  46284. ++count;
  46285. }
  46286. this._charCount = count;
  46287. };
  46288. Text2D.prototype._useTextureAlpha = function () {
  46289. return this.fontTexture != null && this.fontTexture.hasAlpha;
  46290. };
  46291. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  46292. return true;
  46293. };
  46294. Text2D.TEXT2D_MAINPARTID = 1;
  46295. __decorate([
  46296. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  46297. ], Text2D.prototype, "fontName", null);
  46298. __decorate([
  46299. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  46300. ], Text2D.prototype, "defaultFontColor", null);
  46301. __decorate([
  46302. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  46303. ], Text2D.prototype, "text", null);
  46304. __decorate([
  46305. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  46306. ], Text2D.prototype, "size", null);
  46307. Text2D = __decorate([
  46308. BABYLON.className("Text2D")
  46309. ], Text2D);
  46310. return Text2D;
  46311. })(BABYLON.RenderablePrim2D);
  46312. BABYLON.Text2D = Text2D;
  46313. })(BABYLON || (BABYLON = {}));
  46314. var BABYLON;
  46315. (function (BABYLON) {
  46316. var Lines2DRenderCache = (function (_super) {
  46317. __extends(Lines2DRenderCache, _super);
  46318. function Lines2DRenderCache(engine, modelKey) {
  46319. _super.call(this, engine, modelKey);
  46320. this.effectsReady = false;
  46321. this.fillVB = null;
  46322. this.fillIB = null;
  46323. this.fillIndicesCount = 0;
  46324. this.instancingFillAttributes = null;
  46325. this.effectFill = null;
  46326. this.effectFillInstanced = null;
  46327. this.borderVB = null;
  46328. this.borderIB = null;
  46329. this.borderIndicesCount = 0;
  46330. this.instancingBorderAttributes = null;
  46331. this.effectBorder = null;
  46332. this.effectBorderInstanced = null;
  46333. }
  46334. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  46335. // Do nothing if the shader is still loading/preparing
  46336. if (!this.effectsReady) {
  46337. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  46338. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  46339. return false;
  46340. }
  46341. this.effectsReady = true;
  46342. }
  46343. var canvas = instanceInfo.owner.owner;
  46344. var engine = canvas.engine;
  46345. var depthFunction = 0;
  46346. if (this.effectFill && this.effectBorder) {
  46347. depthFunction = engine.getDepthFunction();
  46348. engine.setDepthFunctionToLessOrEqual();
  46349. }
  46350. var curAlphaMode = engine.getAlphaMode();
  46351. if (this.effectFill) {
  46352. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  46353. var pid = context.groupInfoPartData[partIndex];
  46354. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  46355. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  46356. }
  46357. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  46358. engine.enableEffect(effect);
  46359. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  46360. if (context.useInstancing) {
  46361. if (!this.instancingFillAttributes) {
  46362. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  46363. }
  46364. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  46365. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  46366. canvas._addDrawCallCount(1, context.renderMode);
  46367. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  46368. engine.draw(true, 0, this.fillIndicesCount, count);
  46369. engine.unbindInstanceAttributes();
  46370. }
  46371. else {
  46372. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  46373. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  46374. this.setupUniforms(effect, partIndex, pid._partData, i);
  46375. engine.draw(true, 0, this.fillIndicesCount);
  46376. }
  46377. }
  46378. }
  46379. if (this.effectBorder) {
  46380. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  46381. var pid = context.groupInfoPartData[partIndex];
  46382. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  46383. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  46384. }
  46385. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  46386. engine.enableEffect(effect);
  46387. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  46388. if (context.useInstancing) {
  46389. if (!this.instancingBorderAttributes) {
  46390. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  46391. }
  46392. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  46393. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  46394. canvas._addDrawCallCount(1, context.renderMode);
  46395. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  46396. engine.draw(true, 0, this.borderIndicesCount, count);
  46397. engine.unbindInstanceAttributes();
  46398. }
  46399. else {
  46400. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  46401. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  46402. this.setupUniforms(effect, partIndex, pid._partData, i);
  46403. engine.draw(true, 0, this.borderIndicesCount);
  46404. }
  46405. }
  46406. }
  46407. engine.setAlphaMode(curAlphaMode, true);
  46408. if (this.effectFill && this.effectBorder) {
  46409. engine.setDepthFunction(depthFunction);
  46410. }
  46411. return true;
  46412. };
  46413. Lines2DRenderCache.prototype.dispose = function () {
  46414. if (!_super.prototype.dispose.call(this)) {
  46415. return false;
  46416. }
  46417. if (this.fillVB) {
  46418. this._engine._releaseBuffer(this.fillVB);
  46419. this.fillVB = null;
  46420. }
  46421. if (this.fillIB) {
  46422. this._engine._releaseBuffer(this.fillIB);
  46423. this.fillIB = null;
  46424. }
  46425. this.effectFill = null;
  46426. this.effectFillInstanced = null;
  46427. this.effectBorder = null;
  46428. this.effectBorderInstanced = null;
  46429. if (this.borderVB) {
  46430. this._engine._releaseBuffer(this.borderVB);
  46431. this.borderVB = null;
  46432. }
  46433. if (this.borderIB) {
  46434. this._engine._releaseBuffer(this.borderIB);
  46435. this.borderIB = null;
  46436. }
  46437. return true;
  46438. };
  46439. return Lines2DRenderCache;
  46440. })(BABYLON.ModelRenderCache);
  46441. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  46442. var Lines2DInstanceData = (function (_super) {
  46443. __extends(Lines2DInstanceData, _super);
  46444. function Lines2DInstanceData(partId) {
  46445. _super.call(this, partId, 1);
  46446. }
  46447. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  46448. get: function () {
  46449. return null;
  46450. },
  46451. enumerable: true,
  46452. configurable: true
  46453. });
  46454. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  46455. get: function () {
  46456. return null;
  46457. },
  46458. enumerable: true,
  46459. configurable: true
  46460. });
  46461. __decorate([
  46462. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  46463. ], Lines2DInstanceData.prototype, "boundingMin", null);
  46464. __decorate([
  46465. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  46466. ], Lines2DInstanceData.prototype, "boundingMax", null);
  46467. return Lines2DInstanceData;
  46468. })(BABYLON.Shape2DInstanceData);
  46469. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  46470. var Lines2D = (function (_super) {
  46471. __extends(Lines2D, _super);
  46472. /**
  46473. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  46474. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  46475. * @param settings a combination of settings, possible ones are
  46476. * - 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)
  46477. * - children: an array of direct children
  46478. * - id a text identifier, for information purpose
  46479. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  46480. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  46481. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  46482. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  46483. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  46484. * - zOrder: override the zOrder with the specified value
  46485. * - origin: define the normalized origin point location, default [0.5;0.5]
  46486. * - 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.
  46487. * - 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.
  46488. * - 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.
  46489. * - 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.
  46490. * - 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)
  46491. * - 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)
  46492. * - borderThickness: the thickness of the drawn border, default is 1.
  46493. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  46494. * - 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.
  46495. * - 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.
  46496. * - 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!
  46497. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46498. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46499. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46500. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46501. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  46502. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  46503. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  46504. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  46505. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46506. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46507. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46508. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46509. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46510. */
  46511. function Lines2D(points, settings) {
  46512. if (!settings) {
  46513. settings = {};
  46514. }
  46515. _super.call(this, settings);
  46516. this._fillVB = null;
  46517. this._fillIB = null;
  46518. this._borderVB = null;
  46519. this._borderIB = null;
  46520. this._size = BABYLON.Size.Zero();
  46521. this._boundingMin = null;
  46522. this._boundingMax = null;
  46523. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  46524. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  46525. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  46526. var closed = (settings.closed == null) ? false : settings.closed;
  46527. this.points = points;
  46528. this.fillThickness = fillThickness;
  46529. this.startCap = startCap;
  46530. this.endCap = endCap;
  46531. this.closed = closed;
  46532. }
  46533. Object.defineProperty(Lines2D, "NoCap", {
  46534. /**
  46535. * No Cap to apply on the extremity
  46536. */
  46537. get: function () { return Lines2D._noCap; },
  46538. enumerable: true,
  46539. configurable: true
  46540. });
  46541. Object.defineProperty(Lines2D, "RoundCap", {
  46542. /**
  46543. * A round cap, will use the line thickness as diameter
  46544. */
  46545. get: function () { return Lines2D._roundCap; },
  46546. enumerable: true,
  46547. configurable: true
  46548. });
  46549. Object.defineProperty(Lines2D, "TriangleCap", {
  46550. /**
  46551. * Creates a triangle at the extremity.
  46552. */
  46553. get: function () { return Lines2D._triangleCap; },
  46554. enumerable: true,
  46555. configurable: true
  46556. });
  46557. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  46558. /**
  46559. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  46560. */
  46561. get: function () { return Lines2D._squareAnchorCap; },
  46562. enumerable: true,
  46563. configurable: true
  46564. });
  46565. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  46566. /**
  46567. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  46568. */
  46569. get: function () { return Lines2D._roundAnchorCap; },
  46570. enumerable: true,
  46571. configurable: true
  46572. });
  46573. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  46574. /**
  46575. * Creates a diamond anchor at the extremity.
  46576. */
  46577. get: function () { return Lines2D._diamondAnchorCap; },
  46578. enumerable: true,
  46579. configurable: true
  46580. });
  46581. Object.defineProperty(Lines2D, "ArrowCap", {
  46582. /**
  46583. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  46584. */
  46585. get: function () { return Lines2D._arrowCap; },
  46586. enumerable: true,
  46587. configurable: true
  46588. });
  46589. Object.defineProperty(Lines2D.prototype, "points", {
  46590. get: function () {
  46591. return this._points;
  46592. },
  46593. set: function (value) {
  46594. this._points = value;
  46595. this._contour = null;
  46596. this._boundingBoxDirty();
  46597. },
  46598. enumerable: true,
  46599. configurable: true
  46600. });
  46601. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  46602. get: function () {
  46603. return this._fillThickness;
  46604. },
  46605. set: function (value) {
  46606. this._fillThickness = value;
  46607. },
  46608. enumerable: true,
  46609. configurable: true
  46610. });
  46611. Object.defineProperty(Lines2D.prototype, "closed", {
  46612. get: function () {
  46613. return this._closed;
  46614. },
  46615. set: function (value) {
  46616. this._closed = value;
  46617. },
  46618. enumerable: true,
  46619. configurable: true
  46620. });
  46621. Object.defineProperty(Lines2D.prototype, "startCap", {
  46622. get: function () {
  46623. return this._startCap;
  46624. },
  46625. set: function (value) {
  46626. this._startCap = value;
  46627. },
  46628. enumerable: true,
  46629. configurable: true
  46630. });
  46631. Object.defineProperty(Lines2D.prototype, "endCap", {
  46632. get: function () {
  46633. return this._endCap;
  46634. },
  46635. set: function (value) {
  46636. this._endCap = value;
  46637. },
  46638. enumerable: true,
  46639. configurable: true
  46640. });
  46641. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  46642. var _this = this;
  46643. if (this._contour == null) {
  46644. this._computeLines2D();
  46645. }
  46646. var pl = this.points.length;
  46647. var l = this.closed ? pl + 1 : pl;
  46648. var p = intersectInfo._localPickPosition;
  46649. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  46650. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  46651. for (var i = 1; i < l; i++) {
  46652. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  46653. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  46654. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  46655. return true;
  46656. }
  46657. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  46658. return true;
  46659. }
  46660. Lines2D._prevA.x = Lines2D._curA.x;
  46661. Lines2D._prevA.y = Lines2D._curA.y;
  46662. Lines2D._prevB.x = Lines2D._curB.x;
  46663. Lines2D._prevB.y = Lines2D._curB.y;
  46664. }
  46665. var capIntersect = function (tri, points) {
  46666. var l = tri.length;
  46667. for (var i = 0; i < l; i += 3) {
  46668. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  46669. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  46670. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  46671. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  46672. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  46673. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  46674. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  46675. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  46676. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  46677. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  46678. return true;
  46679. }
  46680. }
  46681. return false;
  46682. };
  46683. if (this._startCapTriIndices) {
  46684. if (this._startCapTriIndices && capIntersect(this._startCapTriIndices, this._startCapContour)) {
  46685. return true;
  46686. }
  46687. if (this._endCapTriIndices && capIntersect(this._endCapTriIndices, this._endCapContour)) {
  46688. return true;
  46689. }
  46690. }
  46691. return false;
  46692. };
  46693. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  46694. get: function () {
  46695. if (!this._boundingMin) {
  46696. this._computeLines2D();
  46697. }
  46698. return this._boundingMin;
  46699. },
  46700. enumerable: true,
  46701. configurable: true
  46702. });
  46703. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  46704. get: function () {
  46705. if (!this._boundingMax) {
  46706. this._computeLines2D();
  46707. }
  46708. return this._boundingMax;
  46709. },
  46710. enumerable: true,
  46711. configurable: true
  46712. });
  46713. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  46714. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  46715. // Remove the BORDER category, we don't use it in the VertexShader
  46716. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  46717. if (i !== -1) {
  46718. res.splice(i, 1);
  46719. }
  46720. return res;
  46721. };
  46722. Lines2D.prototype.updateLevelBoundingInfo = function () {
  46723. if (!this._boundingMin) {
  46724. this._computeLines2D();
  46725. }
  46726. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  46727. };
  46728. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  46729. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  46730. return renderCache;
  46731. };
  46732. ///////////////////////////////////////////////////////////////////////////////////
  46733. // Methods for Lines building
  46734. Lines2D.prototype._perp = function (v, res) {
  46735. res.x = v.y;
  46736. res.y = -v.x;
  46737. };
  46738. ;
  46739. Lines2D.prototype._direction = function (a, b, res) {
  46740. a.subtractToRef(b, res);
  46741. res.normalize();
  46742. };
  46743. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  46744. a.addToRef(b, tangent);
  46745. tangent.normalize();
  46746. miter.x = -tangent.y;
  46747. miter.y = tangent.x;
  46748. Lines2D._miterTps.x = -a.y;
  46749. Lines2D._miterTps.y = a.x;
  46750. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  46751. };
  46752. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  46753. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  46754. if (d === 0)
  46755. return false;
  46756. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  46757. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  46758. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  46759. return false;
  46760. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  46761. return false;
  46762. return true;
  46763. };
  46764. Lines2D.prototype._updateMinMax = function (array, offset) {
  46765. if (offset >= array.length) {
  46766. return;
  46767. }
  46768. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  46769. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  46770. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  46771. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  46772. };
  46773. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  46774. var borderMode = borderThickness != null && !isNaN(borderThickness);
  46775. var off = index * (borderMode ? 8 : 4);
  46776. // 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)
  46777. if (off >= array.length) {
  46778. return;
  46779. }
  46780. // Store start/end normal, we need it for the cap construction
  46781. if (index === 0) {
  46782. this._perp(n, Lines2D._startDir);
  46783. }
  46784. else if (index === max - 1) {
  46785. this._perp(n, Lines2D._endDir);
  46786. Lines2D._endDir.x *= -1;
  46787. Lines2D._endDir.y *= -1;
  46788. }
  46789. var swap = false;
  46790. array[off + 0] = p.x + n.x * halfThickness;
  46791. array[off + 1] = p.y + n.y * halfThickness;
  46792. array[off + 2] = p.x + n.x * -halfThickness;
  46793. array[off + 3] = p.y + n.y * -halfThickness;
  46794. this._updateMinMax(array, off);
  46795. this._updateMinMax(array, off + 2);
  46796. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  46797. // 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
  46798. if (detectFlip !== undefined) {
  46799. // Flip if intersect
  46800. var flipOff = detectFlip * (borderMode ? 8 : 4);
  46801. 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])) {
  46802. swap = true;
  46803. var tps = array[off + 0];
  46804. array[off + 0] = array[off + 2];
  46805. array[off + 2] = tps;
  46806. tps = array[off + 1];
  46807. array[off + 1] = array[off + 3];
  46808. array[off + 3] = tps;
  46809. }
  46810. }
  46811. if (borderMode) {
  46812. var t = halfThickness + borderThickness;
  46813. array[off + 4] = p.x + n.x * (swap ? -t : t);
  46814. array[off + 5] = p.y + n.y * (swap ? -t : t);
  46815. array[off + 6] = p.x + n.x * (swap ? t : -t);
  46816. array[off + 7] = p.y + n.y * (swap ? t : -t);
  46817. this._updateMinMax(array, off + 4);
  46818. this._updateMinMax(array, off + 6);
  46819. }
  46820. if (contour) {
  46821. off += borderMode ? 4 : 0;
  46822. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  46823. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  46824. }
  46825. };
  46826. Lines2D.prototype._getCapSize = function (type, border) {
  46827. if (border === void 0) { border = false; }
  46828. var sd = Lines2D._roundCapSubDiv;
  46829. // If no array given, we call this to get the size
  46830. var vbsize = 0, ibsize = 0;
  46831. switch (type) {
  46832. case Lines2D.NoCap:
  46833. {
  46834. // If the line is not close and we're computing border, we add the size to generate the edge border
  46835. if (!this.closed && border) {
  46836. vbsize = 4;
  46837. ibsize = 6;
  46838. }
  46839. else {
  46840. vbsize = ibsize = 0;
  46841. }
  46842. break;
  46843. }
  46844. case Lines2D.RoundCap:
  46845. {
  46846. if (border) {
  46847. vbsize = sd;
  46848. ibsize = (sd - 2) * 3;
  46849. }
  46850. else {
  46851. vbsize = (sd / 2) + 1;
  46852. ibsize = (sd / 2) * 3;
  46853. }
  46854. break;
  46855. }
  46856. case Lines2D.ArrowCap:
  46857. {
  46858. if (border) {
  46859. vbsize = 12;
  46860. ibsize = 24;
  46861. }
  46862. else {
  46863. vbsize = 3;
  46864. ibsize = 3;
  46865. }
  46866. break;
  46867. }
  46868. case Lines2D.TriangleCap:
  46869. {
  46870. if (border) {
  46871. vbsize = 6;
  46872. ibsize = 12;
  46873. }
  46874. else {
  46875. vbsize = 3;
  46876. ibsize = 3;
  46877. }
  46878. break;
  46879. }
  46880. case Lines2D.DiamondAnchorCap:
  46881. {
  46882. if (border) {
  46883. vbsize = 10;
  46884. ibsize = 24;
  46885. }
  46886. else {
  46887. vbsize = 5;
  46888. ibsize = 9;
  46889. }
  46890. break;
  46891. }
  46892. case Lines2D.SquareAnchorCap:
  46893. {
  46894. if (border) {
  46895. vbsize = 12;
  46896. ibsize = 30;
  46897. }
  46898. else {
  46899. vbsize = 4;
  46900. ibsize = 6;
  46901. }
  46902. break;
  46903. }
  46904. case Lines2D.RoundAnchorCap:
  46905. {
  46906. if (border) {
  46907. vbsize = sd * 2;
  46908. ibsize = (sd - 1) * 6;
  46909. }
  46910. else {
  46911. vbsize = sd + 1;
  46912. ibsize = (sd + 1) * 3;
  46913. }
  46914. break;
  46915. }
  46916. }
  46917. return { vbsize: vbsize * 2, ibsize: ibsize };
  46918. };
  46919. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  46920. var c = Math.cos(rotation);
  46921. var s = Math.sin(rotation);
  46922. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  46923. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  46924. var offset = baseOffset + (index * 2);
  46925. vb[offset + 0] = Lines2D._tpsV.x;
  46926. vb[offset + 1] = Lines2D._tpsV.y;
  46927. if (contour) {
  46928. contour.push(Lines2D._tpsV.x);
  46929. contour.push(Lines2D._tpsV.y);
  46930. }
  46931. this._updateMinMax(vb, offset);
  46932. return (baseOffset + index * 2) / 2;
  46933. };
  46934. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  46935. ib[baseOffset + index] = vertexIndex;
  46936. };
  46937. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  46938. // 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
  46939. var sd = Lines2D._roundCapSubDiv;
  46940. var dir = new BABYLON.Vector2(1, 0);
  46941. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  46942. var ht = thickness / 2;
  46943. var t = thickness;
  46944. var borderMode = borderThickness != null;
  46945. var bt = borderThickness;
  46946. switch (type) {
  46947. case Lines2D.NoCap:
  46948. if (borderMode && !this.closed) {
  46949. var vi = 0;
  46950. var ii = 0;
  46951. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  46952. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  46953. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  46954. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  46955. this._storeIndex(ib, ibi, ii++, v1);
  46956. this._storeIndex(ib, ibi, ii++, v2);
  46957. this._storeIndex(ib, ibi, ii++, v3);
  46958. this._storeIndex(ib, ibi, ii++, v1);
  46959. this._storeIndex(ib, ibi, ii++, v3);
  46960. this._storeIndex(ib, ibi, ii++, v4);
  46961. }
  46962. break;
  46963. case Lines2D.ArrowCap:
  46964. ht *= 2;
  46965. case Lines2D.TriangleCap:
  46966. {
  46967. if (borderMode) {
  46968. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  46969. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  46970. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  46971. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  46972. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  46973. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  46974. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  46975. var ii = 0;
  46976. this._storeIndex(ib, ibi, ii++, v1);
  46977. this._storeIndex(ib, ibi, ii++, v4);
  46978. this._storeIndex(ib, ibi, ii++, v5);
  46979. this._storeIndex(ib, ibi, ii++, v1);
  46980. this._storeIndex(ib, ibi, ii++, v5);
  46981. this._storeIndex(ib, ibi, ii++, v2);
  46982. this._storeIndex(ib, ibi, ii++, v6);
  46983. this._storeIndex(ib, ibi, ii++, v3);
  46984. this._storeIndex(ib, ibi, ii++, v2);
  46985. this._storeIndex(ib, ibi, ii++, v6);
  46986. this._storeIndex(ib, ibi, ii++, v2);
  46987. this._storeIndex(ib, ibi, ii++, v5);
  46988. if (type === Lines2D.ArrowCap) {
  46989. var rht = thickness / 2;
  46990. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  46991. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  46992. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  46993. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  46994. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  46995. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  46996. this._storeIndex(ib, ibi, ii++, v7);
  46997. this._storeIndex(ib, ibi, ii++, v8);
  46998. this._storeIndex(ib, ibi, ii++, v9);
  46999. this._storeIndex(ib, ibi, ii++, v7);
  47000. this._storeIndex(ib, ibi, ii++, v9);
  47001. this._storeIndex(ib, ibi, ii++, v4);
  47002. this._storeIndex(ib, ibi, ii++, v10);
  47003. this._storeIndex(ib, ibi, ii++, v12);
  47004. this._storeIndex(ib, ibi, ii++, v11);
  47005. this._storeIndex(ib, ibi, ii++, v10);
  47006. this._storeIndex(ib, ibi, ii++, v6);
  47007. this._storeIndex(ib, ibi, ii++, v12);
  47008. }
  47009. }
  47010. else {
  47011. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  47012. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  47013. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  47014. this._storeIndex(ib, ibi, 0, v1);
  47015. this._storeIndex(ib, ibi, 1, v2);
  47016. this._storeIndex(ib, ibi, 2, v3);
  47017. }
  47018. break;
  47019. }
  47020. case Lines2D.RoundCap:
  47021. {
  47022. if (borderMode) {
  47023. var curA = -Math.PI / 2;
  47024. var incA = Math.PI / (sd / 2 - 1);
  47025. var ii = 0;
  47026. for (var i = 0; i < (sd / 2); i++) {
  47027. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  47028. 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);
  47029. if (i > 0) {
  47030. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47031. this._storeIndex(ib, ibi, ii++, v2 - 2);
  47032. this._storeIndex(ib, ibi, ii++, v2);
  47033. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47034. this._storeIndex(ib, ibi, ii++, v2);
  47035. this._storeIndex(ib, ibi, ii++, v1);
  47036. }
  47037. curA += incA;
  47038. }
  47039. }
  47040. else {
  47041. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  47042. var curA = -Math.PI / 2;
  47043. var incA = Math.PI / (sd / 2 - 1);
  47044. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  47045. curA += incA;
  47046. for (var i = 1; i < (sd / 2); i++) {
  47047. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  47048. this._storeIndex(ib, ibi, i * 3 + 0, c);
  47049. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  47050. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  47051. curA += incA;
  47052. }
  47053. }
  47054. break;
  47055. }
  47056. case Lines2D.SquareAnchorCap:
  47057. {
  47058. var vi = 0;
  47059. var c = borderMode ? null : contour;
  47060. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  47061. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  47062. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  47063. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  47064. if (borderMode) {
  47065. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  47066. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  47067. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  47068. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  47069. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  47070. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  47071. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  47072. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  47073. var ii = 0;
  47074. this._storeIndex(ib, ibi, ii++, v6);
  47075. this._storeIndex(ib, ibi, ii++, v1);
  47076. this._storeIndex(ib, ibi, ii++, v5);
  47077. this._storeIndex(ib, ibi, ii++, v6);
  47078. this._storeIndex(ib, ibi, ii++, v7);
  47079. this._storeIndex(ib, ibi, ii++, v1);
  47080. this._storeIndex(ib, ibi, ii++, v1);
  47081. this._storeIndex(ib, ibi, ii++, v7);
  47082. this._storeIndex(ib, ibi, ii++, v8);
  47083. this._storeIndex(ib, ibi, ii++, v1);
  47084. this._storeIndex(ib, ibi, ii++, v8);
  47085. this._storeIndex(ib, ibi, ii++, v2);
  47086. this._storeIndex(ib, ibi, ii++, v2);
  47087. this._storeIndex(ib, ibi, ii++, v8);
  47088. this._storeIndex(ib, ibi, ii++, v9);
  47089. this._storeIndex(ib, ibi, ii++, v2);
  47090. this._storeIndex(ib, ibi, ii++, v9);
  47091. this._storeIndex(ib, ibi, ii++, v3);
  47092. this._storeIndex(ib, ibi, ii++, v3);
  47093. this._storeIndex(ib, ibi, ii++, v9);
  47094. this._storeIndex(ib, ibi, ii++, v10);
  47095. this._storeIndex(ib, ibi, ii++, v3);
  47096. this._storeIndex(ib, ibi, ii++, v10);
  47097. this._storeIndex(ib, ibi, ii++, v4);
  47098. this._storeIndex(ib, ibi, ii++, v10);
  47099. this._storeIndex(ib, ibi, ii++, v11);
  47100. this._storeIndex(ib, ibi, ii++, v4);
  47101. this._storeIndex(ib, ibi, ii++, v11);
  47102. this._storeIndex(ib, ibi, ii++, v12);
  47103. this._storeIndex(ib, ibi, ii++, v4);
  47104. }
  47105. else {
  47106. this._storeIndex(ib, ibi, 0, v1);
  47107. this._storeIndex(ib, ibi, 1, v2);
  47108. this._storeIndex(ib, ibi, 2, v3);
  47109. this._storeIndex(ib, ibi, 3, v1);
  47110. this._storeIndex(ib, ibi, 4, v3);
  47111. this._storeIndex(ib, ibi, 5, v4);
  47112. }
  47113. break;
  47114. }
  47115. case Lines2D.RoundAnchorCap:
  47116. {
  47117. var cpos = Math.sqrt(t * t - ht * ht);
  47118. var center = new BABYLON.Vector2(cpos, 0);
  47119. var curA = BABYLON.Tools.ToRadians(-150);
  47120. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  47121. if (borderMode) {
  47122. var ii = 0;
  47123. for (var i = 0; i < sd; i++) {
  47124. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  47125. 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);
  47126. if (i > 0) {
  47127. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47128. this._storeIndex(ib, ibi, ii++, v2 - 2);
  47129. this._storeIndex(ib, ibi, ii++, v2);
  47130. this._storeIndex(ib, ibi, ii++, v1 - 2);
  47131. this._storeIndex(ib, ibi, ii++, v2);
  47132. this._storeIndex(ib, ibi, ii++, v1);
  47133. }
  47134. curA += incA;
  47135. }
  47136. }
  47137. else {
  47138. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  47139. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  47140. curA += incA;
  47141. for (var i = 1; i < sd; i++) {
  47142. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  47143. this._storeIndex(ib, ibi, i * 3 + 0, c);
  47144. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  47145. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  47146. curA += incA;
  47147. }
  47148. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  47149. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  47150. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  47151. }
  47152. break;
  47153. }
  47154. case Lines2D.DiamondAnchorCap:
  47155. {
  47156. var vi = 0;
  47157. var c = borderMode ? null : contour;
  47158. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  47159. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  47160. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  47161. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  47162. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  47163. if (borderMode) {
  47164. var f = Math.sqrt(bt * bt * 2);
  47165. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  47166. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  47167. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  47168. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  47169. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  47170. var ii = 0;
  47171. this._storeIndex(ib, ibi, ii++, v6);
  47172. this._storeIndex(ib, ibi, ii++, v7);
  47173. this._storeIndex(ib, ibi, ii++, v1);
  47174. this._storeIndex(ib, ibi, ii++, v1);
  47175. this._storeIndex(ib, ibi, ii++, v7);
  47176. this._storeIndex(ib, ibi, ii++, v2);
  47177. this._storeIndex(ib, ibi, ii++, v2);
  47178. this._storeIndex(ib, ibi, ii++, v7);
  47179. this._storeIndex(ib, ibi, ii++, v8);
  47180. this._storeIndex(ib, ibi, ii++, v2);
  47181. this._storeIndex(ib, ibi, ii++, v8);
  47182. this._storeIndex(ib, ibi, ii++, v3);
  47183. this._storeIndex(ib, ibi, ii++, v3);
  47184. this._storeIndex(ib, ibi, ii++, v8);
  47185. this._storeIndex(ib, ibi, ii++, v9);
  47186. this._storeIndex(ib, ibi, ii++, v3);
  47187. this._storeIndex(ib, ibi, ii++, v9);
  47188. this._storeIndex(ib, ibi, ii++, v4);
  47189. this._storeIndex(ib, ibi, ii++, v4);
  47190. this._storeIndex(ib, ibi, ii++, v9);
  47191. this._storeIndex(ib, ibi, ii++, v10);
  47192. this._storeIndex(ib, ibi, ii++, v4);
  47193. this._storeIndex(ib, ibi, ii++, v10);
  47194. this._storeIndex(ib, ibi, ii++, v5);
  47195. }
  47196. else {
  47197. this._storeIndex(ib, ibi, 0, v1);
  47198. this._storeIndex(ib, ibi, 1, v2);
  47199. this._storeIndex(ib, ibi, 2, v3);
  47200. this._storeIndex(ib, ibi, 3, v1);
  47201. this._storeIndex(ib, ibi, 4, v3);
  47202. this._storeIndex(ib, ibi, 5, v5);
  47203. this._storeIndex(ib, ibi, 6, v5);
  47204. this._storeIndex(ib, ibi, 7, v3);
  47205. this._storeIndex(ib, ibi, 8, v4);
  47206. }
  47207. break;
  47208. }
  47209. }
  47210. return null;
  47211. };
  47212. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  47213. var lineA = BABYLON.Vector2.Zero();
  47214. var lineB = BABYLON.Vector2.Zero();
  47215. var tangent = BABYLON.Vector2.Zero();
  47216. var miter = BABYLON.Vector2.Zero();
  47217. var curNormal = null;
  47218. if (this.closed) {
  47219. this.points.push(this.points[0]);
  47220. }
  47221. var total = this.points.length;
  47222. for (var i = 1; i < total; i++) {
  47223. var last = this.points[i - 1];
  47224. var cur = this.points[i];
  47225. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  47226. this._direction(cur, last, lineA);
  47227. if (!curNormal) {
  47228. curNormal = BABYLON.Vector2.Zero();
  47229. this._perp(lineA, curNormal);
  47230. }
  47231. if (i === 1) {
  47232. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  47233. }
  47234. if (!next) {
  47235. this._perp(lineA, curNormal);
  47236. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  47237. }
  47238. else {
  47239. this._direction(next, cur, lineB);
  47240. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  47241. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  47242. }
  47243. }
  47244. if (this.points.length > 2 && this.closed) {
  47245. var last2 = this.points[total - 2];
  47246. var cur2 = this.points[0];
  47247. var next2 = this.points[1];
  47248. this._direction(cur2, last2, lineA);
  47249. this._direction(next2, cur2, lineB);
  47250. this._perp(lineA, curNormal);
  47251. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  47252. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  47253. // Patch contour
  47254. if (contour) {
  47255. var off = (bt == null) ? 0 : 4;
  47256. contour[0].x = vb[off + 0];
  47257. contour[0].y = vb[off + 1];
  47258. contour[1].x = vb[off + 2];
  47259. contour[1].y = vb[off + 3];
  47260. }
  47261. }
  47262. // Remove the point we added at the beginning
  47263. if (this.closed) {
  47264. this.points.splice(total - 1);
  47265. }
  47266. };
  47267. // Methods for Lines building
  47268. ///////////////////////////////////////////////////////////////////////////////////
  47269. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  47270. var renderCache = modelRenderCache;
  47271. var engine = this.owner.engine;
  47272. if (this._fillVB === null) {
  47273. this._computeLines2D();
  47274. }
  47275. // Need to create WebGL resources for fill part?
  47276. if (this.fill) {
  47277. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  47278. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  47279. renderCache.fillIndicesCount = this._fillIB.length;
  47280. // 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
  47281. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  47282. if (ei) {
  47283. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  47284. }
  47285. // Get the non instanced version
  47286. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  47287. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  47288. }
  47289. // Need to create WebGL resources for border part?
  47290. if (this.border) {
  47291. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  47292. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  47293. renderCache.borderIndicesCount = this._borderIB.length;
  47294. // 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
  47295. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  47296. if (ei) {
  47297. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  47298. }
  47299. // Get the non instanced version
  47300. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  47301. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  47302. }
  47303. this._fillVB = null;
  47304. this._fillIB = null;
  47305. this._borderVB = null;
  47306. this._borderIB = null;
  47307. return renderCache;
  47308. };
  47309. Lines2D.prototype._computeLines2D = function () {
  47310. // Init min/max because their being computed here
  47311. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  47312. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  47313. var contour = new Array();
  47314. var startCapContour = new Array();
  47315. var endCapContour = new Array();
  47316. // Need to create WebGL resources for fill part?
  47317. if (this.fill) {
  47318. var startCapInfo = this._getCapSize(this.startCap);
  47319. var endCapInfo = this._getCapSize(this.endCap);
  47320. var count = this.points.length;
  47321. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  47322. this._fillVB = new Float32Array(vbSize);
  47323. var vb = this._fillVB;
  47324. var ht = this.fillThickness / 2;
  47325. var total = this.points.length;
  47326. this._buildLine(vb, this.border ? null : contour, ht);
  47327. var max = total * 2;
  47328. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  47329. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  47330. var ib = this._fillIB;
  47331. for (var i = 0; i < triCount; i += 2) {
  47332. ib[i * 3 + 0] = i + 0;
  47333. ib[i * 3 + 1] = i + 1;
  47334. ib[i * 3 + 2] = (i + 2) % max;
  47335. ib[i * 3 + 3] = i + 1;
  47336. ib[i * 3 + 4] = (i + 3) % max;
  47337. ib[i * 3 + 5] = (i + 2) % max;
  47338. }
  47339. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  47340. 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);
  47341. }
  47342. // Need to create WebGL resources for border part?
  47343. if (this.border) {
  47344. var startCapInfo = this._getCapSize(this.startCap, true);
  47345. var endCapInfo = this._getCapSize(this.endCap, true);
  47346. var count = this.points.length;
  47347. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  47348. this._borderVB = new Float32Array(vbSize);
  47349. var vb = this._borderVB;
  47350. var ht = this.fillThickness / 2;
  47351. var bt = this.borderThickness;
  47352. var total = this.points.length;
  47353. this._buildLine(vb, contour, ht, bt);
  47354. var max = total * 2 * 2;
  47355. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  47356. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  47357. var ib = this._borderIB;
  47358. for (var i = 0; i < triCount; i += 4) {
  47359. ib[i * 3 + 0] = i + 0;
  47360. ib[i * 3 + 1] = i + 2;
  47361. ib[i * 3 + 2] = (i + 6) % max;
  47362. ib[i * 3 + 3] = i + 0;
  47363. ib[i * 3 + 4] = (i + 6) % max;
  47364. ib[i * 3 + 5] = (i + 4) % max;
  47365. ib[i * 3 + 6] = i + 3;
  47366. ib[i * 3 + 7] = i + 1;
  47367. ib[i * 3 + 8] = (i + 5) % max;
  47368. ib[i * 3 + 9] = i + 3;
  47369. ib[i * 3 + 10] = (i + 5) % max;
  47370. ib[i * 3 + 11] = (i + 7) % max;
  47371. }
  47372. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  47373. 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);
  47374. }
  47375. this._contour = contour;
  47376. if (startCapContour.length > 0) {
  47377. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  47378. this._startCapTriIndices = startCapTri;
  47379. this._startCapContour = startCapContour;
  47380. }
  47381. else {
  47382. this._startCapTriIndices = null;
  47383. this._startCapContour = null;
  47384. }
  47385. if (endCapContour.length > 0) {
  47386. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  47387. this._endCapContour = endCapContour;
  47388. this._endCapTriIndices = endCapTri;
  47389. }
  47390. else {
  47391. this._endCapContour = null;
  47392. this._endCapTriIndices = null;
  47393. }
  47394. var bs = this._boundingMax.subtract(this._boundingMin);
  47395. this._size.width = bs.x;
  47396. this._size.height = bs.y;
  47397. };
  47398. Object.defineProperty(Lines2D.prototype, "size", {
  47399. get: function () {
  47400. if (this._size == null) {
  47401. this._computeLines2D();
  47402. }
  47403. return this._size;
  47404. },
  47405. enumerable: true,
  47406. configurable: true
  47407. });
  47408. Lines2D.prototype.createInstanceDataParts = function () {
  47409. var res = new Array();
  47410. if (this.border) {
  47411. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  47412. }
  47413. if (this.fill) {
  47414. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  47415. }
  47416. return res;
  47417. };
  47418. Lines2D.prototype.applyActualScaleOnTransform = function () {
  47419. return true;
  47420. };
  47421. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  47422. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  47423. return false;
  47424. }
  47425. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  47426. var d = part;
  47427. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  47428. d.boundingMin = this.boundingMin;
  47429. d.boundingMax = this.boundingMax;
  47430. }
  47431. }
  47432. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  47433. var d = part;
  47434. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  47435. d.boundingMin = this.boundingMin;
  47436. d.boundingMax = this.boundingMax;
  47437. }
  47438. }
  47439. return true;
  47440. };
  47441. Lines2D._prevA = BABYLON.Vector2.Zero();
  47442. Lines2D._prevB = BABYLON.Vector2.Zero();
  47443. Lines2D._curA = BABYLON.Vector2.Zero();
  47444. Lines2D._curB = BABYLON.Vector2.Zero();
  47445. Lines2D._miterTps = BABYLON.Vector2.Zero();
  47446. Lines2D._startDir = BABYLON.Vector2.Zero();
  47447. Lines2D._endDir = BABYLON.Vector2.Zero();
  47448. Lines2D._tpsV = BABYLON.Vector2.Zero();
  47449. Lines2D._noCap = 0;
  47450. Lines2D._roundCap = 1;
  47451. Lines2D._triangleCap = 2;
  47452. Lines2D._squareAnchorCap = 3;
  47453. Lines2D._roundAnchorCap = 4;
  47454. Lines2D._diamondAnchorCap = 5;
  47455. Lines2D._arrowCap = 6;
  47456. Lines2D._roundCapSubDiv = 36;
  47457. __decorate([
  47458. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  47459. ], Lines2D.prototype, "points", null);
  47460. __decorate([
  47461. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  47462. ], Lines2D.prototype, "fillThickness", null);
  47463. __decorate([
  47464. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  47465. ], Lines2D.prototype, "closed", null);
  47466. __decorate([
  47467. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  47468. ], Lines2D.prototype, "startCap", null);
  47469. __decorate([
  47470. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  47471. ], Lines2D.prototype, "endCap", null);
  47472. Lines2D = __decorate([
  47473. BABYLON.className("Lines2D")
  47474. ], Lines2D);
  47475. return Lines2D;
  47476. })(BABYLON.Shape2D);
  47477. BABYLON.Lines2D = Lines2D;
  47478. })(BABYLON || (BABYLON = {}));
  47479. var BABYLON;
  47480. (function (BABYLON) {
  47481. // This class contains data that lifetime is bounding to the Babylon Engine object
  47482. var Canvas2DEngineBoundData = (function () {
  47483. function Canvas2DEngineBoundData() {
  47484. this._modelCache = new BABYLON.StringDictionary();
  47485. }
  47486. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  47487. return this._modelCache.getOrAddWithFactory(key, factory);
  47488. };
  47489. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  47490. if (!modelRenderCache.isDisposed) {
  47491. return false;
  47492. }
  47493. this._modelCache.remove(modelRenderCache.modelKey);
  47494. return true;
  47495. };
  47496. return Canvas2DEngineBoundData;
  47497. })();
  47498. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  47499. var Canvas2D = (function (_super) {
  47500. __extends(Canvas2D, _super);
  47501. function Canvas2D(scene, settings) {
  47502. var _this = this;
  47503. _super.call(this, settings);
  47504. /**
  47505. * 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.
  47506. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  47507. */
  47508. this.worldSpaceToNodeLocal = function (worldPos) {
  47509. var node = _this._worldSpaceNode;
  47510. if (!node) {
  47511. return;
  47512. }
  47513. var mtx = node.getWorldMatrix().clone();
  47514. mtx.invert();
  47515. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  47516. var res = new BABYLON.Vector2(v.x, v.y);
  47517. var size = _this.actualSize;
  47518. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  47519. res.y += size.height * 0.5;
  47520. return res;
  47521. };
  47522. /**
  47523. * 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
  47524. */
  47525. this.worldSpaceCacheChanged = function () {
  47526. var plane = _this.worldSpaceCanvasNode;
  47527. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  47528. vd.uvs = new Float32Array(8);
  47529. var material = plane.material;
  47530. var tex = _this._renderableData._cacheTexture;
  47531. if (material.diffuseTexture !== tex) {
  47532. material.diffuseTexture = tex;
  47533. tex.hasAlpha = true;
  47534. }
  47535. var nodeuv = _this._renderableData._cacheNodeUVs;
  47536. for (var i = 0; i < 4; i++) {
  47537. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  47538. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  47539. }
  47540. vd.applyToMesh(plane);
  47541. };
  47542. this._notifDebugMode = false;
  47543. this._mapCounter = 0;
  47544. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  47545. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  47546. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  47547. this._groupRenderCounter = new BABYLON.PerfCounter();
  47548. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  47549. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  47550. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  47551. this._updateLayoutCounter = new BABYLON.PerfCounter();
  47552. this._updatePositioningCounter = new BABYLON.PerfCounter();
  47553. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  47554. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  47555. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  47556. this._cachedCanvasGroup = null;
  47557. this._profileInfoText = null;
  47558. BABYLON.Prim2DBase._isCanvasInit = false;
  47559. if (!settings) {
  47560. settings = {};
  47561. }
  47562. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  47563. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  47564. this._background.zOrder = 1.0;
  47565. this._background.isPickable = false;
  47566. this._background.origin = BABYLON.Vector2.Zero();
  47567. this._background.levelVisible = false;
  47568. if (settings.backgroundRoundRadius != null) {
  47569. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  47570. }
  47571. if (settings.backgroundBorder != null) {
  47572. if (typeof (settings.backgroundBorder) === "string") {
  47573. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  47574. }
  47575. else {
  47576. this.backgroundBorder = settings.backgroundBorder;
  47577. }
  47578. }
  47579. if (settings.backgroundBorderThickNess != null) {
  47580. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  47581. }
  47582. if (settings.backgroundFill != null) {
  47583. if (typeof (settings.backgroundFill) === "string") {
  47584. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  47585. }
  47586. else {
  47587. this.backgroundFill = settings.backgroundFill;
  47588. }
  47589. }
  47590. // Put a handler to resize the background whenever the canvas is resizing
  47591. this.propertyChanged.add(function (e, s) {
  47592. _this._background.size = _this.size;
  47593. }, BABYLON.Group2D.sizeProperty.flagId);
  47594. this._background._patchHierarchy(this);
  47595. }
  47596. var engine = scene.getEngine();
  47597. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  47598. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  47599. this._capturedPointers = new BABYLON.StringDictionary();
  47600. this._pickStartingPosition = BABYLON.Vector2.Zero();
  47601. this._hierarchyLevelMaxSiblingCount = 50;
  47602. this._hierarchyDepth = 0;
  47603. this._zOrder = 0;
  47604. this._zMax = 1;
  47605. this._scene = scene;
  47606. this._engine = engine;
  47607. this._renderingSize = new BABYLON.Size(0, 0);
  47608. this._designSize = settings.designSize || null;
  47609. this._designUseHorizAxis = settings.designUseHorizAxis === true;
  47610. this._trackedGroups = new Array();
  47611. this._maxAdaptiveWorldSpaceCanvasSize = null;
  47612. this._groupCacheMaps = new BABYLON.StringDictionary();
  47613. this._patchHierarchy(this);
  47614. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  47615. this._fitRenderingDevice = !settings.size;
  47616. if (!settings.size) {
  47617. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  47618. }
  47619. // Register scene dispose to also dispose the canvas when it'll happens
  47620. scene.onDisposeObservable.add(function (d, s) {
  47621. _this.dispose();
  47622. });
  47623. if (this._isScreenSpace) {
  47624. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  47625. _this._engine.clear(null, false, true, true);
  47626. _this._render();
  47627. });
  47628. }
  47629. else {
  47630. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  47631. _this._render();
  47632. });
  47633. }
  47634. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  47635. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  47636. this._setupInteraction(enableInteraction);
  47637. }
  47638. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  47639. get: function () {
  47640. return this._drawCallsOpaqueCounter;
  47641. },
  47642. enumerable: true,
  47643. configurable: true
  47644. });
  47645. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  47646. get: function () {
  47647. return this._drawCallsAlphaTestCounter;
  47648. },
  47649. enumerable: true,
  47650. configurable: true
  47651. });
  47652. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  47653. get: function () {
  47654. return this._drawCallsTransparentCounter;
  47655. },
  47656. enumerable: true,
  47657. configurable: true
  47658. });
  47659. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  47660. get: function () {
  47661. return this._groupRenderCounter;
  47662. },
  47663. enumerable: true,
  47664. configurable: true
  47665. });
  47666. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  47667. get: function () {
  47668. return this._updateTransparentDataCounter;
  47669. },
  47670. enumerable: true,
  47671. configurable: true
  47672. });
  47673. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  47674. get: function () {
  47675. return this._cachedGroupRenderCounter;
  47676. },
  47677. enumerable: true,
  47678. configurable: true
  47679. });
  47680. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  47681. get: function () {
  47682. return this._updateCachedStateCounter;
  47683. },
  47684. enumerable: true,
  47685. configurable: true
  47686. });
  47687. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  47688. get: function () {
  47689. return this._updateLayoutCounter;
  47690. },
  47691. enumerable: true,
  47692. configurable: true
  47693. });
  47694. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  47695. get: function () {
  47696. return this._updatePositioningCounter;
  47697. },
  47698. enumerable: true,
  47699. configurable: true
  47700. });
  47701. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  47702. get: function () {
  47703. return this._updateLocalTransformCounter;
  47704. },
  47705. enumerable: true,
  47706. configurable: true
  47707. });
  47708. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  47709. get: function () {
  47710. return this._updateGlobalTransformCounter;
  47711. },
  47712. enumerable: true,
  47713. configurable: true
  47714. });
  47715. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  47716. get: function () {
  47717. return this._boundingInfoRecomputeCounter;
  47718. },
  47719. enumerable: true,
  47720. configurable: true
  47721. });
  47722. Canvas2D.prototype._canvasPreInit = function (settings) {
  47723. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  47724. this._cachingStrategy = cachingStrategy;
  47725. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  47726. };
  47727. Canvas2D.prototype._setupInteraction = function (enable) {
  47728. var _this = this;
  47729. // No change detection
  47730. if (enable === this._interactionEnabled) {
  47731. return;
  47732. }
  47733. // Set the new state
  47734. this._interactionEnabled = enable;
  47735. // ScreenSpace mode
  47736. if (this._isScreenSpace) {
  47737. // Disable interaction
  47738. if (!enable) {
  47739. if (this._scenePrePointerObserver) {
  47740. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  47741. this._scenePrePointerObserver = null;
  47742. }
  47743. return;
  47744. }
  47745. // Enable Interaction
  47746. // Register the observable
  47747. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  47748. if (_this.isVisible === false) {
  47749. return;
  47750. }
  47751. var hs = 1 / _this.engine.getHardwareScalingLevel();
  47752. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  47753. _this._handlePointerEventForInteraction(e, localPos, s);
  47754. });
  47755. }
  47756. else {
  47757. var scene = this.scene;
  47758. if (enable) {
  47759. scene.constantlyUpdateMeshUnderPointer = true;
  47760. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  47761. if (_this.isVisible === false) {
  47762. return;
  47763. }
  47764. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  47765. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  47766. _this._handlePointerEventForInteraction(e, localPos, s);
  47767. }
  47768. });
  47769. }
  47770. else {
  47771. if (this._scenePointerObserver) {
  47772. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  47773. this._scenePointerObserver = null;
  47774. }
  47775. }
  47776. }
  47777. };
  47778. /**
  47779. * Internal method, you should use the Prim2DBase version instead
  47780. */
  47781. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  47782. if (this.isPointerCaptured(pointerId)) {
  47783. return false;
  47784. }
  47785. // Try to capture the pointer on the HTML side
  47786. try {
  47787. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  47788. }
  47789. catch (e) {
  47790. }
  47791. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  47792. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  47793. this._capturedPointers.add(pointerId.toString(), primitive);
  47794. return true;
  47795. };
  47796. /**
  47797. * Internal method, you should use the Prim2DBase version instead
  47798. */
  47799. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  47800. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  47801. return false;
  47802. }
  47803. // Try to release the pointer on the HTML side
  47804. try {
  47805. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  47806. }
  47807. catch (e) {
  47808. }
  47809. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  47810. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  47811. this._capturedPointers.remove(pointerId.toString());
  47812. return true;
  47813. };
  47814. /**
  47815. * Determine if the given pointer is captured or not
  47816. * @param pointerId the Id of the pointer
  47817. * @return true if it's captured, false otherwise
  47818. */
  47819. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  47820. return this._capturedPointers.contains(pointerId.toString());
  47821. };
  47822. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  47823. // Avoid unnecessary lookup
  47824. if (this._capturedPointers.count === 0) {
  47825. return null;
  47826. }
  47827. return this._capturedPointers.get(pointerId.toString());
  47828. };
  47829. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  47830. // Dispose check
  47831. if (this.isDisposed) {
  47832. return;
  47833. }
  47834. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  47835. this._updatePointerInfo(eventData, localPosition);
  47836. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  47837. // 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.
  47838. // 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.
  47839. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  47840. // 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
  47841. this._updateOverStatus();
  47842. // Check if we have nothing to raise
  47843. if (!this._actualOverPrimitive && !capturedPrim) {
  47844. return;
  47845. }
  47846. // Update the relatedTarget info with the over primitive or the captured one (if any)
  47847. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  47848. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  47849. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  47850. // Analyze the pointer event type and fire proper events on the primitive
  47851. var skip = false;
  47852. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  47853. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData);
  47854. }
  47855. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47856. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData);
  47857. }
  47858. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  47859. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData);
  47860. }
  47861. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  47862. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData);
  47863. }
  47864. eventState.skipNextObservers = skip;
  47865. };
  47866. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  47867. var pii = this._primPointerInfo;
  47868. if (!pii.canvasPointerPos) {
  47869. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  47870. }
  47871. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  47872. var engine = this._scene.getEngine();
  47873. if (this._isScreenSpace) {
  47874. var cameraViewport = camera.viewport;
  47875. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47876. // Moving coordinates to local viewport world
  47877. var x = localPosition.x - viewport.x;
  47878. var y = localPosition.y - viewport.y;
  47879. pii.canvasPointerPos.x = x - this.actualPosition.x;
  47880. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  47881. }
  47882. else {
  47883. pii.canvasPointerPos.x = localPosition.x;
  47884. pii.canvasPointerPos.y = localPosition.y;
  47885. }
  47886. //console.log(`UpdatePointerInfo for ${this.id}, X:${pii.canvasPointerPos.x}, Y:${pii.canvasPointerPos.y}`);
  47887. pii.mouseWheelDelta = 0;
  47888. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  47889. var event = eventData.event;
  47890. if (event.wheelDelta) {
  47891. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  47892. }
  47893. else if (event.detail) {
  47894. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  47895. }
  47896. }
  47897. else {
  47898. var pe = eventData.event;
  47899. pii.ctrlKey = pe.ctrlKey;
  47900. pii.altKey = pe.altKey;
  47901. pii.shiftKey = pe.shiftKey;
  47902. pii.metaKey = pe.metaKey;
  47903. pii.button = pe.button;
  47904. pii.buttons = pe.buttons;
  47905. pii.pointerId = pe.pointerId;
  47906. pii.width = pe.width;
  47907. pii.height = pe.height;
  47908. pii.presssure = pe.pressure;
  47909. pii.tilt.x = pe.tiltX;
  47910. pii.tilt.y = pe.tiltY;
  47911. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  47912. }
  47913. };
  47914. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  47915. if (this.scene.getRenderId() === this._intersectionRenderId) {
  47916. return;
  47917. }
  47918. // 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
  47919. if (!this._globalTransform) {
  47920. this.updateCachedStates(true);
  47921. }
  47922. var ii = Canvas2D._interInfo;
  47923. ii.pickPosition.x = mouseLocalPos.x;
  47924. ii.pickPosition.y = mouseLocalPos.y;
  47925. ii.findFirstOnly = false;
  47926. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  47927. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  47928. this._previousIntersectionList = this._actualIntersectionList;
  47929. this._actualIntersectionList = null;
  47930. this._previousOverPrimitive = this._actualOverPrimitive;
  47931. this._actualOverPrimitive = null;
  47932. return;
  47933. }
  47934. this.intersect(ii);
  47935. this._previousIntersectionList = this._actualIntersectionList;
  47936. this._actualIntersectionList = ii.intersectedPrimitives;
  47937. this._previousOverPrimitive = this._actualOverPrimitive;
  47938. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  47939. this._intersectionRenderId = this.scene.getRenderId();
  47940. };
  47941. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  47942. Canvas2D.prototype._updateOverStatus = function () {
  47943. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  47944. return;
  47945. }
  47946. // Detect a change of over
  47947. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  47948. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  47949. if (prevPrim !== actualPrim) {
  47950. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  47951. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  47952. // Notify the previous "over" prim that the pointer is no longer over it
  47953. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  47954. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  47955. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  47956. }
  47957. // Notify the new "over" prim that the pointer is over it
  47958. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  47959. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  47960. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  47961. }
  47962. }
  47963. this._hoverStatusRenderId = this.scene.getRenderId();
  47964. };
  47965. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  47966. if (this._primPointerInfo.isCaptured) {
  47967. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  47968. }
  47969. else {
  47970. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  47971. var pii = _a[_i];
  47972. if (pii.prim === prim) {
  47973. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  47974. return;
  47975. }
  47976. }
  47977. }
  47978. };
  47979. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  47980. if (!this._notifDebugMode) {
  47981. return;
  47982. }
  47983. var debug = "";
  47984. for (var i = 0; i < prim.hierarchyDepth; i++) {
  47985. debug += " ";
  47986. }
  47987. var pii = this._primPointerInfo;
  47988. 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();
  47989. console.log(debug);
  47990. };
  47991. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  47992. var ppi = this._primPointerInfo;
  47993. var event = eventData ? eventData.event : null;
  47994. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  47995. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  47996. this._notifParents(prim, mask);
  47997. }
  47998. var bubbleCancelled = false;
  47999. var cur = prim;
  48000. while (cur) {
  48001. // Only trigger the observers if the primitive is intersected (except for out)
  48002. if (!bubbleCancelled) {
  48003. this._updatePrimPointerPos(cur);
  48004. // Exec the observers
  48005. this._debugExecObserver(cur, mask);
  48006. if (!cur._pointerEventObservable.notifyObservers(ppi, mask) && eventData instanceof BABYLON.PointerInfoPre) {
  48007. eventData.skipOnPointerObservable = true;
  48008. return false;
  48009. }
  48010. this._triggerActionManager(cur, ppi, mask, event);
  48011. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  48012. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  48013. if (ppi.cancelBubble) {
  48014. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  48015. return false;
  48016. }
  48017. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  48018. bubbleCancelled = true;
  48019. }
  48020. }
  48021. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  48022. if (bubbleCancelled) {
  48023. this._updatePrimPointerPos(cur);
  48024. }
  48025. // Trigger a PointerEnter corresponding to the PointerOver
  48026. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  48027. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  48028. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  48029. }
  48030. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  48031. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  48032. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  48033. }
  48034. // Loop to the parent
  48035. cur = cur.parent;
  48036. }
  48037. return true;
  48038. };
  48039. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  48040. var _this = this;
  48041. // 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
  48042. if (!this._globalTransform) {
  48043. this.updateCachedStates(true);
  48044. }
  48045. // Process Trigger related to PointerDown
  48046. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  48047. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  48048. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  48049. this._pickStartingTime = new Date().getTime();
  48050. this._pickedDownPrim = null;
  48051. if (prim.actionManager) {
  48052. this._pickedDownPrim = prim;
  48053. if (prim.actionManager.hasPickTriggers) {
  48054. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48055. switch (eventData.button) {
  48056. case 0:
  48057. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  48058. break;
  48059. case 1:
  48060. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  48061. break;
  48062. case 2:
  48063. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  48064. break;
  48065. }
  48066. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  48067. }
  48068. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  48069. window.setTimeout(function () {
  48070. var ppi = _this._primPointerInfo;
  48071. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  48072. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  48073. var ii = new BABYLON.IntersectInfo2D();
  48074. ii.pickPosition = ppi.canvasPointerPos.clone();
  48075. ii.findFirstOnly = false;
  48076. _this.intersect(ii);
  48077. if (ii.isPrimIntersected(prim) !== null) {
  48078. if (prim.actionManager) {
  48079. 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)) {
  48080. _this._pickStartingTime = 0;
  48081. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  48082. }
  48083. }
  48084. }
  48085. }, BABYLON.ActionManager.LongPressDelay);
  48086. }
  48087. }
  48088. }
  48089. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  48090. this._pickStartingTime = 0;
  48091. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48092. if (prim.actionManager) {
  48093. // OnPickUpTrigger
  48094. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  48095. // OnPickTrigger
  48096. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  48097. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  48098. }
  48099. }
  48100. // OnPickOutTrigger
  48101. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  48102. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  48103. }
  48104. }
  48105. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  48106. if (prim.actionManager) {
  48107. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48108. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  48109. }
  48110. }
  48111. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  48112. if (prim.actionManager) {
  48113. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  48114. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  48115. }
  48116. }
  48117. };
  48118. Canvas2D.prototype._notifParents = function (prim, mask) {
  48119. var pii = this._primPointerInfo;
  48120. var curPrim = this;
  48121. while (curPrim) {
  48122. this._updatePrimPointerPos(curPrim);
  48123. // Fire the proper notification
  48124. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  48125. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  48126. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  48127. }
  48128. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  48129. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  48130. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  48131. }
  48132. curPrim = curPrim.parent;
  48133. }
  48134. };
  48135. /**
  48136. * Don't forget to call the dispose method when you're done with the Canvas instance.
  48137. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  48138. */
  48139. Canvas2D.prototype.dispose = function () {
  48140. if (!_super.prototype.dispose.call(this)) {
  48141. return false;
  48142. }
  48143. if (this._profilingCanvas) {
  48144. this._profilingCanvas.dispose();
  48145. this._profilingCanvas = null;
  48146. }
  48147. if (this.interactionEnabled) {
  48148. this._setupInteraction(false);
  48149. }
  48150. if (this._beforeRenderObserver) {
  48151. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  48152. this._beforeRenderObserver = null;
  48153. }
  48154. if (this._afterRenderObserver) {
  48155. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  48156. this._afterRenderObserver = null;
  48157. }
  48158. if (this._groupCacheMaps) {
  48159. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  48160. this._groupCacheMaps = null;
  48161. }
  48162. };
  48163. Object.defineProperty(Canvas2D.prototype, "scene", {
  48164. /**
  48165. * Accessor to the Scene that owns the Canvas
  48166. * @returns The instance of the Scene object
  48167. */
  48168. get: function () {
  48169. return this._scene;
  48170. },
  48171. enumerable: true,
  48172. configurable: true
  48173. });
  48174. Object.defineProperty(Canvas2D.prototype, "engine", {
  48175. /**
  48176. * Accessor to the Engine that drives the Scene used by this Canvas
  48177. * @returns The instance of the Engine object
  48178. */
  48179. get: function () {
  48180. return this._engine;
  48181. },
  48182. enumerable: true,
  48183. configurable: true
  48184. });
  48185. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  48186. /**
  48187. * Accessor of the Caching Strategy used by this Canvas.
  48188. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  48189. * @returns the value corresponding to the used strategy.
  48190. */
  48191. get: function () {
  48192. return this._cachingStrategy;
  48193. },
  48194. enumerable: true,
  48195. configurable: true
  48196. });
  48197. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  48198. /**
  48199. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  48200. * @returns {}
  48201. */
  48202. get: function () {
  48203. return this._isScreenSpace;
  48204. },
  48205. enumerable: true,
  48206. configurable: true
  48207. });
  48208. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  48209. /**
  48210. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  48211. */
  48212. get: function () {
  48213. return this._worldSpaceNode;
  48214. },
  48215. set: function (val) {
  48216. this._worldSpaceNode = val;
  48217. },
  48218. enumerable: true,
  48219. configurable: true
  48220. });
  48221. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  48222. /**
  48223. * Check if the WebGL Instanced Array extension is supported or not
  48224. */
  48225. get: function () {
  48226. return this._supprtInstancedArray;
  48227. },
  48228. enumerable: true,
  48229. configurable: true
  48230. });
  48231. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  48232. /**
  48233. * Property that defines the fill object used to draw the background of the Canvas.
  48234. * Note that Canvas with a Caching Strategy of
  48235. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  48236. */
  48237. get: function () {
  48238. if (!this._background || !this._background.isVisible) {
  48239. return null;
  48240. }
  48241. return this._background.fill;
  48242. },
  48243. set: function (value) {
  48244. this.checkBackgroundAvailability();
  48245. if (value === this._background.fill) {
  48246. return;
  48247. }
  48248. this._background.fill = value;
  48249. this._background.levelVisible = true;
  48250. },
  48251. enumerable: true,
  48252. configurable: true
  48253. });
  48254. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  48255. /**
  48256. * Property that defines the border object used to draw the background of the Canvas.
  48257. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  48258. */
  48259. get: function () {
  48260. if (!this._background || !this._background.isVisible) {
  48261. return null;
  48262. }
  48263. return this._background.border;
  48264. },
  48265. set: function (value) {
  48266. this.checkBackgroundAvailability();
  48267. if (value === this._background.border) {
  48268. return;
  48269. }
  48270. this._background.border = value;
  48271. this._background.levelVisible = true;
  48272. },
  48273. enumerable: true,
  48274. configurable: true
  48275. });
  48276. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  48277. /**
  48278. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  48279. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  48280. */
  48281. get: function () {
  48282. if (!this._background || !this._background.isVisible) {
  48283. return null;
  48284. }
  48285. return this._background.borderThickness;
  48286. },
  48287. set: function (value) {
  48288. this.checkBackgroundAvailability();
  48289. if (value === this._background.borderThickness) {
  48290. return;
  48291. }
  48292. this._background.borderThickness = value;
  48293. },
  48294. enumerable: true,
  48295. configurable: true
  48296. });
  48297. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  48298. /**
  48299. * You can set the roundRadius of the background
  48300. * @returns The current roundRadius
  48301. */
  48302. get: function () {
  48303. if (!this._background || !this._background.isVisible) {
  48304. return null;
  48305. }
  48306. return this._background.roundRadius;
  48307. },
  48308. set: function (value) {
  48309. this.checkBackgroundAvailability();
  48310. if (value === this._background.roundRadius) {
  48311. return;
  48312. }
  48313. this._background.roundRadius = value;
  48314. this._background.levelVisible = true;
  48315. },
  48316. enumerable: true,
  48317. configurable: true
  48318. });
  48319. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  48320. /**
  48321. * Enable/Disable interaction for this Canvas
  48322. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  48323. */
  48324. get: function () {
  48325. return this._interactionEnabled;
  48326. },
  48327. set: function (enable) {
  48328. this._setupInteraction(enable);
  48329. },
  48330. enumerable: true,
  48331. configurable: true
  48332. });
  48333. Object.defineProperty(Canvas2D.prototype, "designSize", {
  48334. get: function () {
  48335. return this._designSize;
  48336. },
  48337. enumerable: true,
  48338. configurable: true
  48339. });
  48340. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizAxis", {
  48341. get: function () {
  48342. return this._designUseHorizAxis;
  48343. },
  48344. enumerable: true,
  48345. configurable: true
  48346. });
  48347. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  48348. /**
  48349. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  48350. * @returns {}
  48351. */
  48352. get: function () {
  48353. return this.__engineData;
  48354. },
  48355. enumerable: true,
  48356. configurable: true
  48357. });
  48358. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  48359. if (this._profilingCanvas) {
  48360. return this._profilingCanvas;
  48361. }
  48362. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  48363. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  48364. new BABYLON.Rectangle2D({
  48365. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  48366. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  48367. ]
  48368. })
  48369. ]
  48370. });
  48371. this._profileInfoText = canvas.findById("ProfileInfoText");
  48372. this._profilingCanvas = canvas;
  48373. return canvas;
  48374. };
  48375. Canvas2D.prototype.checkBackgroundAvailability = function () {
  48376. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  48377. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  48378. }
  48379. };
  48380. Canvas2D.prototype._initPerfMetrics = function () {
  48381. this._drawCallsOpaqueCounter.fetchNewFrame();
  48382. this._drawCallsAlphaTestCounter.fetchNewFrame();
  48383. this._drawCallsTransparentCounter.fetchNewFrame();
  48384. this._groupRenderCounter.fetchNewFrame();
  48385. this._updateTransparentDataCounter.fetchNewFrame();
  48386. this._cachedGroupRenderCounter.fetchNewFrame();
  48387. this._updateCachedStateCounter.fetchNewFrame();
  48388. this._updateLayoutCounter.fetchNewFrame();
  48389. this._updatePositioningCounter.fetchNewFrame();
  48390. this._updateLocalTransformCounter.fetchNewFrame();
  48391. this._updateGlobalTransformCounter.fetchNewFrame();
  48392. this._boundingInfoRecomputeCounter.fetchNewFrame();
  48393. };
  48394. Canvas2D.prototype._fetchPerfMetrics = function () {
  48395. this._drawCallsOpaqueCounter.addCount(0, true);
  48396. this._drawCallsAlphaTestCounter.addCount(0, true);
  48397. this._drawCallsTransparentCounter.addCount(0, true);
  48398. this._groupRenderCounter.addCount(0, true);
  48399. this._updateTransparentDataCounter.addCount(0, true);
  48400. this._cachedGroupRenderCounter.addCount(0, true);
  48401. this._updateCachedStateCounter.addCount(0, true);
  48402. this._updateLayoutCounter.addCount(0, true);
  48403. this._updatePositioningCounter.addCount(0, true);
  48404. this._updateLocalTransformCounter.addCount(0, true);
  48405. this._updateGlobalTransformCounter.addCount(0, true);
  48406. this._boundingInfoRecomputeCounter.addCount(0, true);
  48407. };
  48408. Canvas2D.prototype._updateProfileCanvas = function () {
  48409. if (this._profileInfoText == null) {
  48410. return;
  48411. }
  48412. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  48413. var p = "Draw Calls:\n" +
  48414. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  48415. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  48416. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  48417. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  48418. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  48419. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  48420. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  48421. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  48422. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  48423. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  48424. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  48425. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  48426. this._profileInfoText.text = p;
  48427. };
  48428. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  48429. switch (renderMode) {
  48430. case BABYLON.Render2DContext.RenderModeOpaque:
  48431. this._drawCallsOpaqueCounter.addCount(count, false);
  48432. return;
  48433. case BABYLON.Render2DContext.RenderModeAlphaTest:
  48434. this._drawCallsAlphaTestCounter.addCount(count, false);
  48435. return;
  48436. case BABYLON.Render2DContext.RenderModeTransparent:
  48437. this._drawCallsTransparentCounter.addCount(count, false);
  48438. return;
  48439. }
  48440. };
  48441. Canvas2D.prototype._addGroupRenderCount = function (count) {
  48442. this._groupRenderCounter.addCount(count, false);
  48443. };
  48444. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  48445. this._updateTransparentDataCounter.addCount(count, false);
  48446. };
  48447. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  48448. this._cachedGroupRenderCounter.addCount(count, false);
  48449. };
  48450. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  48451. this._updateCachedStateCounter.addCount(count, false);
  48452. };
  48453. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  48454. this._updateLayoutCounter.addCount(count, false);
  48455. };
  48456. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  48457. this._updatePositioningCounter.addCount(count, false);
  48458. };
  48459. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  48460. this._updateLocalTransformCounter.addCount(count, false);
  48461. };
  48462. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  48463. this._updateGlobalTransformCounter.addCount(count, false);
  48464. };
  48465. Canvas2D.prototype._updateTrackedNodes = function () {
  48466. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  48467. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  48468. var rh = this.engine.getRenderHeight();
  48469. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  48470. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  48471. var group = _a[_i];
  48472. if (group.isDisposed || !group.isVisible) {
  48473. continue;
  48474. }
  48475. var node = group.trackedNode;
  48476. var worldMtx = node.getWorldMatrix();
  48477. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  48478. var s = this.scale;
  48479. group.x = Math.round(proj.x / s);
  48480. group.y = Math.round((rh - proj.y) / s);
  48481. }
  48482. };
  48483. /**
  48484. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  48485. */
  48486. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  48487. this._updateCanvasState(forceRecompute);
  48488. };
  48489. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  48490. if (this._globalTransformStep < 2) {
  48491. return;
  48492. }
  48493. var n = this.worldSpaceCanvasNode;
  48494. var bi = n.getBoundingInfo().boundingBox;
  48495. var v = bi.vectorsWorld;
  48496. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  48497. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  48498. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  48499. var projPoints = new Array(4);
  48500. for (var i = 0; i < 4; i++) {
  48501. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  48502. }
  48503. var left = projPoints[3].subtract(projPoints[0]).length();
  48504. var top = projPoints[3].subtract(projPoints[1]).length();
  48505. var right = projPoints[1].subtract(projPoints[2]).length();
  48506. var bottom = projPoints[2].subtract(projPoints[0]).length();
  48507. var w = Math.round(Math.max(top, bottom));
  48508. var h = Math.round(Math.max(right, left));
  48509. var isW = w > h;
  48510. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  48511. var edge = Math.max(w, h);
  48512. if (edge < 256) {
  48513. edge = 256;
  48514. }
  48515. else {
  48516. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  48517. }
  48518. // Clip values if needed
  48519. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  48520. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  48521. if (newScale !== this.scale) {
  48522. var scale = newScale;
  48523. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  48524. this._setRenderingScale(scale);
  48525. }
  48526. };
  48527. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  48528. // Check if the update has already been made for this render Frame
  48529. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  48530. return;
  48531. }
  48532. // Detect a change of rendering size
  48533. var renderingSizeChanged = false;
  48534. var newWidth = this.engine.getRenderWidth();
  48535. if (newWidth !== this._renderingSize.width) {
  48536. renderingSizeChanged = true;
  48537. }
  48538. this._renderingSize.width = newWidth;
  48539. var newHeight = this.engine.getRenderHeight();
  48540. if (newHeight !== this._renderingSize.height) {
  48541. renderingSizeChanged = true;
  48542. }
  48543. this._renderingSize.height = newHeight;
  48544. // If the canvas fit the rendering size and it changed, update
  48545. if (renderingSizeChanged && this._fitRenderingDevice) {
  48546. this.size = this._renderingSize;
  48547. if (this._background) {
  48548. this._background.size = this.size;
  48549. }
  48550. // Dirty the Layout at the Canvas level to recompute as the size changed
  48551. this._setLayoutDirty();
  48552. }
  48553. // If there's a design size, update the scale according to the renderingSize
  48554. if (this._designSize) {
  48555. var scale;
  48556. if (this._designUseHorizAxis) {
  48557. scale = this._renderingSize.width / this._designSize.width;
  48558. }
  48559. else {
  48560. scale = this._renderingSize.height / this._designSize.height;
  48561. }
  48562. this.scale = scale;
  48563. }
  48564. var context = new BABYLON.PrepareRender2DContext();
  48565. ++this._globalTransformProcessStep;
  48566. this.updateCachedStates(false);
  48567. this._prepareGroupRender(context);
  48568. this._updateRenderId = this.scene.getRenderId();
  48569. };
  48570. /**
  48571. * Method that renders the Canvas, you should not invoke
  48572. */
  48573. Canvas2D.prototype._render = function () {
  48574. this._initPerfMetrics();
  48575. this._updateCanvasState(false);
  48576. this._updateTrackedNodes();
  48577. // Nothing to do is the Canvas is not visible
  48578. if (this.isVisible === false) {
  48579. return;
  48580. }
  48581. if (!this._isScreenSpace) {
  48582. this._updateAdaptiveSizeWorldCanvas();
  48583. }
  48584. this._updateCanvasState(false);
  48585. if (this._primPointerInfo.canvasPointerPos) {
  48586. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  48587. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  48588. }
  48589. this.engine.setState(false);
  48590. this._groupRender();
  48591. if (!this._isScreenSpace) {
  48592. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  48593. this.worldSpaceCacheChanged();
  48594. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  48595. }
  48596. }
  48597. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  48598. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  48599. this._cachedCanvasGroup._renderCachedCanvas();
  48600. }
  48601. this._fetchPerfMetrics();
  48602. this._updateProfileCanvas();
  48603. };
  48604. /**
  48605. * Internal method that allocate a cache for the given group.
  48606. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  48607. * @param group The group to allocate the cache of.
  48608. * @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.
  48609. */
  48610. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  48611. if (useMipMap === void 0) { useMipMap = false; }
  48612. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  48613. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  48614. var rd = group._renderableData;
  48615. var noResizeScale = rd._noResizeOnScale;
  48616. var isCanvas = parent == null;
  48617. var scale;
  48618. if (noResizeScale) {
  48619. scale = isCanvas ? Canvas2D._unS : group.parent.actualScale;
  48620. }
  48621. else {
  48622. scale = group.actualScale;
  48623. }
  48624. // Determine size
  48625. var size = group.actualSize;
  48626. size = new BABYLON.Size(Math.ceil(size.width * scale.x), Math.ceil(size.height * scale.y));
  48627. if (minSize) {
  48628. size.width = Math.max(minSize.width, size.width);
  48629. size.height = Math.max(minSize.height, size.height);
  48630. }
  48631. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  48632. // Try to find a spot in one of the cached texture
  48633. var res = null;
  48634. var map;
  48635. for (var _i = 0; _i < mapArray.length; _i++) {
  48636. var _map = mapArray[_i];
  48637. map = _map;
  48638. var node = map.allocateRect(size);
  48639. if (node) {
  48640. res = { node: node, texture: map };
  48641. break;
  48642. }
  48643. }
  48644. // Couldn't find a map that could fit the rect, create a new map for it
  48645. if (!res) {
  48646. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  48647. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  48648. if (size.width > mapSize.width || size.height > mapSize.height) {
  48649. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  48650. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  48651. }
  48652. var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
  48653. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  48654. map.hasAlpha = true;
  48655. map.anisotropicFilteringLevel = 4;
  48656. mapArray.splice(0, 0, map);
  48657. var node = map.allocateRect(size);
  48658. res = { node: node, texture: map };
  48659. }
  48660. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  48661. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  48662. if (group !== this || this._isScreenSpace) {
  48663. var node = res.node;
  48664. // 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
  48665. var sprite;
  48666. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  48667. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  48668. sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  48669. sprite.zOrder = 1;
  48670. sprite.origin = BABYLON.Vector2.Zero();
  48671. }
  48672. else {
  48673. sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.actualPosition.x, y: group.actualPosition.y, spriteSize: node.contentSize, spriteLocation: node.pos, dontInheritParentScale: true });
  48674. sprite.origin = group.origin.clone();
  48675. sprite.addExternalData("__cachedGroup__", group);
  48676. sprite.pointerEventObservable.add(function (e, s) {
  48677. if (group.pointerEventObservable !== null) {
  48678. group.pointerEventObservable.notifyObservers(e, s.mask);
  48679. }
  48680. });
  48681. res.sprite = sprite;
  48682. }
  48683. if (sprite && noResizeScale) {
  48684. var relScale = isCanvas ? group.actualScale : group.actualScale.divide(group.parent.actualScale);
  48685. sprite.scaleX = relScale.x;
  48686. sprite.scaleY = relScale.y;
  48687. }
  48688. }
  48689. return res;
  48690. };
  48691. /**
  48692. * Internal method used to register a Scene Node to track position for the given group
  48693. * Do not invoke this method, for internal purpose only.
  48694. * @param group the group to track its associated Scene Node
  48695. */
  48696. Canvas2D.prototype._registerTrackedNode = function (group) {
  48697. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  48698. return;
  48699. }
  48700. this._trackedGroups.push(group);
  48701. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  48702. };
  48703. /**
  48704. * Internal method used to unregister a tracked Scene Node
  48705. * Do not invoke this method, it's for internal purpose only.
  48706. * @param group the group to unregister its tracked Scene Node from.
  48707. */
  48708. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  48709. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  48710. return;
  48711. }
  48712. var i = this._trackedGroups.indexOf(group);
  48713. if (i !== -1) {
  48714. this._trackedGroups.splice(i, 1);
  48715. }
  48716. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  48717. };
  48718. /**
  48719. * Get a Solid Color Brush instance matching the given color.
  48720. * @param color The color to retrieve
  48721. * @return A shared instance of the SolidColorBrush2D class that use the given color
  48722. */
  48723. Canvas2D.GetSolidColorBrush = function (color) {
  48724. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  48725. };
  48726. /**
  48727. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  48728. * @param color The color to retrieve
  48729. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  48730. */
  48731. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  48732. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  48733. };
  48734. /**
  48735. * Get a Gradient Color Brush
  48736. * @param color1 starting color
  48737. * @param color2 engine color
  48738. * @param translation translation vector to apply. default is [0;0]
  48739. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  48740. * @param scale scaling factor to apply. default is 1.
  48741. */
  48742. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  48743. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  48744. if (rotation === void 0) { rotation = 0; }
  48745. if (scale === void 0) { scale = 1; }
  48746. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  48747. };
  48748. /**
  48749. * Create a solid or gradient brush from a string value.
  48750. * @param brushString should be either
  48751. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  48752. * - "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.
  48753. */
  48754. Canvas2D.GetBrushFromString = function (brushString) {
  48755. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  48756. brushString = brushString.trim();
  48757. var split = brushString.split(",");
  48758. // Solid, formatted as: "[solid:]#FF808080"
  48759. if (split.length === 1) {
  48760. var value = null;
  48761. if (brushString.indexOf("solid:") === 0) {
  48762. value = brushString.substr(6).trim();
  48763. }
  48764. else if (brushString.indexOf("#") === 0) {
  48765. value = brushString;
  48766. }
  48767. else {
  48768. return null;
  48769. }
  48770. return Canvas2D.GetSolidColorBrushFromHex(value);
  48771. }
  48772. else {
  48773. if (split[0].indexOf("gradient:") === 0) {
  48774. split[0] = split[0].substr(9).trim();
  48775. }
  48776. try {
  48777. var start = BABYLON.Color4.FromHexString(split[0].trim());
  48778. var end = BABYLON.Color4.FromHexString(split[1].trim());
  48779. var t = BABYLON.Vector2.Zero();
  48780. if (split.length > 2) {
  48781. var v = split[2].trim();
  48782. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  48783. return null;
  48784. }
  48785. var sep = v.indexOf(":");
  48786. var x = parseFloat(v.substr(1, sep));
  48787. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  48788. t = new BABYLON.Vector2(x, y);
  48789. }
  48790. var r = 0;
  48791. if (split.length > 3) {
  48792. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  48793. }
  48794. var s = 1;
  48795. if (split.length > 4) {
  48796. s = parseFloat(split[4].trim());
  48797. }
  48798. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  48799. }
  48800. catch (e) {
  48801. return null;
  48802. }
  48803. }
  48804. };
  48805. /**
  48806. * 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.
  48807. * This strategy doesn't allow primitives added directly as children of the Canvas.
  48808. * 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.
  48809. */
  48810. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  48811. /**
  48812. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  48813. * 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.
  48814. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  48815. * 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.
  48816. */
  48817. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  48818. /**
  48819. * 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).
  48820. */
  48821. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  48822. /**
  48823. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  48824. * 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).
  48825. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  48826. */
  48827. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  48828. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  48829. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  48830. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  48831. Canvas2D._m = BABYLON.Matrix.Identity();
  48832. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  48833. Canvas2D._unS = new BABYLON.Vector2(1, 1);
  48834. /**
  48835. * Define the default size used for both the width and height of a MapTexture to allocate.
  48836. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  48837. */
  48838. Canvas2D._groupTextureCacheSize = 1024;
  48839. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  48840. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  48841. Canvas2D = __decorate([
  48842. BABYLON.className("Canvas2D")
  48843. ], Canvas2D);
  48844. return Canvas2D;
  48845. })(BABYLON.Group2D);
  48846. BABYLON.Canvas2D = Canvas2D;
  48847. var WorldSpaceCanvas2D = (function (_super) {
  48848. __extends(WorldSpaceCanvas2D, _super);
  48849. /**
  48850. * 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.
  48851. * 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.
  48852. * @param scene the Scene that owns the Canvas
  48853. * @param size the dimension of the Canvas in World Space
  48854. * @param settings a combination of settings, possible ones are
  48855. * - children: an array of direct children primitives
  48856. * - id: a text identifier, for information purpose only, default is null.
  48857. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  48858. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  48859. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  48860. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  48861. * - 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).
  48862. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  48863. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  48864. * - 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.
  48865. * - 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.
  48866. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  48867. * - 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.
  48868. * - 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.
  48869. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48870. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48871. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48872. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48873. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  48874. */
  48875. function WorldSpaceCanvas2D(scene, size, settings) {
  48876. BABYLON.Prim2DBase._isCanvasInit = true;
  48877. var s = settings;
  48878. s.isScreenSpace = false;
  48879. s.size = size.clone();
  48880. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  48881. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  48882. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  48883. }
  48884. _super.call(this, scene, settings);
  48885. BABYLON.Prim2DBase._isCanvasInit = false;
  48886. this._renderableData._useMipMap = true;
  48887. this._renderableData._anisotropicLevel = 8;
  48888. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  48889. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  48890. //}
  48891. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  48892. var id = settings ? settings.id || null : null;
  48893. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  48894. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  48895. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  48896. if (settings.maxAdaptiveCanvasSize == null) {
  48897. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  48898. }
  48899. else {
  48900. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  48901. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  48902. }
  48903. if (createWorldSpaceNode) {
  48904. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  48905. var vertexData = BABYLON.VertexData.CreatePlane({
  48906. width: size.width,
  48907. height: size.height,
  48908. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  48909. });
  48910. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  48911. this.applyCachedTexture(vertexData, mtl);
  48912. vertexData.applyToMesh(plane, true);
  48913. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  48914. mtl.disableLighting = true;
  48915. mtl.useAlphaFromDiffuseTexture = true;
  48916. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  48917. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  48918. plane.material = mtl;
  48919. this._worldSpaceNode = plane;
  48920. }
  48921. else {
  48922. this._worldSpaceNode = settings.customWorldSpaceNode;
  48923. this.applyCachedTexture(null, null);
  48924. }
  48925. }
  48926. WorldSpaceCanvas2D = __decorate([
  48927. BABYLON.className("WorldSpaceCanvas2D")
  48928. ], WorldSpaceCanvas2D);
  48929. return WorldSpaceCanvas2D;
  48930. })(Canvas2D);
  48931. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  48932. var ScreenSpaceCanvas2D = (function (_super) {
  48933. __extends(ScreenSpaceCanvas2D, _super);
  48934. /**
  48935. * 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.
  48936. * 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.
  48937. * All caching strategies will be available.
  48938. * 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]
  48939. * @param scene the Scene that owns the Canvas
  48940. * @param settings a combination of settings, possible ones are
  48941. * - children: an array of direct children primitives
  48942. * - id: a text identifier, for information purpose only
  48943. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  48944. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  48945. * - 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]
  48946. * - width: the width of the Canvas. you can alternatively use the size setting.
  48947. * - height: the height of the Canvas. you can alternatively use the size setting.
  48948. * - 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
  48949. * - designSize: if you want to set the canvas content based on fixed coordinates whatever the final canvas dimension would be, set this. For instance a designSize of 360*640 will give you the possibility to specify all the children element in this frame. The Canvas' true size will be the HTMLCanvas' size: for instance it could be 720*1280, then a uniform scale of 2 will be applied on the Canvas to keep the absolute coordinates working as expecting. If the ratios of the designSize and the true Canvas size are not the same, then the scale is computed following the designUseHorizAxis member by using either the size of the horizontal axis or the vertical axis.
  48950. * - designUseHorizAxis: you can set this member if you use designSize to specify which axis is priority to compute the scale when the ratio of the canvas' size is different from the designSize's one.
  48951. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  48952. * - 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.
  48953. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  48954. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  48955. * - 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.
  48956. * - 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.
  48957. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  48958. * - 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.
  48959. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48960. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48961. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48962. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48963. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  48964. */
  48965. function ScreenSpaceCanvas2D(scene, settings) {
  48966. BABYLON.Prim2DBase._isCanvasInit = true;
  48967. _super.call(this, scene, settings);
  48968. }
  48969. ScreenSpaceCanvas2D = __decorate([
  48970. BABYLON.className("ScreenSpaceCanvas2D")
  48971. ], ScreenSpaceCanvas2D);
  48972. return ScreenSpaceCanvas2D;
  48973. })(Canvas2D);
  48974. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  48975. })(BABYLON || (BABYLON = {}));
  48976. var BABYLON;
  48977. (function (BABYLON) {
  48978. /**
  48979. * This is the class that is used to display a World Space Canvas into a 3D scene
  48980. */
  48981. var WorldSpaceCanvas2DNode = (function (_super) {
  48982. __extends(WorldSpaceCanvas2DNode, _super);
  48983. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  48984. _super.call(this, name, scene);
  48985. this._canvas = canvas;
  48986. }
  48987. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  48988. _super.prototype.dispose.call(this);
  48989. if (this._canvas) {
  48990. this._canvas.dispose();
  48991. this._canvas = null;
  48992. }
  48993. };
  48994. return WorldSpaceCanvas2DNode;
  48995. })(BABYLON.Mesh);
  48996. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  48997. })(BABYLON || (BABYLON = {}));
  48998. var BABYLON;
  48999. (function (BABYLON) {
  49000. var LayoutEngineBase = (function () {
  49001. function LayoutEngineBase() {
  49002. this.layoutDirtyOnPropertyChangedMask = 0;
  49003. }
  49004. LayoutEngineBase.prototype.updateLayout = function (prim) {
  49005. };
  49006. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  49007. get: function () {
  49008. return false;
  49009. },
  49010. enumerable: true,
  49011. configurable: true
  49012. });
  49013. LayoutEngineBase.prototype.isLocked = function () {
  49014. return this._isLocked;
  49015. };
  49016. LayoutEngineBase.prototype.lock = function () {
  49017. if (this._isLocked) {
  49018. return false;
  49019. }
  49020. this._isLocked = true;
  49021. return true;
  49022. };
  49023. LayoutEngineBase = __decorate([
  49024. BABYLON.className("LayoutEngineBase")
  49025. ], LayoutEngineBase);
  49026. return LayoutEngineBase;
  49027. })();
  49028. BABYLON.LayoutEngineBase = LayoutEngineBase;
  49029. var CanvasLayoutEngine = (function (_super) {
  49030. __extends(CanvasLayoutEngine, _super);
  49031. function CanvasLayoutEngine() {
  49032. _super.apply(this, arguments);
  49033. }
  49034. // A very simple (no) layout computing...
  49035. // The Canvas and its direct children gets the Canvas' size as Layout Area
  49036. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  49037. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  49038. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  49039. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  49040. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  49041. var child = _a[_i];
  49042. this._doUpdate(child);
  49043. }
  49044. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  49045. }
  49046. };
  49047. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  49048. // Canvas ?
  49049. if (prim instanceof BABYLON.Canvas2D) {
  49050. prim.layoutArea = prim.actualSize;
  49051. }
  49052. else if (prim.parent instanceof BABYLON.Canvas2D) {
  49053. prim.layoutArea = prim.owner.actualSize;
  49054. }
  49055. else {
  49056. prim.layoutArea = prim.parent.contentArea;
  49057. }
  49058. };
  49059. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  49060. get: function () {
  49061. return true;
  49062. },
  49063. enumerable: true,
  49064. configurable: true
  49065. });
  49066. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  49067. CanvasLayoutEngine = __decorate([
  49068. BABYLON.className("CanvasLayoutEngine")
  49069. ], CanvasLayoutEngine);
  49070. return CanvasLayoutEngine;
  49071. })(LayoutEngineBase);
  49072. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  49073. var StackPanelLayoutEngine = (function (_super) {
  49074. __extends(StackPanelLayoutEngine, _super);
  49075. function StackPanelLayoutEngine() {
  49076. _super.call(this);
  49077. this._isHorizontal = true;
  49078. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  49079. }
  49080. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  49081. get: function () {
  49082. if (!StackPanelLayoutEngine._horizontal) {
  49083. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  49084. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  49085. StackPanelLayoutEngine._horizontal.lock();
  49086. }
  49087. return StackPanelLayoutEngine._horizontal;
  49088. },
  49089. enumerable: true,
  49090. configurable: true
  49091. });
  49092. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  49093. get: function () {
  49094. if (!StackPanelLayoutEngine._vertical) {
  49095. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  49096. StackPanelLayoutEngine._vertical.isHorizontal = false;
  49097. StackPanelLayoutEngine._vertical.lock();
  49098. }
  49099. return StackPanelLayoutEngine._vertical;
  49100. },
  49101. enumerable: true,
  49102. configurable: true
  49103. });
  49104. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  49105. get: function () {
  49106. return this._isHorizontal;
  49107. },
  49108. set: function (val) {
  49109. if (this.isLocked()) {
  49110. return;
  49111. }
  49112. this._isHorizontal = val;
  49113. },
  49114. enumerable: true,
  49115. configurable: true
  49116. });
  49117. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  49118. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  49119. var x = 0;
  49120. var y = 0;
  49121. var h = this.isHorizontal;
  49122. var max = 0;
  49123. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  49124. var child = _a[_i];
  49125. var layoutArea = child.layoutArea;
  49126. child.margin.computeArea(child.actualSize, layoutArea);
  49127. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  49128. }
  49129. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  49130. var child = _c[_b];
  49131. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  49132. var layoutArea = child.layoutArea;
  49133. if (h) {
  49134. x += layoutArea.width;
  49135. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  49136. }
  49137. else {
  49138. y += layoutArea.height;
  49139. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  49140. }
  49141. }
  49142. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  49143. }
  49144. };
  49145. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  49146. get: function () {
  49147. return false;
  49148. },
  49149. enumerable: true,
  49150. configurable: true
  49151. });
  49152. StackPanelLayoutEngine._horizontal = null;
  49153. StackPanelLayoutEngine._vertical = null;
  49154. StackPanelLayoutEngine = __decorate([
  49155. BABYLON.className("StackPanelLayoutEngine")
  49156. ], StackPanelLayoutEngine);
  49157. return StackPanelLayoutEngine;
  49158. })(LayoutEngineBase);
  49159. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  49160. })(BABYLON || (BABYLON = {}));
  49161. var BABYLON;
  49162. (function (BABYLON) {
  49163. var ShaderMaterial = (function (_super) {
  49164. __extends(ShaderMaterial, _super);
  49165. function ShaderMaterial(name, scene, shaderPath, options) {
  49166. _super.call(this, name, scene);
  49167. this._textures = {};
  49168. this._textureArrays = {};
  49169. this._floats = {};
  49170. this._floatsArrays = {};
  49171. this._colors3 = {};
  49172. this._colors4 = {};
  49173. this._vectors2 = {};
  49174. this._vectors3 = {};
  49175. this._vectors4 = {};
  49176. this._matrices = {};
  49177. this._matrices3x3 = {};
  49178. this._matrices2x2 = {};
  49179. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  49180. this._shaderPath = shaderPath;
  49181. options.needAlphaBlending = options.needAlphaBlending || false;
  49182. options.needAlphaTesting = options.needAlphaTesting || false;
  49183. options.attributes = options.attributes || ["position", "normal", "uv"];
  49184. options.uniforms = options.uniforms || ["worldViewProjection"];
  49185. options.samplers = options.samplers || [];
  49186. options.defines = options.defines || [];
  49187. this._options = options;
  49188. }
  49189. ShaderMaterial.prototype.needAlphaBlending = function () {
  49190. return this._options.needAlphaBlending;
  49191. };
  49192. ShaderMaterial.prototype.needAlphaTesting = function () {
  49193. return this._options.needAlphaTesting;
  49194. };
  49195. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  49196. if (this._options.uniforms.indexOf(uniformName) === -1) {
  49197. this._options.uniforms.push(uniformName);
  49198. }
  49199. };
  49200. ShaderMaterial.prototype.setTexture = function (name, texture) {
  49201. if (this._options.samplers.indexOf(name) === -1) {
  49202. this._options.samplers.push(name);
  49203. }
  49204. this._textures[name] = texture;
  49205. return this;
  49206. };
  49207. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  49208. if (this._options.samplers.indexOf(name) === -1) {
  49209. this._options.samplers.push(name);
  49210. }
  49211. this._checkUniform(name);
  49212. this._textureArrays[name] = textures;
  49213. return this;
  49214. };
  49215. ShaderMaterial.prototype.setFloat = function (name, value) {
  49216. this._checkUniform(name);
  49217. this._floats[name] = value;
  49218. return this;
  49219. };
  49220. ShaderMaterial.prototype.setFloats = function (name, value) {
  49221. this._checkUniform(name);
  49222. this._floatsArrays[name] = value;
  49223. return this;
  49224. };
  49225. ShaderMaterial.prototype.setColor3 = function (name, value) {
  49226. this._checkUniform(name);
  49227. this._colors3[name] = value;
  49228. return this;
  49229. };
  49230. ShaderMaterial.prototype.setColor4 = function (name, value) {
  49231. this._checkUniform(name);
  49232. this._colors4[name] = value;
  49233. return this;
  49234. };
  49235. ShaderMaterial.prototype.setVector2 = function (name, value) {
  49236. this._checkUniform(name);
  49237. this._vectors2[name] = value;
  49238. return this;
  49239. };
  49240. ShaderMaterial.prototype.setVector3 = function (name, value) {
  49241. this._checkUniform(name);
  49242. this._vectors3[name] = value;
  49243. return this;
  49244. };
  49245. ShaderMaterial.prototype.setVector4 = function (name, value) {
  49246. this._checkUniform(name);
  49247. this._vectors4[name] = value;
  49248. return this;
  49249. };
  49250. ShaderMaterial.prototype.setMatrix = function (name, value) {
  49251. this._checkUniform(name);
  49252. this._matrices[name] = value;
  49253. return this;
  49254. };
  49255. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  49256. this._checkUniform(name);
  49257. this._matrices3x3[name] = value;
  49258. return this;
  49259. };
  49260. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  49261. this._checkUniform(name);
  49262. this._matrices2x2[name] = value;
  49263. return this;
  49264. };
  49265. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  49266. var scene = this.getScene();
  49267. var engine = scene.getEngine();
  49268. if (!this.checkReadyOnEveryCall) {
  49269. if (this._renderId === scene.getRenderId()) {
  49270. return true;
  49271. }
  49272. }
  49273. // Instances
  49274. var defines = [];
  49275. var fallbacks = new BABYLON.EffectFallbacks();
  49276. if (useInstances) {
  49277. defines.push("#define INSTANCES");
  49278. }
  49279. for (var index = 0; index < this._options.defines.length; index++) {
  49280. defines.push(this._options.defines[index]);
  49281. }
  49282. // Bones
  49283. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  49284. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49285. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49286. fallbacks.addCPUSkinningFallback(0, mesh);
  49287. }
  49288. // Alpha test
  49289. if (engine.getAlphaTesting()) {
  49290. defines.push("#define ALPHATEST");
  49291. }
  49292. var previousEffect = this._effect;
  49293. var join = defines.join("\n");
  49294. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  49295. if (!this._effect.isReady()) {
  49296. return false;
  49297. }
  49298. if (previousEffect !== this._effect) {
  49299. scene.resetCachedMaterial();
  49300. }
  49301. this._renderId = scene.getRenderId();
  49302. return true;
  49303. };
  49304. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  49305. var scene = this.getScene();
  49306. if (this._options.uniforms.indexOf("world") !== -1) {
  49307. this._effect.setMatrix("world", world);
  49308. }
  49309. if (this._options.uniforms.indexOf("worldView") !== -1) {
  49310. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  49311. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  49312. }
  49313. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  49314. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  49315. }
  49316. };
  49317. ShaderMaterial.prototype.bind = function (world, mesh) {
  49318. // Std values
  49319. this.bindOnlyWorldMatrix(world);
  49320. if (this.getScene().getCachedMaterial() !== this) {
  49321. if (this._options.uniforms.indexOf("view") !== -1) {
  49322. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  49323. }
  49324. if (this._options.uniforms.indexOf("projection") !== -1) {
  49325. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  49326. }
  49327. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  49328. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  49329. }
  49330. // Bones
  49331. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  49332. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49333. }
  49334. var name;
  49335. // Texture
  49336. for (name in this._textures) {
  49337. this._effect.setTexture(name, this._textures[name]);
  49338. }
  49339. // Texture arrays
  49340. for (name in this._textureArrays) {
  49341. this._effect.setTextureArray(name, this._textureArrays[name]);
  49342. }
  49343. // Float
  49344. for (name in this._floats) {
  49345. this._effect.setFloat(name, this._floats[name]);
  49346. }
  49347. // Float s
  49348. for (name in this._floatsArrays) {
  49349. this._effect.setArray(name, this._floatsArrays[name]);
  49350. }
  49351. // Color3
  49352. for (name in this._colors3) {
  49353. this._effect.setColor3(name, this._colors3[name]);
  49354. }
  49355. // Color4
  49356. for (name in this._colors4) {
  49357. var color = this._colors4[name];
  49358. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  49359. }
  49360. // Vector2
  49361. for (name in this._vectors2) {
  49362. this._effect.setVector2(name, this._vectors2[name]);
  49363. }
  49364. // Vector3
  49365. for (name in this._vectors3) {
  49366. this._effect.setVector3(name, this._vectors3[name]);
  49367. }
  49368. // Vector4
  49369. for (name in this._vectors4) {
  49370. this._effect.setVector4(name, this._vectors4[name]);
  49371. }
  49372. // Matrix
  49373. for (name in this._matrices) {
  49374. this._effect.setMatrix(name, this._matrices[name]);
  49375. }
  49376. // Matrix 3x3
  49377. for (name in this._matrices3x3) {
  49378. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  49379. }
  49380. // Matrix 2x2
  49381. for (name in this._matrices2x2) {
  49382. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  49383. }
  49384. }
  49385. _super.prototype.bind.call(this, world, mesh);
  49386. };
  49387. ShaderMaterial.prototype.clone = function (name) {
  49388. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  49389. return newShaderMaterial;
  49390. };
  49391. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  49392. if (forceDisposeTextures) {
  49393. var name;
  49394. for (name in this._textures) {
  49395. this._textures[name].dispose();
  49396. }
  49397. for (name in this._textureArrays) {
  49398. var array = this._textureArrays[name];
  49399. for (var index = 0; index < array.length; index++) {
  49400. array[index].dispose();
  49401. }
  49402. }
  49403. }
  49404. this._textures = {};
  49405. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  49406. };
  49407. ShaderMaterial.prototype.serialize = function () {
  49408. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  49409. serializationObject.customType = "BABYLON.ShaderMaterial";
  49410. serializationObject.options = this._options;
  49411. serializationObject.shaderPath = this._shaderPath;
  49412. var name;
  49413. // Texture
  49414. serializationObject.textures = {};
  49415. for (name in this._textures) {
  49416. serializationObject.textures[name] = this._textures[name].serialize();
  49417. }
  49418. // Texture arrays
  49419. serializationObject.textureArrays = {};
  49420. for (name in this._textureArrays) {
  49421. serializationObject.textureArrays[name] = [];
  49422. var array = this._textureArrays[name];
  49423. for (var index = 0; index < array.length; index++) {
  49424. serializationObject.textureArrays[name].push(array[index].serialize());
  49425. }
  49426. }
  49427. // Float
  49428. serializationObject.floats = {};
  49429. for (name in this._floats) {
  49430. serializationObject.floats[name] = this._floats[name];
  49431. }
  49432. // Float s
  49433. serializationObject.floatArrays = {};
  49434. for (name in this._floatsArrays) {
  49435. serializationObject.floatArrays[name] = this._floatsArrays[name];
  49436. }
  49437. // Color3
  49438. serializationObject.colors3 = {};
  49439. for (name in this._colors3) {
  49440. serializationObject.colors3[name] = this._colors3[name].asArray();
  49441. }
  49442. // Color4
  49443. serializationObject.colors4 = {};
  49444. for (name in this._colors4) {
  49445. serializationObject.colors4[name] = this._colors4[name].asArray();
  49446. }
  49447. // Vector2
  49448. serializationObject.vectors2 = {};
  49449. for (name in this._vectors2) {
  49450. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  49451. }
  49452. // Vector3
  49453. serializationObject.vectors3 = {};
  49454. for (name in this._vectors3) {
  49455. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  49456. }
  49457. // Vector4
  49458. serializationObject.vectors4 = {};
  49459. for (name in this._vectors4) {
  49460. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  49461. }
  49462. // Matrix
  49463. serializationObject.matrices = {};
  49464. for (name in this._matrices) {
  49465. serializationObject.matrices[name] = this._matrices[name].asArray();
  49466. }
  49467. // Matrix 3x3
  49468. serializationObject.matrices3x3 = {};
  49469. for (name in this._matrices3x3) {
  49470. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  49471. }
  49472. // Matrix 2x2
  49473. serializationObject.matrices2x2 = {};
  49474. for (name in this._matrices2x2) {
  49475. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  49476. }
  49477. return serializationObject;
  49478. };
  49479. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  49480. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  49481. var name;
  49482. // Texture
  49483. for (name in source.textures) {
  49484. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  49485. }
  49486. // Texture arrays
  49487. for (name in source.textureArrays) {
  49488. var array = source.textureArrays[name];
  49489. var textureArray = new Array();
  49490. for (var index = 0; index < array.length; index++) {
  49491. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  49492. }
  49493. material.setTextureArray(name, textureArray);
  49494. }
  49495. // Float
  49496. for (name in source.floats) {
  49497. material.setFloat(name, source.floats[name]);
  49498. }
  49499. // Float s
  49500. for (name in source.floatsArrays) {
  49501. material.setFloats(name, source.floatsArrays[name]);
  49502. }
  49503. // Color3
  49504. for (name in source.colors3) {
  49505. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  49506. }
  49507. // Color4
  49508. for (name in source.colors4) {
  49509. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  49510. }
  49511. // Vector2
  49512. for (name in source.vectors2) {
  49513. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  49514. }
  49515. // Vector3
  49516. for (name in source.vectors3) {
  49517. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  49518. }
  49519. // Vector4
  49520. for (name in source.vectors4) {
  49521. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  49522. }
  49523. // Matrix
  49524. for (name in source.matrices) {
  49525. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  49526. }
  49527. // Matrix 3x3
  49528. for (name in source.matrices3x3) {
  49529. material.setMatrix3x3(name, source.matrices3x3[name]);
  49530. }
  49531. // Matrix 2x2
  49532. for (name in source.matrices2x2) {
  49533. material.setMatrix2x2(name, source.matrices2x2[name]);
  49534. }
  49535. return material;
  49536. };
  49537. return ShaderMaterial;
  49538. })(BABYLON.Material);
  49539. BABYLON.ShaderMaterial = ShaderMaterial;
  49540. })(BABYLON || (BABYLON = {}));
  49541. var BABYLON;
  49542. (function (BABYLON) {
  49543. var Internals;
  49544. (function (Internals) {
  49545. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  49546. // All values and structures referenced from:
  49547. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  49548. var DDS_MAGIC = 0x20534444;
  49549. 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;
  49550. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  49551. 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;
  49552. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  49553. function FourCCToInt32(value) {
  49554. return value.charCodeAt(0) +
  49555. (value.charCodeAt(1) << 8) +
  49556. (value.charCodeAt(2) << 16) +
  49557. (value.charCodeAt(3) << 24);
  49558. }
  49559. function Int32ToFourCC(value) {
  49560. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  49561. }
  49562. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  49563. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  49564. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  49565. var headerLengthInt = 31; // The header length in 32 bit ints
  49566. // Offsets into the header array
  49567. var off_magic = 0;
  49568. var off_size = 1;
  49569. var off_flags = 2;
  49570. var off_height = 3;
  49571. var off_width = 4;
  49572. var off_mipmapCount = 7;
  49573. var off_pfFlags = 20;
  49574. var off_pfFourCC = 21;
  49575. var off_RGBbpp = 22;
  49576. var off_RMask = 23;
  49577. var off_GMask = 24;
  49578. var off_BMask = 25;
  49579. var off_AMask = 26;
  49580. var off_caps1 = 27;
  49581. var off_caps2 = 28;
  49582. ;
  49583. var DDSTools = (function () {
  49584. function DDSTools() {
  49585. }
  49586. DDSTools.GetDDSInfo = function (arrayBuffer) {
  49587. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  49588. var mipmapCount = 1;
  49589. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  49590. mipmapCount = Math.max(1, header[off_mipmapCount]);
  49591. }
  49592. return {
  49593. width: header[off_width],
  49594. height: header[off_height],
  49595. mipmapCount: mipmapCount,
  49596. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  49597. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  49598. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  49599. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  49600. };
  49601. };
  49602. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49603. var byteArray = new Uint8Array(dataLength);
  49604. var srcData = new Uint8Array(arrayBuffer);
  49605. var index = 0;
  49606. for (var y = height - 1; y >= 0; y--) {
  49607. for (var x = 0; x < width; x++) {
  49608. var srcPos = dataOffset + (x + y * width) * 4;
  49609. byteArray[index + 2] = srcData[srcPos];
  49610. byteArray[index + 1] = srcData[srcPos + 1];
  49611. byteArray[index] = srcData[srcPos + 2];
  49612. byteArray[index + 3] = srcData[srcPos + 3];
  49613. index += 4;
  49614. }
  49615. }
  49616. return byteArray;
  49617. };
  49618. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49619. var byteArray = new Uint8Array(dataLength);
  49620. var srcData = new Uint8Array(arrayBuffer);
  49621. var index = 0;
  49622. for (var y = height - 1; y >= 0; y--) {
  49623. for (var x = 0; x < width; x++) {
  49624. var srcPos = dataOffset + (x + y * width) * 3;
  49625. byteArray[index + 2] = srcData[srcPos];
  49626. byteArray[index + 1] = srcData[srcPos + 1];
  49627. byteArray[index] = srcData[srcPos + 2];
  49628. index += 3;
  49629. }
  49630. }
  49631. return byteArray;
  49632. };
  49633. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49634. var byteArray = new Uint8Array(dataLength);
  49635. var srcData = new Uint8Array(arrayBuffer);
  49636. var index = 0;
  49637. for (var y = height - 1; y >= 0; y--) {
  49638. for (var x = 0; x < width; x++) {
  49639. var srcPos = dataOffset + (x + y * width);
  49640. byteArray[index] = srcData[srcPos];
  49641. index++;
  49642. }
  49643. }
  49644. return byteArray;
  49645. };
  49646. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  49647. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  49648. if (header[off_magic] != DDS_MAGIC) {
  49649. BABYLON.Tools.Error("Invalid magic number in DDS header");
  49650. return;
  49651. }
  49652. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  49653. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  49654. return;
  49655. }
  49656. if (info.isFourCC) {
  49657. fourCC = header[off_pfFourCC];
  49658. switch (fourCC) {
  49659. case FOURCC_DXT1:
  49660. blockBytes = 8;
  49661. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  49662. break;
  49663. case FOURCC_DXT3:
  49664. blockBytes = 16;
  49665. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  49666. break;
  49667. case FOURCC_DXT5:
  49668. blockBytes = 16;
  49669. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  49670. break;
  49671. default:
  49672. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  49673. return;
  49674. }
  49675. }
  49676. mipmapCount = 1;
  49677. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  49678. mipmapCount = Math.max(1, header[off_mipmapCount]);
  49679. }
  49680. var bpp = header[off_RGBbpp];
  49681. for (var face = 0; face < faces; face++) {
  49682. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  49683. width = header[off_width];
  49684. height = header[off_height];
  49685. dataOffset = header[off_size] + 4;
  49686. for (i = 0; i < mipmapCount; ++i) {
  49687. if (info.isRGB) {
  49688. if (bpp === 24) {
  49689. dataLength = width * height * 3;
  49690. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49691. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  49692. }
  49693. else {
  49694. dataLength = width * height * 4;
  49695. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49696. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  49697. }
  49698. }
  49699. else if (info.isLuminance) {
  49700. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  49701. var unpaddedRowSize = width;
  49702. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  49703. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  49704. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49705. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  49706. }
  49707. else {
  49708. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  49709. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  49710. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  49711. }
  49712. dataOffset += dataLength;
  49713. width *= 0.5;
  49714. height *= 0.5;
  49715. width = Math.max(1.0, width);
  49716. height = Math.max(1.0, height);
  49717. }
  49718. }
  49719. };
  49720. return DDSTools;
  49721. })();
  49722. Internals.DDSTools = DDSTools;
  49723. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49724. })(BABYLON || (BABYLON = {}));
  49725. var BABYLON;
  49726. (function (BABYLON) {
  49727. var CannonJSPlugin = (function () {
  49728. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  49729. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  49730. if (iterations === void 0) { iterations = 10; }
  49731. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  49732. this.name = "CannonJSPlugin";
  49733. this._physicsMaterials = [];
  49734. this._fixedTimeStep = 1 / 60;
  49735. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  49736. this._currentCollisionGroup = 2;
  49737. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  49738. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  49739. this._tmpPosition = BABYLON.Vector3.Zero();
  49740. this._tmpQuaternion = new BABYLON.Quaternion();
  49741. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  49742. this._tmpDeltaRotation = new BABYLON.Quaternion();
  49743. this._tmpUnityRotation = new BABYLON.Quaternion();
  49744. if (!this.isSupported()) {
  49745. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  49746. return;
  49747. }
  49748. this.world = new CANNON.World();
  49749. this.world.broadphase = new CANNON.NaiveBroadphase();
  49750. this.world.solver.iterations = iterations;
  49751. }
  49752. CannonJSPlugin.prototype.setGravity = function (gravity) {
  49753. this.world.gravity.copy(gravity);
  49754. };
  49755. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  49756. this._fixedTimeStep = timeStep;
  49757. };
  49758. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  49759. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  49760. };
  49761. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  49762. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  49763. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  49764. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  49765. };
  49766. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  49767. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  49768. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  49769. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  49770. };
  49771. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  49772. //parent-child relationship. Does this impostor has a parent impostor?
  49773. if (impostor.parent) {
  49774. if (impostor.physicsBody) {
  49775. this.removePhysicsBody(impostor);
  49776. //TODO is that needed?
  49777. impostor.forceUpdate();
  49778. }
  49779. return;
  49780. }
  49781. //should a new body be created for this impostor?
  49782. if (impostor.isBodyInitRequired()) {
  49783. var shape = this._createShape(impostor);
  49784. //unregister events, if body is being changed
  49785. var oldBody = impostor.physicsBody;
  49786. if (oldBody) {
  49787. this.removePhysicsBody(impostor);
  49788. }
  49789. //create the body and material
  49790. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  49791. var bodyCreationObject = {
  49792. mass: impostor.getParam("mass"),
  49793. material: material
  49794. };
  49795. // A simple extend, in case native options were used.
  49796. var nativeOptions = impostor.getParam("nativeOptions");
  49797. for (var key in nativeOptions) {
  49798. if (nativeOptions.hasOwnProperty(key)) {
  49799. bodyCreationObject[key] = nativeOptions[key];
  49800. }
  49801. }
  49802. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  49803. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  49804. this.world.addEventListener("preStep", impostor.beforeStep);
  49805. this.world.addEventListener("postStep", impostor.afterStep);
  49806. impostor.physicsBody.addShape(shape);
  49807. this.world.add(impostor.physicsBody);
  49808. //try to keep the body moving in the right direction by taking old properties.
  49809. //Should be tested!
  49810. if (oldBody) {
  49811. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  49812. impostor.physicsBody[param].copy(oldBody[param]);
  49813. });
  49814. }
  49815. this._processChildMeshes(impostor);
  49816. }
  49817. //now update the body's transformation
  49818. this._updatePhysicsBodyTransformation(impostor);
  49819. };
  49820. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  49821. var _this = this;
  49822. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  49823. if (meshChildren.length) {
  49824. var processMesh = function (localPosition, mesh) {
  49825. var childImpostor = mesh.getPhysicsImpostor();
  49826. if (childImpostor) {
  49827. var parent = childImpostor.parent;
  49828. if (parent !== mainImpostor) {
  49829. var localPosition = mesh.position;
  49830. if (childImpostor.physicsBody) {
  49831. _this.removePhysicsBody(childImpostor);
  49832. childImpostor.physicsBody = null;
  49833. }
  49834. childImpostor.parent = mainImpostor;
  49835. childImpostor.resetUpdateFlags();
  49836. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  49837. //Add the mass of the children.
  49838. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  49839. }
  49840. }
  49841. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  49842. };
  49843. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  49844. }
  49845. };
  49846. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  49847. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  49848. this.world.removeEventListener("preStep", impostor.beforeStep);
  49849. this.world.removeEventListener("postStep", impostor.afterStep);
  49850. this.world.remove(impostor.physicsBody);
  49851. };
  49852. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  49853. var mainBody = impostorJoint.mainImpostor.physicsBody;
  49854. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  49855. if (!mainBody || !connectedBody) {
  49856. return;
  49857. }
  49858. var constraint;
  49859. var jointData = impostorJoint.joint.jointData;
  49860. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  49861. var constraintData = {
  49862. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  49863. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  49864. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  49865. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  49866. maxForce: jointData.nativeParams.maxForce,
  49867. collideConnected: !!jointData.collision
  49868. };
  49869. //Not needed, Cannon has a collideConnected flag
  49870. /*if (!jointData.collision) {
  49871. //add 1st body to a collision group of its own, if it is not in 1
  49872. if (mainBody.collisionFilterGroup === 1) {
  49873. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  49874. this._currentCollisionGroup <<= 1;
  49875. }
  49876. if (connectedBody.collisionFilterGroup === 1) {
  49877. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  49878. this._currentCollisionGroup <<= 1;
  49879. }
  49880. //add their mask to the collisionFilterMask of each other:
  49881. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  49882. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  49883. }*/
  49884. switch (impostorJoint.joint.type) {
  49885. case BABYLON.PhysicsJoint.HingeJoint:
  49886. case BABYLON.PhysicsJoint.Hinge2Joint:
  49887. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  49888. break;
  49889. case BABYLON.PhysicsJoint.DistanceJoint:
  49890. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  49891. break;
  49892. case BABYLON.PhysicsJoint.SpringJoint:
  49893. var springData = jointData;
  49894. constraint = new CANNON.Spring(mainBody, connectedBody, {
  49895. restLength: springData.length,
  49896. stiffness: springData.stiffness,
  49897. damping: springData.damping,
  49898. localAnchorA: constraintData.pivotA,
  49899. localAnchorB: constraintData.pivotB
  49900. });
  49901. break;
  49902. case BABYLON.PhysicsJoint.LockJoint:
  49903. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  49904. break;
  49905. case BABYLON.PhysicsJoint.PointToPointJoint:
  49906. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  49907. default:
  49908. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  49909. break;
  49910. }
  49911. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  49912. constraint.collideConnected = !!jointData.collision;
  49913. impostorJoint.joint.physicsJoint = constraint;
  49914. //don't add spring as constraint, as it is not one.
  49915. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  49916. this.world.addConstraint(constraint);
  49917. }
  49918. else {
  49919. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  49920. constraint.applyForce();
  49921. });
  49922. }
  49923. };
  49924. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  49925. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  49926. };
  49927. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  49928. var index;
  49929. var mat;
  49930. for (index = 0; index < this._physicsMaterials.length; index++) {
  49931. mat = this._physicsMaterials[index];
  49932. if (mat.friction === friction && mat.restitution === restitution) {
  49933. return mat;
  49934. }
  49935. }
  49936. var currentMat = new CANNON.Material(name);
  49937. currentMat.friction = friction;
  49938. currentMat.restitution = restitution;
  49939. this._physicsMaterials.push(currentMat);
  49940. return currentMat;
  49941. };
  49942. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  49943. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  49944. };
  49945. CannonJSPlugin.prototype._createShape = function (impostor) {
  49946. var object = impostor.object;
  49947. var returnValue;
  49948. var extendSize = impostor.getObjectExtendSize();
  49949. switch (impostor.type) {
  49950. case BABYLON.PhysicsEngine.SphereImpostor:
  49951. var radiusX = extendSize.x;
  49952. var radiusY = extendSize.y;
  49953. var radiusZ = extendSize.z;
  49954. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  49955. break;
  49956. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  49957. case BABYLON.PhysicsImpostor.CylinderImpostor:
  49958. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  49959. break;
  49960. case BABYLON.PhysicsImpostor.BoxImpostor:
  49961. var box = extendSize.scale(0.5);
  49962. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  49963. break;
  49964. case BABYLON.PhysicsImpostor.PlaneImpostor:
  49965. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  49966. returnValue = new CANNON.Plane();
  49967. break;
  49968. case BABYLON.PhysicsImpostor.MeshImpostor:
  49969. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  49970. var rawFaces = object.getIndices ? object.getIndices() : [];
  49971. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  49972. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  49973. break;
  49974. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  49975. returnValue = this._createHeightmap(object);
  49976. break;
  49977. case BABYLON.PhysicsImpostor.ParticleImpostor:
  49978. returnValue = new CANNON.Particle();
  49979. break;
  49980. }
  49981. return returnValue;
  49982. };
  49983. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  49984. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49985. var matrix = [];
  49986. //For now pointDepth will not be used and will be automatically calculated.
  49987. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  49988. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  49989. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  49990. var elementSize = dim * 2 / arraySize;
  49991. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  49992. for (var i = 0; i < pos.length; i = i + 3) {
  49993. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  49994. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  49995. var y = pos[i + 1] + minY;
  49996. if (!matrix[x]) {
  49997. matrix[x] = [];
  49998. }
  49999. if (!matrix[x][z]) {
  50000. matrix[x][z] = y;
  50001. }
  50002. matrix[x][z] = Math.max(y, matrix[x][z]);
  50003. }
  50004. for (var x = 0; x <= arraySize; ++x) {
  50005. if (!matrix[x]) {
  50006. var loc = 1;
  50007. while (!matrix[(x + loc) % arraySize]) {
  50008. loc++;
  50009. }
  50010. matrix[x] = matrix[(x + loc) % arraySize].slice();
  50011. }
  50012. for (var z = 0; z <= arraySize; ++z) {
  50013. if (!matrix[x][z]) {
  50014. var loc = 1;
  50015. var newValue;
  50016. while (newValue === undefined) {
  50017. newValue = matrix[x][(z + loc++) % arraySize];
  50018. }
  50019. matrix[x][z] = newValue;
  50020. }
  50021. }
  50022. }
  50023. var shape = new CANNON.Heightfield(matrix, {
  50024. elementSize: elementSize
  50025. });
  50026. //For future reference, needed for body transformation
  50027. shape.minY = minY;
  50028. return shape;
  50029. };
  50030. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  50031. var object = impostor.object;
  50032. //make sure it is updated...
  50033. object.computeWorldMatrix && object.computeWorldMatrix(true);
  50034. // The delta between the mesh position and the mesh bounding box center
  50035. var center = impostor.getObjectCenter();
  50036. var extendSize = impostor.getObjectExtendSize();
  50037. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  50038. this._tmpPosition.copyFrom(center);
  50039. var quaternion = object.rotationQuaternion;
  50040. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  50041. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  50042. //-90 DEG in X, precalculated
  50043. quaternion = quaternion.multiply(this._minus90X);
  50044. //Invert! (Precalculated, 90 deg in X)
  50045. //No need to clone. this will never change.
  50046. impostor.setDeltaRotation(this._plus90X);
  50047. }
  50048. //If it is a heightfield, if should be centered.
  50049. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  50050. var mesh = object;
  50051. //calculate the correct body position:
  50052. var rotationQuaternion = mesh.rotationQuaternion;
  50053. mesh.rotationQuaternion = this._tmpUnityRotation;
  50054. mesh.computeWorldMatrix(true);
  50055. //get original center with no rotation
  50056. var c = center.clone();
  50057. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  50058. //rotation is back
  50059. mesh.rotationQuaternion = rotationQuaternion;
  50060. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  50061. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  50062. mesh.setPivotMatrix(p);
  50063. mesh.computeWorldMatrix(true);
  50064. //calculate the translation
  50065. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  50066. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  50067. //add it inverted to the delta
  50068. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  50069. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  50070. mesh.setPivotMatrix(oldPivot);
  50071. mesh.computeWorldMatrix(true);
  50072. }
  50073. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  50074. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  50075. this._tmpPosition.copyFrom(object.position);
  50076. }
  50077. impostor.setDeltaPosition(this._tmpDeltaPosition);
  50078. //Now update the impostor object
  50079. impostor.physicsBody.position.copy(this._tmpPosition);
  50080. impostor.physicsBody.quaternion.copy(quaternion);
  50081. };
  50082. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  50083. impostor.object.position.copyFrom(impostor.physicsBody.position);
  50084. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  50085. };
  50086. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  50087. impostor.physicsBody.position.copy(newPosition);
  50088. impostor.physicsBody.quaternion.copy(newRotation);
  50089. };
  50090. CannonJSPlugin.prototype.isSupported = function () {
  50091. return window.CANNON !== undefined;
  50092. };
  50093. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  50094. impostor.physicsBody.velocity.copy(velocity);
  50095. };
  50096. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  50097. impostor.physicsBody.angularVelocity.copy(velocity);
  50098. };
  50099. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  50100. var v = impostor.physicsBody.velocity;
  50101. if (!v)
  50102. return null;
  50103. return new BABYLON.Vector3(v.x, v.y, v.z);
  50104. };
  50105. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  50106. var v = impostor.physicsBody.angularVelocity;
  50107. if (!v)
  50108. return null;
  50109. return new BABYLON.Vector3(v.x, v.y, v.z);
  50110. };
  50111. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  50112. impostor.physicsBody.mass = mass;
  50113. impostor.physicsBody.updateMassProperties();
  50114. };
  50115. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  50116. impostor.physicsBody.sleep();
  50117. };
  50118. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  50119. impostor.physicsBody.wakeUp();
  50120. };
  50121. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  50122. joint.physicsJoint.distance = maxDistance;
  50123. };
  50124. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  50125. if (!motorIndex) {
  50126. joint.physicsJoint.enableMotor();
  50127. }
  50128. };
  50129. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  50130. if (!motorIndex) {
  50131. joint.physicsJoint.disableMotor();
  50132. }
  50133. };
  50134. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  50135. if (!motorIndex) {
  50136. joint.physicsJoint.enableMotor();
  50137. joint.physicsJoint.setMotorSpeed(speed);
  50138. if (maxForce) {
  50139. this.setLimit(joint, maxForce);
  50140. }
  50141. }
  50142. };
  50143. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  50144. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  50145. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  50146. };
  50147. CannonJSPlugin.prototype.dispose = function () {
  50148. //nothing to do, actually.
  50149. };
  50150. return CannonJSPlugin;
  50151. })();
  50152. BABYLON.CannonJSPlugin = CannonJSPlugin;
  50153. })(BABYLON || (BABYLON = {}));
  50154. var BABYLON;
  50155. (function (BABYLON) {
  50156. var OimoJSPlugin = (function () {
  50157. function OimoJSPlugin(iterations) {
  50158. this.name = "OimoJSPlugin";
  50159. this._tmpImpostorsArray = [];
  50160. this._tmpPositionVector = BABYLON.Vector3.Zero();
  50161. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  50162. this.world.clear();
  50163. //making sure no stats are calculated
  50164. this.world.isNoStat = true;
  50165. }
  50166. OimoJSPlugin.prototype.setGravity = function (gravity) {
  50167. this.world.gravity.copy(gravity);
  50168. };
  50169. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  50170. this.world.timeStep = timeStep;
  50171. };
  50172. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  50173. var _this = this;
  50174. impostors.forEach(function (impostor) {
  50175. impostor.beforeStep();
  50176. });
  50177. this.world.step();
  50178. impostors.forEach(function (impostor) {
  50179. impostor.afterStep();
  50180. //update the ordered impostors array
  50181. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  50182. });
  50183. //check for collisions
  50184. var contact = this.world.contacts;
  50185. while (contact !== null) {
  50186. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  50187. contact = contact.next;
  50188. continue;
  50189. }
  50190. //is this body colliding with any other? get the impostor
  50191. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  50192. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  50193. if (!mainImpostor || !collidingImpostor) {
  50194. contact = contact.next;
  50195. continue;
  50196. }
  50197. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  50198. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  50199. contact = contact.next;
  50200. }
  50201. };
  50202. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  50203. var mass = impostor.physicsBody.massInfo.mass;
  50204. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  50205. };
  50206. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  50207. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  50208. this.applyImpulse(impostor, force, contactPoint);
  50209. };
  50210. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  50211. var _this = this;
  50212. //parent-child relationship. Does this impostor has a parent impostor?
  50213. if (impostor.parent) {
  50214. if (impostor.physicsBody) {
  50215. this.removePhysicsBody(impostor);
  50216. //TODO is that needed?
  50217. impostor.forceUpdate();
  50218. }
  50219. return;
  50220. }
  50221. if (impostor.isBodyInitRequired()) {
  50222. var bodyConfig = {
  50223. name: impostor.uniqueId,
  50224. //Oimo must have mass, also for static objects.
  50225. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  50226. size: [],
  50227. type: [],
  50228. pos: [],
  50229. rot: [],
  50230. move: impostor.getParam("mass") !== 0,
  50231. //Supporting older versions of Oimo
  50232. world: this.world
  50233. };
  50234. var impostors = [impostor];
  50235. function addToArray(parent) {
  50236. if (!parent.getChildMeshes)
  50237. return;
  50238. parent.getChildMeshes().forEach(function (m) {
  50239. if (m.physicsImpostor) {
  50240. impostors.push(m.physicsImpostor);
  50241. m.physicsImpostor._init();
  50242. }
  50243. });
  50244. }
  50245. addToArray(impostor.object);
  50246. function checkWithEpsilon(value) {
  50247. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  50248. }
  50249. impostors.forEach(function (i) {
  50250. //get the correct bounding box
  50251. var oldQuaternion = i.object.rotationQuaternion;
  50252. var rot = new OIMO.Euler().setFromQuaternion({
  50253. x: impostor.object.rotationQuaternion.x,
  50254. y: impostor.object.rotationQuaternion.y,
  50255. z: impostor.object.rotationQuaternion.z,
  50256. s: impostor.object.rotationQuaternion.w
  50257. });
  50258. var extendSize = i.getObjectExtendSize();
  50259. if (i === impostor) {
  50260. var center = impostor.getObjectCenter();
  50261. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  50262. //Can also use Array.prototype.push.apply
  50263. bodyConfig.pos.push(center.x);
  50264. bodyConfig.pos.push(center.y);
  50265. bodyConfig.pos.push(center.z);
  50266. //tmp solution
  50267. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  50268. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  50269. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  50270. }
  50271. else {
  50272. bodyConfig.pos.push(i.object.position.x);
  50273. bodyConfig.pos.push(i.object.position.y);
  50274. bodyConfig.pos.push(i.object.position.z);
  50275. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  50276. bodyConfig.rot.push(0);
  50277. bodyConfig.rot.push(0);
  50278. bodyConfig.rot.push(0);
  50279. }
  50280. // register mesh
  50281. switch (i.type) {
  50282. case BABYLON.PhysicsImpostor.ParticleImpostor:
  50283. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  50284. case BABYLON.PhysicsImpostor.SphereImpostor:
  50285. var radiusX = extendSize.x;
  50286. var radiusY = extendSize.y;
  50287. var radiusZ = extendSize.z;
  50288. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  50289. bodyConfig.type.push('sphere');
  50290. //due to the way oimo works with compounds, add 3 times
  50291. bodyConfig.size.push(size);
  50292. bodyConfig.size.push(size);
  50293. bodyConfig.size.push(size);
  50294. break;
  50295. case BABYLON.PhysicsImpostor.CylinderImpostor:
  50296. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  50297. var sizeY = checkWithEpsilon(extendSize.y);
  50298. bodyConfig.type.push('cylinder');
  50299. bodyConfig.size.push(sizeX);
  50300. bodyConfig.size.push(sizeY);
  50301. //due to the way oimo works with compounds, add one more value.
  50302. bodyConfig.size.push(sizeY);
  50303. break;
  50304. case BABYLON.PhysicsImpostor.PlaneImpostor:
  50305. case BABYLON.PhysicsImpostor.BoxImpostor:
  50306. default:
  50307. var sizeX = checkWithEpsilon(extendSize.x);
  50308. var sizeY = checkWithEpsilon(extendSize.y);
  50309. var sizeZ = checkWithEpsilon(extendSize.z);
  50310. bodyConfig.type.push('box');
  50311. bodyConfig.size.push(sizeX);
  50312. bodyConfig.size.push(sizeY);
  50313. bodyConfig.size.push(sizeZ);
  50314. break;
  50315. }
  50316. //actually not needed, but hey...
  50317. i.object.rotationQuaternion = oldQuaternion;
  50318. });
  50319. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  50320. }
  50321. else {
  50322. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  50323. }
  50324. impostor.setDeltaPosition(this._tmpPositionVector);
  50325. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  50326. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  50327. };
  50328. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  50329. //impostor.physicsBody.dispose();
  50330. //Same as : (older oimo versions)
  50331. this.world.removeRigidBody(impostor.physicsBody);
  50332. };
  50333. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  50334. var mainBody = impostorJoint.mainImpostor.physicsBody;
  50335. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  50336. if (!mainBody || !connectedBody) {
  50337. return;
  50338. }
  50339. var jointData = impostorJoint.joint.jointData;
  50340. var options = jointData.nativeParams || {};
  50341. var type;
  50342. var nativeJointData = {
  50343. body1: mainBody,
  50344. body2: connectedBody,
  50345. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  50346. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  50347. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  50348. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  50349. min: options.min,
  50350. max: options.max,
  50351. collision: options.collision || jointData.collision,
  50352. spring: options.spring,
  50353. //supporting older version of Oimo
  50354. world: this.world
  50355. };
  50356. switch (impostorJoint.joint.type) {
  50357. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  50358. type = "jointBall";
  50359. break;
  50360. case BABYLON.PhysicsJoint.SpringJoint:
  50361. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  50362. var springData = jointData;
  50363. nativeJointData.min = springData.length || nativeJointData.min;
  50364. //Max should also be set, just make sure it is at least min
  50365. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  50366. case BABYLON.PhysicsJoint.DistanceJoint:
  50367. type = "jointDistance";
  50368. nativeJointData.max = jointData.maxDistance;
  50369. break;
  50370. case BABYLON.PhysicsJoint.PrismaticJoint:
  50371. type = "jointPrisme";
  50372. break;
  50373. case BABYLON.PhysicsJoint.SliderJoint:
  50374. type = "jointSlide";
  50375. break;
  50376. case BABYLON.PhysicsJoint.WheelJoint:
  50377. type = "jointWheel";
  50378. break;
  50379. case BABYLON.PhysicsJoint.HingeJoint:
  50380. default:
  50381. type = "jointHinge";
  50382. break;
  50383. }
  50384. nativeJointData.type = type;
  50385. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  50386. };
  50387. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  50388. //Bug in Oimo prevents us from disposing a joint in the playground
  50389. //joint.joint.physicsJoint.dispose();
  50390. //So we will bruteforce it!
  50391. try {
  50392. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  50393. }
  50394. catch (e) {
  50395. BABYLON.Tools.Warn(e);
  50396. }
  50397. };
  50398. OimoJSPlugin.prototype.isSupported = function () {
  50399. return OIMO !== undefined;
  50400. };
  50401. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  50402. if (!impostor.physicsBody.sleeping) {
  50403. //TODO check that
  50404. if (impostor.physicsBody.shapes.next) {
  50405. var parentShape = this._getLastShape(impostor.physicsBody);
  50406. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  50407. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  50408. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  50409. }
  50410. else {
  50411. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  50412. }
  50413. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  50414. impostor.object.rotationQuaternion.normalize();
  50415. }
  50416. };
  50417. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  50418. var body = impostor.physicsBody;
  50419. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  50420. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  50421. body.syncShapes();
  50422. body.awake();
  50423. };
  50424. OimoJSPlugin.prototype._getLastShape = function (body) {
  50425. var lastShape = body.shapes;
  50426. while (lastShape.next) {
  50427. lastShape = lastShape.next;
  50428. }
  50429. return lastShape;
  50430. };
  50431. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  50432. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  50433. };
  50434. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  50435. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  50436. };
  50437. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  50438. var v = impostor.physicsBody.linearVelocity;
  50439. if (!v)
  50440. return null;
  50441. return new BABYLON.Vector3(v.x, v.y, v.z);
  50442. };
  50443. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  50444. var v = impostor.physicsBody.angularVelocity;
  50445. if (!v)
  50446. return null;
  50447. return new BABYLON.Vector3(v.x, v.y, v.z);
  50448. };
  50449. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  50450. var staticBody = mass === 0;
  50451. //this will actually set the body's density and not its mass.
  50452. //But this is how oimo treats the mass variable.
  50453. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  50454. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  50455. };
  50456. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  50457. impostor.physicsBody.sleep();
  50458. };
  50459. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  50460. impostor.physicsBody.awake();
  50461. };
  50462. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  50463. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  50464. if (minDistance !== void 0) {
  50465. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  50466. }
  50467. };
  50468. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  50469. //TODO separate rotational and transational motors.
  50470. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  50471. if (motor) {
  50472. motor.setMotor(speed, maxForce);
  50473. }
  50474. };
  50475. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  50476. //TODO separate rotational and transational motors.
  50477. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  50478. if (motor) {
  50479. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  50480. }
  50481. };
  50482. OimoJSPlugin.prototype.dispose = function () {
  50483. this.world.clear();
  50484. };
  50485. return OimoJSPlugin;
  50486. })();
  50487. BABYLON.OimoJSPlugin = OimoJSPlugin;
  50488. })(BABYLON || (BABYLON = {}));
  50489. var BABYLON;
  50490. (function (BABYLON) {
  50491. var DisplayPassPostProcess = (function (_super) {
  50492. __extends(DisplayPassPostProcess, _super);
  50493. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  50494. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  50495. }
  50496. return DisplayPassPostProcess;
  50497. })(BABYLON.PostProcess);
  50498. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  50499. })(BABYLON || (BABYLON = {}));
  50500. var BABYLON;
  50501. (function (BABYLON) {
  50502. var SimplificationSettings = (function () {
  50503. function SimplificationSettings(quality, distance, optimizeMesh) {
  50504. this.quality = quality;
  50505. this.distance = distance;
  50506. this.optimizeMesh = optimizeMesh;
  50507. }
  50508. return SimplificationSettings;
  50509. })();
  50510. BABYLON.SimplificationSettings = SimplificationSettings;
  50511. var SimplificationQueue = (function () {
  50512. function SimplificationQueue() {
  50513. this.running = false;
  50514. this._simplificationArray = [];
  50515. }
  50516. SimplificationQueue.prototype.addTask = function (task) {
  50517. this._simplificationArray.push(task);
  50518. };
  50519. SimplificationQueue.prototype.executeNext = function () {
  50520. var task = this._simplificationArray.pop();
  50521. if (task) {
  50522. this.running = true;
  50523. this.runSimplification(task);
  50524. }
  50525. else {
  50526. this.running = false;
  50527. }
  50528. };
  50529. SimplificationQueue.prototype.runSimplification = function (task) {
  50530. var _this = this;
  50531. if (task.parallelProcessing) {
  50532. //parallel simplifier
  50533. task.settings.forEach(function (setting) {
  50534. var simplifier = _this.getSimplifier(task);
  50535. simplifier.simplify(setting, function (newMesh) {
  50536. task.mesh.addLODLevel(setting.distance, newMesh);
  50537. newMesh.isVisible = true;
  50538. //check if it is the last
  50539. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  50540. //all done, run the success callback.
  50541. task.successCallback();
  50542. }
  50543. _this.executeNext();
  50544. });
  50545. });
  50546. }
  50547. else {
  50548. //single simplifier.
  50549. var simplifier = this.getSimplifier(task);
  50550. var runDecimation = function (setting, callback) {
  50551. simplifier.simplify(setting, function (newMesh) {
  50552. task.mesh.addLODLevel(setting.distance, newMesh);
  50553. newMesh.isVisible = true;
  50554. //run the next quality level
  50555. callback();
  50556. });
  50557. };
  50558. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  50559. runDecimation(task.settings[loop.index], function () {
  50560. loop.executeNext();
  50561. });
  50562. }, function () {
  50563. //execution ended, run the success callback.
  50564. if (task.successCallback) {
  50565. task.successCallback();
  50566. }
  50567. _this.executeNext();
  50568. });
  50569. }
  50570. };
  50571. SimplificationQueue.prototype.getSimplifier = function (task) {
  50572. switch (task.simplificationType) {
  50573. case SimplificationType.QUADRATIC:
  50574. default:
  50575. return new QuadraticErrorSimplification(task.mesh);
  50576. }
  50577. };
  50578. return SimplificationQueue;
  50579. })();
  50580. BABYLON.SimplificationQueue = SimplificationQueue;
  50581. /**
  50582. * The implemented types of simplification.
  50583. * At the moment only Quadratic Error Decimation is implemented.
  50584. */
  50585. (function (SimplificationType) {
  50586. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  50587. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  50588. var SimplificationType = BABYLON.SimplificationType;
  50589. var DecimationTriangle = (function () {
  50590. function DecimationTriangle(vertices) {
  50591. this.vertices = vertices;
  50592. this.error = new Array(4);
  50593. this.deleted = false;
  50594. this.isDirty = false;
  50595. this.deletePending = false;
  50596. this.borderFactor = 0;
  50597. }
  50598. return DecimationTriangle;
  50599. })();
  50600. BABYLON.DecimationTriangle = DecimationTriangle;
  50601. var DecimationVertex = (function () {
  50602. function DecimationVertex(position, id) {
  50603. this.position = position;
  50604. this.id = id;
  50605. this.isBorder = true;
  50606. this.q = new QuadraticMatrix();
  50607. this.triangleCount = 0;
  50608. this.triangleStart = 0;
  50609. this.originalOffsets = [];
  50610. }
  50611. DecimationVertex.prototype.updatePosition = function (newPosition) {
  50612. this.position.copyFrom(newPosition);
  50613. };
  50614. return DecimationVertex;
  50615. })();
  50616. BABYLON.DecimationVertex = DecimationVertex;
  50617. var QuadraticMatrix = (function () {
  50618. function QuadraticMatrix(data) {
  50619. this.data = new Array(10);
  50620. for (var i = 0; i < 10; ++i) {
  50621. if (data && data[i]) {
  50622. this.data[i] = data[i];
  50623. }
  50624. else {
  50625. this.data[i] = 0;
  50626. }
  50627. }
  50628. }
  50629. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  50630. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  50631. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  50632. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  50633. return det;
  50634. };
  50635. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  50636. for (var i = 0; i < 10; ++i) {
  50637. this.data[i] += matrix.data[i];
  50638. }
  50639. };
  50640. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  50641. for (var i = 0; i < 10; ++i) {
  50642. this.data[i] += data[i];
  50643. }
  50644. };
  50645. QuadraticMatrix.prototype.add = function (matrix) {
  50646. var m = new QuadraticMatrix();
  50647. for (var i = 0; i < 10; ++i) {
  50648. m.data[i] = this.data[i] + matrix.data[i];
  50649. }
  50650. return m;
  50651. };
  50652. QuadraticMatrix.FromData = function (a, b, c, d) {
  50653. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  50654. };
  50655. //returning an array to avoid garbage collection
  50656. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  50657. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  50658. };
  50659. return QuadraticMatrix;
  50660. })();
  50661. BABYLON.QuadraticMatrix = QuadraticMatrix;
  50662. var Reference = (function () {
  50663. function Reference(vertexId, triangleId) {
  50664. this.vertexId = vertexId;
  50665. this.triangleId = triangleId;
  50666. }
  50667. return Reference;
  50668. })();
  50669. BABYLON.Reference = Reference;
  50670. /**
  50671. * An implementation of the Quadratic Error simplification algorithm.
  50672. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  50673. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  50674. * @author RaananW
  50675. */
  50676. var QuadraticErrorSimplification = (function () {
  50677. function QuadraticErrorSimplification(_mesh) {
  50678. this._mesh = _mesh;
  50679. this.initialized = false;
  50680. this.syncIterations = 5000;
  50681. this.aggressiveness = 7;
  50682. this.decimationIterations = 100;
  50683. this.boundingBoxEpsilon = BABYLON.Epsilon;
  50684. }
  50685. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  50686. var _this = this;
  50687. this.initDecimatedMesh();
  50688. //iterating through the submeshes array, one after the other.
  50689. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  50690. _this.initWithMesh(loop.index, function () {
  50691. _this.runDecimation(settings, loop.index, function () {
  50692. loop.executeNext();
  50693. });
  50694. }, settings.optimizeMesh);
  50695. }, function () {
  50696. setTimeout(function () {
  50697. successCallback(_this._reconstructedMesh);
  50698. }, 0);
  50699. });
  50700. };
  50701. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  50702. var _this = this;
  50703. var gCount = 0;
  50704. triangle.vertices.forEach(function (vertex) {
  50705. var count = 0;
  50706. var vPos = vertex.position;
  50707. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  50708. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  50709. ++count;
  50710. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  50711. ++count;
  50712. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  50713. ++count;
  50714. if (count > 1) {
  50715. ++gCount;
  50716. }
  50717. ;
  50718. });
  50719. if (gCount > 1) {
  50720. console.log(triangle, gCount);
  50721. }
  50722. return gCount > 1;
  50723. };
  50724. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  50725. var _this = this;
  50726. var targetCount = ~~(this.triangles.length * settings.quality);
  50727. var deletedTriangles = 0;
  50728. var triangleCount = this.triangles.length;
  50729. var iterationFunction = function (iteration, callback) {
  50730. setTimeout(function () {
  50731. if (iteration % 5 === 0) {
  50732. _this.updateMesh(iteration === 0);
  50733. }
  50734. for (var i = 0; i < _this.triangles.length; ++i) {
  50735. _this.triangles[i].isDirty = false;
  50736. }
  50737. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  50738. var trianglesIterator = function (i) {
  50739. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  50740. var t = _this.triangles[tIdx];
  50741. if (!t)
  50742. return;
  50743. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  50744. return;
  50745. }
  50746. for (var j = 0; j < 3; ++j) {
  50747. if (t.error[j] < threshold) {
  50748. var deleted0 = [];
  50749. var deleted1 = [];
  50750. var v0 = t.vertices[j];
  50751. var v1 = t.vertices[(j + 1) % 3];
  50752. if (v0.isBorder || v1.isBorder)
  50753. continue;
  50754. var p = BABYLON.Vector3.Zero();
  50755. var n = BABYLON.Vector3.Zero();
  50756. var uv = BABYLON.Vector2.Zero();
  50757. var color = new BABYLON.Color4(0, 0, 0, 1);
  50758. _this.calculateError(v0, v1, p, n, uv, color);
  50759. var delTr = [];
  50760. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  50761. continue;
  50762. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  50763. continue;
  50764. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  50765. continue;
  50766. var uniqueArray = [];
  50767. delTr.forEach(function (deletedT) {
  50768. if (uniqueArray.indexOf(deletedT) === -1) {
  50769. deletedT.deletePending = true;
  50770. uniqueArray.push(deletedT);
  50771. }
  50772. });
  50773. if (uniqueArray.length % 2 !== 0) {
  50774. continue;
  50775. }
  50776. v0.q = v1.q.add(v0.q);
  50777. v0.updatePosition(p);
  50778. var tStart = _this.references.length;
  50779. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  50780. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  50781. var tCount = _this.references.length - tStart;
  50782. if (tCount <= v0.triangleCount) {
  50783. if (tCount) {
  50784. for (var c = 0; c < tCount; c++) {
  50785. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  50786. }
  50787. }
  50788. }
  50789. else {
  50790. v0.triangleStart = tStart;
  50791. }
  50792. v0.triangleCount = tCount;
  50793. break;
  50794. }
  50795. }
  50796. };
  50797. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  50798. }, 0);
  50799. };
  50800. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  50801. if (triangleCount - deletedTriangles <= targetCount)
  50802. loop.breakLoop();
  50803. else {
  50804. iterationFunction(loop.index, function () {
  50805. loop.executeNext();
  50806. });
  50807. }
  50808. }, function () {
  50809. setTimeout(function () {
  50810. //reconstruct this part of the mesh
  50811. _this.reconstructMesh(submeshIndex);
  50812. successCallback();
  50813. }, 0);
  50814. });
  50815. };
  50816. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  50817. var _this = this;
  50818. this.vertices = [];
  50819. this.triangles = [];
  50820. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50821. var indices = this._mesh.getIndices();
  50822. var submesh = this._mesh.subMeshes[submeshIndex];
  50823. var findInVertices = function (positionToSearch) {
  50824. if (optimizeMesh) {
  50825. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  50826. if (_this.vertices[ii].position.equals(positionToSearch)) {
  50827. return _this.vertices[ii];
  50828. }
  50829. }
  50830. }
  50831. return null;
  50832. };
  50833. var vertexReferences = [];
  50834. var vertexInit = function (i) {
  50835. var offset = i + submesh.verticesStart;
  50836. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  50837. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  50838. vertex.originalOffsets.push(offset);
  50839. if (vertex.id === _this.vertices.length) {
  50840. _this.vertices.push(vertex);
  50841. }
  50842. vertexReferences.push(vertex.id);
  50843. };
  50844. //var totalVertices = mesh.getTotalVertices();
  50845. var totalVertices = submesh.verticesCount;
  50846. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  50847. var indicesInit = function (i) {
  50848. var offset = (submesh.indexStart / 3) + i;
  50849. var pos = (offset * 3);
  50850. var i0 = indices[pos + 0];
  50851. var i1 = indices[pos + 1];
  50852. var i2 = indices[pos + 2];
  50853. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  50854. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  50855. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  50856. var triangle = new DecimationTriangle([v0, v1, v2]);
  50857. triangle.originalOffset = pos;
  50858. _this.triangles.push(triangle);
  50859. };
  50860. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  50861. _this.init(callback);
  50862. });
  50863. });
  50864. };
  50865. QuadraticErrorSimplification.prototype.init = function (callback) {
  50866. var _this = this;
  50867. var triangleInit1 = function (i) {
  50868. var t = _this.triangles[i];
  50869. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  50870. for (var j = 0; j < 3; j++) {
  50871. 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))));
  50872. }
  50873. };
  50874. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  50875. var triangleInit2 = function (i) {
  50876. var t = _this.triangles[i];
  50877. for (var j = 0; j < 3; ++j) {
  50878. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  50879. }
  50880. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  50881. };
  50882. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  50883. _this.initialized = true;
  50884. callback();
  50885. });
  50886. });
  50887. };
  50888. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  50889. var newTriangles = [];
  50890. var i;
  50891. for (i = 0; i < this.vertices.length; ++i) {
  50892. this.vertices[i].triangleCount = 0;
  50893. }
  50894. var t;
  50895. var j;
  50896. for (i = 0; i < this.triangles.length; ++i) {
  50897. if (!this.triangles[i].deleted) {
  50898. t = this.triangles[i];
  50899. for (j = 0; j < 3; ++j) {
  50900. t.vertices[j].triangleCount = 1;
  50901. }
  50902. newTriangles.push(t);
  50903. }
  50904. }
  50905. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  50906. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  50907. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  50908. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  50909. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50910. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50911. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50912. var vertexCount = 0;
  50913. for (i = 0; i < this.vertices.length; ++i) {
  50914. var vertex = this.vertices[i];
  50915. vertex.id = vertexCount;
  50916. if (vertex.triangleCount) {
  50917. vertex.originalOffsets.forEach(function (originalOffset) {
  50918. newPositionData.push(vertex.position.x);
  50919. newPositionData.push(vertex.position.y);
  50920. newPositionData.push(vertex.position.z);
  50921. newNormalData.push(normalData[originalOffset * 3]);
  50922. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  50923. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  50924. if (uvs && uvs.length) {
  50925. newUVsData.push(uvs[(originalOffset * 2)]);
  50926. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  50927. }
  50928. else if (colorsData && colorsData.length) {
  50929. newColorsData.push(colorsData[(originalOffset * 4)]);
  50930. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  50931. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  50932. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  50933. }
  50934. ++vertexCount;
  50935. });
  50936. }
  50937. }
  50938. var startingIndex = this._reconstructedMesh.getTotalIndices();
  50939. var startingVertex = this._reconstructedMesh.getTotalVertices();
  50940. var submeshesArray = this._reconstructedMesh.subMeshes;
  50941. this._reconstructedMesh.subMeshes = [];
  50942. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  50943. var originalIndices = this._mesh.getIndices();
  50944. for (i = 0; i < newTriangles.length; ++i) {
  50945. t = newTriangles[i]; //now get the new referencing point for each vertex
  50946. [0, 1, 2].forEach(function (idx) {
  50947. var id = originalIndices[t.originalOffset + idx];
  50948. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  50949. if (offset < 0)
  50950. offset = 0;
  50951. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  50952. });
  50953. }
  50954. //overwriting the old vertex buffers and indices.
  50955. this._reconstructedMesh.setIndices(newIndicesArray);
  50956. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  50957. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  50958. if (newUVsData.length > 0)
  50959. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  50960. if (newColorsData.length > 0)
  50961. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  50962. //create submesh
  50963. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  50964. if (submeshIndex > 0) {
  50965. this._reconstructedMesh.subMeshes = [];
  50966. submeshesArray.forEach(function (submesh) {
  50967. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  50968. });
  50969. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  50970. }
  50971. };
  50972. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  50973. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  50974. this._reconstructedMesh.material = this._mesh.material;
  50975. this._reconstructedMesh.parent = this._mesh.parent;
  50976. this._reconstructedMesh.isVisible = false;
  50977. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  50978. };
  50979. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  50980. for (var i = 0; i < vertex1.triangleCount; ++i) {
  50981. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  50982. if (t.deleted)
  50983. continue;
  50984. var s = this.references[vertex1.triangleStart + i].vertexId;
  50985. var v1 = t.vertices[(s + 1) % 3];
  50986. var v2 = t.vertices[(s + 2) % 3];
  50987. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  50988. deletedArray[i] = true;
  50989. delTr.push(t);
  50990. continue;
  50991. }
  50992. var d1 = v1.position.subtract(point);
  50993. d1 = d1.normalize();
  50994. var d2 = v2.position.subtract(point);
  50995. d2 = d2.normalize();
  50996. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  50997. return true;
  50998. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  50999. deletedArray[i] = false;
  51000. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  51001. return true;
  51002. }
  51003. return false;
  51004. };
  51005. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  51006. var newDeleted = deletedTriangles;
  51007. for (var i = 0; i < vertex.triangleCount; ++i) {
  51008. var ref = this.references[vertex.triangleStart + i];
  51009. var t = this.triangles[ref.triangleId];
  51010. if (t.deleted)
  51011. continue;
  51012. if (deletedArray[i] && t.deletePending) {
  51013. t.deleted = true;
  51014. newDeleted++;
  51015. continue;
  51016. }
  51017. t.vertices[ref.vertexId] = origVertex;
  51018. t.isDirty = true;
  51019. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  51020. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  51021. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  51022. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  51023. this.references.push(ref);
  51024. }
  51025. return newDeleted;
  51026. };
  51027. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  51028. for (var i = 0; i < this.vertices.length; ++i) {
  51029. var vCount = [];
  51030. var vId = [];
  51031. var v = this.vertices[i];
  51032. var j;
  51033. for (j = 0; j < v.triangleCount; ++j) {
  51034. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  51035. for (var ii = 0; ii < 3; ii++) {
  51036. var ofs = 0;
  51037. var vv = triangle.vertices[ii];
  51038. while (ofs < vCount.length) {
  51039. if (vId[ofs] === vv.id)
  51040. break;
  51041. ++ofs;
  51042. }
  51043. if (ofs === vCount.length) {
  51044. vCount.push(1);
  51045. vId.push(vv.id);
  51046. }
  51047. else {
  51048. vCount[ofs]++;
  51049. }
  51050. }
  51051. }
  51052. for (j = 0; j < vCount.length; ++j) {
  51053. if (vCount[j] === 1) {
  51054. this.vertices[vId[j]].isBorder = true;
  51055. }
  51056. else {
  51057. this.vertices[vId[j]].isBorder = false;
  51058. }
  51059. }
  51060. }
  51061. };
  51062. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  51063. if (identifyBorders === void 0) { identifyBorders = false; }
  51064. var i;
  51065. if (!identifyBorders) {
  51066. var newTrianglesVector = [];
  51067. for (i = 0; i < this.triangles.length; ++i) {
  51068. if (!this.triangles[i].deleted) {
  51069. newTrianglesVector.push(this.triangles[i]);
  51070. }
  51071. }
  51072. this.triangles = newTrianglesVector;
  51073. }
  51074. for (i = 0; i < this.vertices.length; ++i) {
  51075. this.vertices[i].triangleCount = 0;
  51076. this.vertices[i].triangleStart = 0;
  51077. }
  51078. var t;
  51079. var j;
  51080. var v;
  51081. for (i = 0; i < this.triangles.length; ++i) {
  51082. t = this.triangles[i];
  51083. for (j = 0; j < 3; ++j) {
  51084. v = t.vertices[j];
  51085. v.triangleCount++;
  51086. }
  51087. }
  51088. var tStart = 0;
  51089. for (i = 0; i < this.vertices.length; ++i) {
  51090. this.vertices[i].triangleStart = tStart;
  51091. tStart += this.vertices[i].triangleCount;
  51092. this.vertices[i].triangleCount = 0;
  51093. }
  51094. var newReferences = new Array(this.triangles.length * 3);
  51095. for (i = 0; i < this.triangles.length; ++i) {
  51096. t = this.triangles[i];
  51097. for (j = 0; j < 3; ++j) {
  51098. v = t.vertices[j];
  51099. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  51100. v.triangleCount++;
  51101. }
  51102. }
  51103. this.references = newReferences;
  51104. if (identifyBorders) {
  51105. this.identifyBorder();
  51106. }
  51107. };
  51108. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  51109. var x = point.x;
  51110. var y = point.y;
  51111. var z = point.z;
  51112. 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
  51113. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  51114. };
  51115. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  51116. var q = vertex1.q.add(vertex2.q);
  51117. var border = vertex1.isBorder && vertex2.isBorder;
  51118. var error = 0;
  51119. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  51120. if (qDet !== 0 && !border) {
  51121. if (!pointResult) {
  51122. pointResult = BABYLON.Vector3.Zero();
  51123. }
  51124. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  51125. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  51126. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  51127. error = this.vertexError(q, pointResult);
  51128. }
  51129. else {
  51130. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  51131. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  51132. var error1 = this.vertexError(q, vertex1.position);
  51133. var error2 = this.vertexError(q, vertex2.position);
  51134. var error3 = this.vertexError(q, p3);
  51135. error = Math.min(error1, error2, error3);
  51136. if (error === error1) {
  51137. if (pointResult) {
  51138. pointResult.copyFrom(vertex1.position);
  51139. }
  51140. }
  51141. else if (error === error2) {
  51142. if (pointResult) {
  51143. pointResult.copyFrom(vertex2.position);
  51144. }
  51145. }
  51146. else {
  51147. if (pointResult) {
  51148. pointResult.copyFrom(p3);
  51149. }
  51150. }
  51151. }
  51152. return error;
  51153. };
  51154. return QuadraticErrorSimplification;
  51155. })();
  51156. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  51157. })(BABYLON || (BABYLON = {}));
  51158. var BABYLON;
  51159. (function (BABYLON) {
  51160. var serializedGeometries = [];
  51161. var serializeGeometry = function (geometry, serializationGeometries) {
  51162. if (serializedGeometries[geometry.id]) {
  51163. return;
  51164. }
  51165. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  51166. serializationGeometries.boxes.push(geometry.serialize());
  51167. }
  51168. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  51169. serializationGeometries.spheres.push(geometry.serialize());
  51170. }
  51171. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  51172. serializationGeometries.cylinders.push(geometry.serialize());
  51173. }
  51174. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  51175. serializationGeometries.toruses.push(geometry.serialize());
  51176. }
  51177. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  51178. serializationGeometries.grounds.push(geometry.serialize());
  51179. }
  51180. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  51181. serializationGeometries.planes.push(geometry.serialize());
  51182. }
  51183. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  51184. serializationGeometries.torusKnots.push(geometry.serialize());
  51185. }
  51186. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  51187. throw new Error("Unknown primitive type");
  51188. }
  51189. else {
  51190. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  51191. }
  51192. serializedGeometries[geometry.id] = true;
  51193. };
  51194. var serializeMesh = function (mesh, serializationScene) {
  51195. var serializationObject = {};
  51196. serializationObject.name = mesh.name;
  51197. serializationObject.id = mesh.id;
  51198. if (BABYLON.Tags.HasTags(mesh)) {
  51199. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  51200. }
  51201. serializationObject.position = mesh.position.asArray();
  51202. if (mesh.rotationQuaternion) {
  51203. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  51204. }
  51205. else if (mesh.rotation) {
  51206. serializationObject.rotation = mesh.rotation.asArray();
  51207. }
  51208. serializationObject.scaling = mesh.scaling.asArray();
  51209. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  51210. serializationObject.isEnabled = mesh.isEnabled();
  51211. serializationObject.isVisible = mesh.isVisible;
  51212. serializationObject.infiniteDistance = mesh.infiniteDistance;
  51213. serializationObject.pickable = mesh.isPickable;
  51214. serializationObject.receiveShadows = mesh.receiveShadows;
  51215. serializationObject.billboardMode = mesh.billboardMode;
  51216. serializationObject.visibility = mesh.visibility;
  51217. serializationObject.checkCollisions = mesh.checkCollisions;
  51218. // Parent
  51219. if (mesh.parent) {
  51220. serializationObject.parentId = mesh.parent.id;
  51221. }
  51222. // Geometry
  51223. var geometry = mesh._geometry;
  51224. if (geometry) {
  51225. var geometryId = geometry.id;
  51226. serializationObject.geometryId = geometryId;
  51227. if (!mesh.getScene().getGeometryByID(geometryId)) {
  51228. // 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
  51229. serializeGeometry(geometry, serializationScene.geometries);
  51230. }
  51231. // SubMeshes
  51232. serializationObject.subMeshes = [];
  51233. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  51234. var subMesh = mesh.subMeshes[subIndex];
  51235. serializationObject.subMeshes.push({
  51236. materialIndex: subMesh.materialIndex,
  51237. verticesStart: subMesh.verticesStart,
  51238. verticesCount: subMesh.verticesCount,
  51239. indexStart: subMesh.indexStart,
  51240. indexCount: subMesh.indexCount
  51241. });
  51242. }
  51243. }
  51244. // Material
  51245. if (mesh.material) {
  51246. serializationObject.materialId = mesh.material.id;
  51247. }
  51248. else {
  51249. mesh.material = null;
  51250. }
  51251. // Skeleton
  51252. if (mesh.skeleton) {
  51253. serializationObject.skeletonId = mesh.skeleton.id;
  51254. }
  51255. // Physics
  51256. //TODO implement correct serialization for physics impostors.
  51257. if (mesh.getPhysicsImpostor()) {
  51258. serializationObject.physicsMass = mesh.getPhysicsMass();
  51259. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  51260. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  51261. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  51262. }
  51263. // Instances
  51264. serializationObject.instances = [];
  51265. for (var index = 0; index < mesh.instances.length; index++) {
  51266. var instance = mesh.instances[index];
  51267. var serializationInstance = {
  51268. name: instance.name,
  51269. position: instance.position.asArray(),
  51270. scaling: instance.scaling.asArray()
  51271. };
  51272. if (instance.rotationQuaternion) {
  51273. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  51274. }
  51275. else if (instance.rotation) {
  51276. serializationInstance.rotation = instance.rotation.asArray();
  51277. }
  51278. serializationObject.instances.push(serializationInstance);
  51279. // Animations
  51280. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  51281. serializationInstance.ranges = instance.serializeAnimationRanges();
  51282. }
  51283. // Animations
  51284. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  51285. serializationObject.ranges = mesh.serializeAnimationRanges();
  51286. // Layer mask
  51287. serializationObject.layerMask = mesh.layerMask;
  51288. // Action Manager
  51289. if (mesh.actionManager) {
  51290. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  51291. }
  51292. return serializationObject;
  51293. };
  51294. var finalizeSingleMesh = function (mesh, serializationObject) {
  51295. //only works if the mesh is already loaded
  51296. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  51297. //serialize material
  51298. if (mesh.material) {
  51299. if (mesh.material instanceof BABYLON.StandardMaterial) {
  51300. serializationObject.materials = serializationObject.materials || [];
  51301. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  51302. serializationObject.materials.push(mesh.material.serialize());
  51303. }
  51304. }
  51305. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  51306. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  51307. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  51308. serializationObject.multiMaterials.push(mesh.material.serialize());
  51309. }
  51310. }
  51311. }
  51312. //serialize geometry
  51313. var geometry = mesh._geometry;
  51314. if (geometry) {
  51315. if (!serializationObject.geometries) {
  51316. serializationObject.geometries = {};
  51317. serializationObject.geometries.boxes = [];
  51318. serializationObject.geometries.spheres = [];
  51319. serializationObject.geometries.cylinders = [];
  51320. serializationObject.geometries.toruses = [];
  51321. serializationObject.geometries.grounds = [];
  51322. serializationObject.geometries.planes = [];
  51323. serializationObject.geometries.torusKnots = [];
  51324. serializationObject.geometries.vertexData = [];
  51325. }
  51326. serializeGeometry(geometry, serializationObject.geometries);
  51327. }
  51328. // Skeletons
  51329. if (mesh.skeleton) {
  51330. serializationObject.skeletons = serializationObject.skeletons || [];
  51331. serializationObject.skeletons.push(mesh.skeleton.serialize());
  51332. }
  51333. //serialize the actual mesh
  51334. serializationObject.meshes = serializationObject.meshes || [];
  51335. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  51336. }
  51337. };
  51338. var SceneSerializer = (function () {
  51339. function SceneSerializer() {
  51340. }
  51341. SceneSerializer.ClearCache = function () {
  51342. serializedGeometries = [];
  51343. };
  51344. SceneSerializer.Serialize = function (scene) {
  51345. var serializationObject = {};
  51346. // Scene
  51347. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  51348. serializationObject.autoClear = scene.autoClear;
  51349. serializationObject.clearColor = scene.clearColor.asArray();
  51350. serializationObject.ambientColor = scene.ambientColor.asArray();
  51351. serializationObject.gravity = scene.gravity.asArray();
  51352. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  51353. serializationObject.workerCollisions = scene.workerCollisions;
  51354. // Fog
  51355. if (scene.fogMode && scene.fogMode !== 0) {
  51356. serializationObject.fogMode = scene.fogMode;
  51357. serializationObject.fogColor = scene.fogColor.asArray();
  51358. serializationObject.fogStart = scene.fogStart;
  51359. serializationObject.fogEnd = scene.fogEnd;
  51360. serializationObject.fogDensity = scene.fogDensity;
  51361. }
  51362. //Physics
  51363. if (scene.isPhysicsEnabled()) {
  51364. serializationObject.physicsEnabled = true;
  51365. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  51366. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  51367. }
  51368. // Lights
  51369. serializationObject.lights = [];
  51370. var index;
  51371. var light;
  51372. for (index = 0; index < scene.lights.length; index++) {
  51373. light = scene.lights[index];
  51374. serializationObject.lights.push(light.serialize());
  51375. }
  51376. // Cameras
  51377. serializationObject.cameras = [];
  51378. for (index = 0; index < scene.cameras.length; index++) {
  51379. var camera = scene.cameras[index];
  51380. serializationObject.cameras.push(camera.serialize());
  51381. }
  51382. if (scene.activeCamera) {
  51383. serializationObject.activeCameraID = scene.activeCamera.id;
  51384. }
  51385. // Animations
  51386. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  51387. // Materials
  51388. serializationObject.materials = [];
  51389. serializationObject.multiMaterials = [];
  51390. var material;
  51391. for (index = 0; index < scene.materials.length; index++) {
  51392. material = scene.materials[index];
  51393. serializationObject.materials.push(material.serialize());
  51394. }
  51395. // MultiMaterials
  51396. serializationObject.multiMaterials = [];
  51397. for (index = 0; index < scene.multiMaterials.length; index++) {
  51398. var multiMaterial = scene.multiMaterials[index];
  51399. serializationObject.multiMaterials.push(multiMaterial.serialize());
  51400. }
  51401. // Skeletons
  51402. serializationObject.skeletons = [];
  51403. for (index = 0; index < scene.skeletons.length; index++) {
  51404. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  51405. }
  51406. // Geometries
  51407. serializationObject.geometries = {};
  51408. serializationObject.geometries.boxes = [];
  51409. serializationObject.geometries.spheres = [];
  51410. serializationObject.geometries.cylinders = [];
  51411. serializationObject.geometries.toruses = [];
  51412. serializationObject.geometries.grounds = [];
  51413. serializationObject.geometries.planes = [];
  51414. serializationObject.geometries.torusKnots = [];
  51415. serializationObject.geometries.vertexData = [];
  51416. serializedGeometries = [];
  51417. var geometries = scene.getGeometries();
  51418. for (index = 0; index < geometries.length; index++) {
  51419. var geometry = geometries[index];
  51420. if (geometry.isReady()) {
  51421. serializeGeometry(geometry, serializationObject.geometries);
  51422. }
  51423. }
  51424. // Meshes
  51425. serializationObject.meshes = [];
  51426. for (index = 0; index < scene.meshes.length; index++) {
  51427. var abstractMesh = scene.meshes[index];
  51428. if (abstractMesh instanceof BABYLON.Mesh) {
  51429. var mesh = abstractMesh;
  51430. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  51431. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  51432. }
  51433. }
  51434. }
  51435. // Particles Systems
  51436. serializationObject.particleSystems = [];
  51437. for (index = 0; index < scene.particleSystems.length; index++) {
  51438. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  51439. }
  51440. // Lens flares
  51441. serializationObject.lensFlareSystems = [];
  51442. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  51443. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  51444. }
  51445. // Shadows
  51446. serializationObject.shadowGenerators = [];
  51447. for (index = 0; index < scene.lights.length; index++) {
  51448. light = scene.lights[index];
  51449. var shadowGenerator = light.getShadowGenerator();
  51450. // Only support serialization for official generator so far.
  51451. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  51452. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  51453. }
  51454. }
  51455. // Action Manager
  51456. if (scene.actionManager) {
  51457. serializationObject.actions = scene.actionManager.serialize("scene");
  51458. }
  51459. // Audio
  51460. serializationObject.sounds = [];
  51461. for (index = 0; index < scene.soundTracks.length; index++) {
  51462. var soundtrack = scene.soundTracks[index];
  51463. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  51464. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  51465. }
  51466. }
  51467. return serializationObject;
  51468. };
  51469. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  51470. if (withParents === void 0) { withParents = false; }
  51471. if (withChildren === void 0) { withChildren = false; }
  51472. var serializationObject = {};
  51473. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  51474. if (withParents || withChildren) {
  51475. //deliberate for loop! not for each, appended should be processed as well.
  51476. for (var i = 0; i < toSerialize.length; ++i) {
  51477. if (withChildren) {
  51478. toSerialize[i].getDescendants().forEach(function (node) {
  51479. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  51480. toSerialize.push(node);
  51481. }
  51482. });
  51483. }
  51484. //make sure the array doesn't contain the object already
  51485. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  51486. toSerialize.push(toSerialize[i].parent);
  51487. }
  51488. }
  51489. }
  51490. toSerialize.forEach(function (mesh) {
  51491. finalizeSingleMesh(mesh, serializationObject);
  51492. });
  51493. return serializationObject;
  51494. };
  51495. return SceneSerializer;
  51496. })();
  51497. BABYLON.SceneSerializer = SceneSerializer;
  51498. })(BABYLON || (BABYLON = {}));
  51499. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  51500. // Huge respect for a such great lib.
  51501. // Earcut license:
  51502. // Copyright (c) 2016, Mapbox
  51503. //
  51504. // Permission to use, copy, modify, and/or distribute this software for any purpose
  51505. // with or without fee is hereby granted, provided that the above copyright notice
  51506. // and this permission notice appear in all copies.
  51507. //
  51508. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  51509. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  51510. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  51511. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  51512. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  51513. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  51514. // THIS SOFTWARE.
  51515. var Earcut;
  51516. (function (Earcut) {
  51517. /**
  51518. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  51519. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  51520. * @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).
  51521. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  51522. */
  51523. function earcut(data, holeIndices, dim) {
  51524. dim = dim || 2;
  51525. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  51526. if (!outerNode)
  51527. return triangles;
  51528. var minX, minY, maxX, maxY, x, y, size;
  51529. if (hasHoles)
  51530. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  51531. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  51532. if (data.length > 80 * dim) {
  51533. minX = maxX = data[0];
  51534. minY = maxY = data[1];
  51535. for (var i = dim; i < outerLen; i += dim) {
  51536. x = data[i];
  51537. y = data[i + 1];
  51538. if (x < minX)
  51539. minX = x;
  51540. if (y < minY)
  51541. minY = y;
  51542. if (x > maxX)
  51543. maxX = x;
  51544. if (y > maxY)
  51545. maxY = y;
  51546. }
  51547. // minX, minY and size are later used to transform coords into integers for z-order calculation
  51548. size = Math.max(maxX - minX, maxY - minY);
  51549. }
  51550. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  51551. return triangles;
  51552. }
  51553. Earcut.earcut = earcut;
  51554. // create a circular doubly linked list from polygon points in the specified winding order
  51555. function linkedList(data, start, end, dim, clockwise) {
  51556. var i, last;
  51557. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  51558. for (i = start; i < end; i += dim)
  51559. last = insertNode(i, data[i], data[i + 1], last);
  51560. }
  51561. else {
  51562. for (i = end - dim; i >= start; i -= dim)
  51563. last = insertNode(i, data[i], data[i + 1], last);
  51564. }
  51565. if (last && equals(last, last.next)) {
  51566. removeNode(last);
  51567. last = last.next;
  51568. }
  51569. return last;
  51570. }
  51571. // eliminate colinear or duplicate points
  51572. function filterPoints(start, end) {
  51573. if (!start)
  51574. return start;
  51575. if (!end)
  51576. end = start;
  51577. var p = start, again;
  51578. do {
  51579. again = false;
  51580. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  51581. removeNode(p);
  51582. p = end = p.prev;
  51583. if (p === p.next)
  51584. return null;
  51585. again = true;
  51586. }
  51587. else {
  51588. p = p.next;
  51589. }
  51590. } while (again || p !== end);
  51591. return end;
  51592. }
  51593. // main ear slicing loop which triangulates a polygon (given as a linked list)
  51594. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  51595. if (!ear)
  51596. return;
  51597. // interlink polygon nodes in z-order
  51598. if (!pass && size)
  51599. indexCurve(ear, minX, minY, size);
  51600. var stop = ear, prev, next;
  51601. // iterate through ears, slicing them one by one
  51602. while (ear.prev !== ear.next) {
  51603. prev = ear.prev;
  51604. next = ear.next;
  51605. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  51606. // cut off the triangle
  51607. triangles.push(prev.i / dim);
  51608. triangles.push(ear.i / dim);
  51609. triangles.push(next.i / dim);
  51610. removeNode(ear);
  51611. // skipping the next vertice leads to less sliver triangles
  51612. ear = next.next;
  51613. stop = next.next;
  51614. continue;
  51615. }
  51616. ear = next;
  51617. // if we looped through the whole remaining polygon and can't find any more ears
  51618. if (ear === stop) {
  51619. // try filtering points and slicing again
  51620. if (!pass) {
  51621. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  51622. }
  51623. else if (pass === 1) {
  51624. ear = cureLocalIntersections(ear, triangles, dim);
  51625. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  51626. }
  51627. else if (pass === 2) {
  51628. splitEarcut(ear, triangles, dim, minX, minY, size);
  51629. }
  51630. break;
  51631. }
  51632. }
  51633. }
  51634. // check whether a polygon node forms a valid ear with adjacent nodes
  51635. function isEar(ear) {
  51636. var a = ear.prev, b = ear, c = ear.next;
  51637. if (area(a, b, c) >= 0)
  51638. return false; // reflex, can't be an ear
  51639. // now make sure we don't have other points inside the potential ear
  51640. var p = ear.next.next;
  51641. while (p !== ear.prev) {
  51642. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51643. area(p.prev, p, p.next) >= 0)
  51644. return false;
  51645. p = p.next;
  51646. }
  51647. return true;
  51648. }
  51649. function isEarHashed(ear, minX, minY, size) {
  51650. var a = ear.prev, b = ear, c = ear.next;
  51651. if (area(a, b, c) >= 0)
  51652. return false; // reflex, can't be an ear
  51653. // triangle bbox; min & max are calculated like this for speed
  51654. 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);
  51655. // z-order range for the current triangle bbox;
  51656. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  51657. // first look for points inside the triangle in increasing z-order
  51658. var p = ear.nextZ;
  51659. while (p && p.z <= maxZ) {
  51660. if (p !== ear.prev &&
  51661. p !== ear.next &&
  51662. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51663. area(p.prev, p, p.next) >= 0)
  51664. return false;
  51665. p = p.nextZ;
  51666. }
  51667. // then look for points in decreasing z-order
  51668. p = ear.prevZ;
  51669. while (p && p.z >= minZ) {
  51670. if (p !== ear.prev &&
  51671. p !== ear.next &&
  51672. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51673. area(p.prev, p, p.next) >= 0)
  51674. return false;
  51675. p = p.prevZ;
  51676. }
  51677. return true;
  51678. }
  51679. // go through all polygon nodes and cure small local self-intersections
  51680. function cureLocalIntersections(start, triangles, dim) {
  51681. var p = start;
  51682. do {
  51683. var a = p.prev, b = p.next.next;
  51684. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  51685. triangles.push(a.i / dim);
  51686. triangles.push(p.i / dim);
  51687. triangles.push(b.i / dim);
  51688. // remove two nodes involved
  51689. removeNode(p);
  51690. removeNode(p.next);
  51691. p = start = b;
  51692. }
  51693. p = p.next;
  51694. } while (p !== start);
  51695. return p;
  51696. }
  51697. // try splitting polygon into two and triangulate them independently
  51698. function splitEarcut(start, triangles, dim, minX, minY, size) {
  51699. // look for a valid diagonal that divides the polygon into two
  51700. var a = start;
  51701. do {
  51702. var b = a.next.next;
  51703. while (b !== a.prev) {
  51704. if (a.i !== b.i && isValidDiagonal(a, b)) {
  51705. // split the polygon in two by the diagonal
  51706. var c = splitPolygon(a, b);
  51707. // filter colinear points around the cuts
  51708. a = filterPoints(a, a.next);
  51709. c = filterPoints(c, c.next);
  51710. // run earcut on each half
  51711. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  51712. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  51713. return;
  51714. }
  51715. b = b.next;
  51716. }
  51717. a = a.next;
  51718. } while (a !== start);
  51719. }
  51720. // link every hole into the outer loop, producing a single-ring polygon without holes
  51721. function eliminateHoles(data, holeIndices, outerNode, dim) {
  51722. var queue = [], i, len, start, end, list;
  51723. for (i = 0, len = holeIndices.length; i < len; i++) {
  51724. start = holeIndices[i] * dim;
  51725. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  51726. list = linkedList(data, start, end, dim, false);
  51727. if (list === list.next)
  51728. list.steiner = true;
  51729. queue.push(getLeftmost(list));
  51730. }
  51731. queue.sort(compareX);
  51732. // process holes from left to right
  51733. for (i = 0; i < queue.length; i++) {
  51734. eliminateHole(queue[i], outerNode);
  51735. outerNode = filterPoints(outerNode, outerNode.next);
  51736. }
  51737. return outerNode;
  51738. }
  51739. function compareX(a, b) {
  51740. return a.x - b.x;
  51741. }
  51742. // find a bridge between vertices that connects hole with an outer ring and and link it
  51743. function eliminateHole(hole, outerNode) {
  51744. outerNode = findHoleBridge(hole, outerNode);
  51745. if (outerNode) {
  51746. var b = splitPolygon(outerNode, hole);
  51747. filterPoints(b, b.next);
  51748. }
  51749. }
  51750. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  51751. function findHoleBridge(hole, outerNode) {
  51752. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  51753. // find a segment intersected by a ray from the hole's leftmost point to the left;
  51754. // segment's endpoint with lesser x will be potential connection point
  51755. do {
  51756. if (hy <= p.y && hy >= p.next.y) {
  51757. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  51758. if (x <= hx && x > qx) {
  51759. qx = x;
  51760. if (x === hx) {
  51761. if (hy === p.y)
  51762. return p;
  51763. if (hy === p.next.y)
  51764. return p.next;
  51765. }
  51766. m = p.x < p.next.x ? p : p.next;
  51767. }
  51768. }
  51769. p = p.next;
  51770. } while (p !== outerNode);
  51771. if (!m)
  51772. return null;
  51773. if (hx === qx)
  51774. return m.prev; // hole touches outer segment; pick lower endpoint
  51775. // look for points inside the triangle of hole point, segment intersection and endpoint;
  51776. // if there are no points found, we have a valid connection;
  51777. // otherwise choose the point of the minimum angle with the ray as connection point
  51778. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  51779. p = m.next;
  51780. while (p !== stop) {
  51781. if (hx >= p.x &&
  51782. p.x >= mx &&
  51783. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  51784. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  51785. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  51786. m = p;
  51787. tanMin = tan;
  51788. }
  51789. }
  51790. p = p.next;
  51791. }
  51792. return m;
  51793. }
  51794. // interlink polygon nodes in z-order
  51795. function indexCurve(start, minX, minY, size) {
  51796. var p = start;
  51797. do {
  51798. if (p.z === null)
  51799. p.z = zOrder(p.x, p.y, minX, minY, size);
  51800. p.prevZ = p.prev;
  51801. p.nextZ = p.next;
  51802. p = p.next;
  51803. } while (p !== start);
  51804. p.prevZ.nextZ = null;
  51805. p.prevZ = null;
  51806. sortLinked(p);
  51807. }
  51808. // Simon Tatham's linked list merge sort algorithm
  51809. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  51810. function sortLinked(list) {
  51811. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  51812. do {
  51813. p = list;
  51814. list = null;
  51815. tail = null;
  51816. numMerges = 0;
  51817. while (p) {
  51818. numMerges++;
  51819. q = p;
  51820. pSize = 0;
  51821. for (i = 0; i < inSize; i++) {
  51822. pSize++;
  51823. q = q.nextZ;
  51824. if (!q)
  51825. break;
  51826. }
  51827. qSize = inSize;
  51828. while (pSize > 0 || (qSize > 0 && q)) {
  51829. if (pSize === 0) {
  51830. e = q;
  51831. q = q.nextZ;
  51832. qSize--;
  51833. }
  51834. else if (qSize === 0 || !q) {
  51835. e = p;
  51836. p = p.nextZ;
  51837. pSize--;
  51838. }
  51839. else if (p.z <= q.z) {
  51840. e = p;
  51841. p = p.nextZ;
  51842. pSize--;
  51843. }
  51844. else {
  51845. e = q;
  51846. q = q.nextZ;
  51847. qSize--;
  51848. }
  51849. if (tail)
  51850. tail.nextZ = e;
  51851. else
  51852. list = e;
  51853. e.prevZ = tail;
  51854. tail = e;
  51855. }
  51856. p = q;
  51857. }
  51858. tail.nextZ = null;
  51859. inSize *= 2;
  51860. } while (numMerges > 1);
  51861. return list;
  51862. }
  51863. // z-order of a point given coords and size of the data bounding box
  51864. function zOrder(x, y, minX, minY, size) {
  51865. // coords are transformed into non-negative 15-bit integer range
  51866. x = 32767 * (x - minX) / size;
  51867. y = 32767 * (y - minY) / size;
  51868. x = (x | (x << 8)) & 0x00FF00FF;
  51869. x = (x | (x << 4)) & 0x0F0F0F0F;
  51870. x = (x | (x << 2)) & 0x33333333;
  51871. x = (x | (x << 1)) & 0x55555555;
  51872. y = (y | (y << 8)) & 0x00FF00FF;
  51873. y = (y | (y << 4)) & 0x0F0F0F0F;
  51874. y = (y | (y << 2)) & 0x33333333;
  51875. y = (y | (y << 1)) & 0x55555555;
  51876. return x | (y << 1);
  51877. }
  51878. // find the leftmost node of a polygon ring
  51879. function getLeftmost(start) {
  51880. var p = start, leftmost = start;
  51881. do {
  51882. if (p.x < leftmost.x)
  51883. leftmost = p;
  51884. p = p.next;
  51885. } while (p !== start);
  51886. return leftmost;
  51887. }
  51888. // check if a point lies within a convex triangle
  51889. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  51890. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  51891. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  51892. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  51893. }
  51894. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  51895. function isValidDiagonal(a, b) {
  51896. return a.next.i !== b.i &&
  51897. a.prev.i !== b.i &&
  51898. !intersectsPolygon(a, b) &&
  51899. locallyInside(a, b) &&
  51900. locallyInside(b, a) &&
  51901. middleInside(a, b);
  51902. }
  51903. // signed area of a triangle
  51904. function area(p, q, r) {
  51905. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  51906. }
  51907. // check if two points are equal
  51908. function equals(p1, p2) {
  51909. return p1.x === p2.x && p1.y === p2.y;
  51910. }
  51911. // check if two segments intersect
  51912. function intersects(p1, q1, p2, q2) {
  51913. if ((equals(p1, q1) && equals(p2, q2)) ||
  51914. (equals(p1, q2) && equals(p2, q1)))
  51915. return true;
  51916. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  51917. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  51918. }
  51919. // check if a polygon diagonal intersects any polygon segments
  51920. function intersectsPolygon(a, b) {
  51921. var p = a;
  51922. do {
  51923. if (p.i !== a.i &&
  51924. p.next.i !== a.i &&
  51925. p.i !== b.i &&
  51926. p.next.i !== b.i &&
  51927. intersects(p, p.next, a, b))
  51928. return true;
  51929. p = p.next;
  51930. } while (p !== a);
  51931. return false;
  51932. }
  51933. // check if a polygon diagonal is locally inside the polygon
  51934. function locallyInside(a, b) {
  51935. return area(a.prev, a, a.next) < 0
  51936. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  51937. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  51938. }
  51939. // check if the middle point of a polygon diagonal is inside the polygon
  51940. function middleInside(a, b) {
  51941. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  51942. do {
  51943. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  51944. inside = !inside;
  51945. p = p.next;
  51946. } while (p !== a);
  51947. return inside;
  51948. }
  51949. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  51950. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  51951. function splitPolygon(a, b) {
  51952. 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;
  51953. a.next = b;
  51954. b.prev = a;
  51955. a2.next = an;
  51956. an.prev = a2;
  51957. b2.next = a2;
  51958. a2.prev = b2;
  51959. bp.next = b2;
  51960. b2.prev = bp;
  51961. return b2;
  51962. }
  51963. // create a node and optionally link it with previous one (in a circular doubly linked list)
  51964. function insertNode(i, x, y, last) {
  51965. var p = new Node(i, x, y);
  51966. if (!last) {
  51967. p.prev = p;
  51968. p.next = p;
  51969. }
  51970. else {
  51971. p.next = last.next;
  51972. p.prev = last;
  51973. last.next.prev = p;
  51974. last.next = p;
  51975. }
  51976. return p;
  51977. }
  51978. function removeNode(p) {
  51979. p.next.prev = p.prev;
  51980. p.prev.next = p.next;
  51981. if (p.prevZ)
  51982. p.prevZ.nextZ = p.nextZ;
  51983. if (p.nextZ)
  51984. p.nextZ.prevZ = p.prevZ;
  51985. }
  51986. function Node(i, x, y) {
  51987. // vertice index in coordinates array
  51988. this.i = i;
  51989. // vertex coordinates
  51990. this.x = x;
  51991. this.y = y;
  51992. // previous and next vertice nodes in a polygon ring
  51993. this.prev = null;
  51994. this.next = null;
  51995. // z-order curve value
  51996. this.z = null;
  51997. // previous and next nodes in z-order
  51998. this.prevZ = null;
  51999. this.nextZ = null;
  52000. // indicates whether this is a steiner point
  52001. this.steiner = false;
  52002. }
  52003. /**
  52004. * return a percentage difference between the polygon area and its triangulation area;
  52005. * used to verify correctness of triangulation
  52006. */
  52007. function deviation(data, holeIndices, dim, triangles) {
  52008. var hasHoles = holeIndices && holeIndices.length;
  52009. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  52010. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  52011. if (hasHoles) {
  52012. for (var i = 0, len = holeIndices.length; i < len; i++) {
  52013. var start = holeIndices[i] * dim;
  52014. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  52015. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  52016. }
  52017. }
  52018. var trianglesArea = 0;
  52019. for (i = 0; i < triangles.length; i += 3) {
  52020. var a = triangles[i] * dim;
  52021. var b = triangles[i + 1] * dim;
  52022. var c = triangles[i + 2] * dim;
  52023. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  52024. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  52025. }
  52026. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  52027. }
  52028. Earcut.deviation = deviation;
  52029. ;
  52030. function signedArea(data, start, end, dim) {
  52031. var sum = 0;
  52032. for (var i = start, j = end - dim; i < end; i += dim) {
  52033. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  52034. j = i;
  52035. }
  52036. return sum;
  52037. }
  52038. /**
  52039. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  52040. */
  52041. function flatten(data) {
  52042. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  52043. for (var i = 0; i < data.length; i++) {
  52044. for (var j = 0; j < data[i].length; j++) {
  52045. for (var d = 0; d < dim; d++)
  52046. result.vertices.push(data[i][j][d]);
  52047. }
  52048. if (i > 0) {
  52049. holeIndex += data[i - 1].length;
  52050. result.holes.push(holeIndex);
  52051. }
  52052. }
  52053. return result;
  52054. }
  52055. Earcut.flatten = flatten;
  52056. ;
  52057. })(Earcut || (Earcut = {}));
  52058. var BABYLON;
  52059. (function (BABYLON) {
  52060. // Unique ID when we import meshes from Babylon to CSG
  52061. var currentCSGMeshId = 0;
  52062. // # class Vertex
  52063. // Represents a vertex of a polygon. Use your own vertex class instead of this
  52064. // one to provide additional features like texture coordinates and vertex
  52065. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  52066. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  52067. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  52068. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  52069. // is not used anywhere else.
  52070. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  52071. var Vertex = (function () {
  52072. function Vertex(pos, normal, uv) {
  52073. this.pos = pos;
  52074. this.normal = normal;
  52075. this.uv = uv;
  52076. }
  52077. Vertex.prototype.clone = function () {
  52078. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  52079. };
  52080. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  52081. // orientation of a polygon is flipped.
  52082. Vertex.prototype.flip = function () {
  52083. this.normal = this.normal.scale(-1);
  52084. };
  52085. // Create a new vertex between this vertex and `other` by linearly
  52086. // interpolating all properties using a parameter of `t`. Subclasses should
  52087. // override this to interpolate additional properties.
  52088. Vertex.prototype.interpolate = function (other, t) {
  52089. 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));
  52090. };
  52091. return Vertex;
  52092. })();
  52093. // # class Plane
  52094. // Represents a plane in 3D space.
  52095. var Plane = (function () {
  52096. function Plane(normal, w) {
  52097. this.normal = normal;
  52098. this.w = w;
  52099. }
  52100. Plane.FromPoints = function (a, b, c) {
  52101. var v0 = c.subtract(a);
  52102. var v1 = b.subtract(a);
  52103. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  52104. return null;
  52105. }
  52106. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  52107. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  52108. };
  52109. Plane.prototype.clone = function () {
  52110. return new Plane(this.normal.clone(), this.w);
  52111. };
  52112. Plane.prototype.flip = function () {
  52113. this.normal.scaleInPlace(-1);
  52114. this.w = -this.w;
  52115. };
  52116. // Split `polygon` by this plane if needed, then put the polygon or polygon
  52117. // fragments in the appropriate lists. Coplanar polygons go into either
  52118. // `coplanarFront` or `coplanarBack` depending on their orientation with
  52119. // respect to this plane. Polygons in front or in back of this plane go into
  52120. // either `front` or `back`.
  52121. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  52122. var COPLANAR = 0;
  52123. var FRONT = 1;
  52124. var BACK = 2;
  52125. var SPANNING = 3;
  52126. // Classify each point as well as the entire polygon into one of the above
  52127. // four classes.
  52128. var polygonType = 0;
  52129. var types = [];
  52130. var i;
  52131. var t;
  52132. for (i = 0; i < polygon.vertices.length; i++) {
  52133. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  52134. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  52135. polygonType |= type;
  52136. types.push(type);
  52137. }
  52138. // Put the polygon in the correct list, splitting it when necessary.
  52139. switch (polygonType) {
  52140. case COPLANAR:
  52141. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  52142. break;
  52143. case FRONT:
  52144. front.push(polygon);
  52145. break;
  52146. case BACK:
  52147. back.push(polygon);
  52148. break;
  52149. case SPANNING:
  52150. var f = [], b = [];
  52151. for (i = 0; i < polygon.vertices.length; i++) {
  52152. var j = (i + 1) % polygon.vertices.length;
  52153. var ti = types[i], tj = types[j];
  52154. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  52155. if (ti !== BACK)
  52156. f.push(vi);
  52157. if (ti !== FRONT)
  52158. b.push(ti !== BACK ? vi.clone() : vi);
  52159. if ((ti | tj) === SPANNING) {
  52160. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  52161. var v = vi.interpolate(vj, t);
  52162. f.push(v);
  52163. b.push(v.clone());
  52164. }
  52165. }
  52166. var poly;
  52167. if (f.length >= 3) {
  52168. poly = new Polygon(f, polygon.shared);
  52169. if (poly.plane)
  52170. front.push(poly);
  52171. }
  52172. if (b.length >= 3) {
  52173. poly = new Polygon(b, polygon.shared);
  52174. if (poly.plane)
  52175. back.push(poly);
  52176. }
  52177. break;
  52178. }
  52179. };
  52180. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  52181. // point is on the plane.
  52182. Plane.EPSILON = 1e-5;
  52183. return Plane;
  52184. })();
  52185. // # class Polygon
  52186. // Represents a convex polygon. The vertices used to initialize a polygon must
  52187. // be coplanar and form a convex loop.
  52188. //
  52189. // Each convex polygon has a `shared` property, which is shared between all
  52190. // polygons that are clones of each other or were split from the same polygon.
  52191. // This can be used to define per-polygon properties (such as surface color).
  52192. var Polygon = (function () {
  52193. function Polygon(vertices, shared) {
  52194. this.vertices = vertices;
  52195. this.shared = shared;
  52196. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  52197. }
  52198. Polygon.prototype.clone = function () {
  52199. var vertices = this.vertices.map(function (v) { return v.clone(); });
  52200. return new Polygon(vertices, this.shared);
  52201. };
  52202. Polygon.prototype.flip = function () {
  52203. this.vertices.reverse().map(function (v) { v.flip(); });
  52204. this.plane.flip();
  52205. };
  52206. return Polygon;
  52207. })();
  52208. // # class Node
  52209. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  52210. // by picking a polygon to split along. That polygon (and all other coplanar
  52211. // polygons) are added directly to that node and the other polygons are added to
  52212. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  52213. // no distinction between internal and leaf nodes.
  52214. var Node = (function () {
  52215. function Node(polygons) {
  52216. this.plane = null;
  52217. this.front = null;
  52218. this.back = null;
  52219. this.polygons = [];
  52220. if (polygons) {
  52221. this.build(polygons);
  52222. }
  52223. }
  52224. Node.prototype.clone = function () {
  52225. var node = new Node();
  52226. node.plane = this.plane && this.plane.clone();
  52227. node.front = this.front && this.front.clone();
  52228. node.back = this.back && this.back.clone();
  52229. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  52230. return node;
  52231. };
  52232. // Convert solid space to empty space and empty space to solid space.
  52233. Node.prototype.invert = function () {
  52234. for (var i = 0; i < this.polygons.length; i++) {
  52235. this.polygons[i].flip();
  52236. }
  52237. if (this.plane) {
  52238. this.plane.flip();
  52239. }
  52240. if (this.front) {
  52241. this.front.invert();
  52242. }
  52243. if (this.back) {
  52244. this.back.invert();
  52245. }
  52246. var temp = this.front;
  52247. this.front = this.back;
  52248. this.back = temp;
  52249. };
  52250. // Recursively remove all polygons in `polygons` that are inside this BSP
  52251. // tree.
  52252. Node.prototype.clipPolygons = function (polygons) {
  52253. if (!this.plane)
  52254. return polygons.slice();
  52255. var front = [], back = [];
  52256. for (var i = 0; i < polygons.length; i++) {
  52257. this.plane.splitPolygon(polygons[i], front, back, front, back);
  52258. }
  52259. if (this.front) {
  52260. front = this.front.clipPolygons(front);
  52261. }
  52262. if (this.back) {
  52263. back = this.back.clipPolygons(back);
  52264. }
  52265. else {
  52266. back = [];
  52267. }
  52268. return front.concat(back);
  52269. };
  52270. // Remove all polygons in this BSP tree that are inside the other BSP tree
  52271. // `bsp`.
  52272. Node.prototype.clipTo = function (bsp) {
  52273. this.polygons = bsp.clipPolygons(this.polygons);
  52274. if (this.front)
  52275. this.front.clipTo(bsp);
  52276. if (this.back)
  52277. this.back.clipTo(bsp);
  52278. };
  52279. // Return a list of all polygons in this BSP tree.
  52280. Node.prototype.allPolygons = function () {
  52281. var polygons = this.polygons.slice();
  52282. if (this.front)
  52283. polygons = polygons.concat(this.front.allPolygons());
  52284. if (this.back)
  52285. polygons = polygons.concat(this.back.allPolygons());
  52286. return polygons;
  52287. };
  52288. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  52289. // new polygons are filtered down to the bottom of the tree and become new
  52290. // nodes there. Each set of polygons is partitioned using the first polygon
  52291. // (no heuristic is used to pick a good split).
  52292. Node.prototype.build = function (polygons) {
  52293. if (!polygons.length)
  52294. return;
  52295. if (!this.plane)
  52296. this.plane = polygons[0].plane.clone();
  52297. var front = [], back = [];
  52298. for (var i = 0; i < polygons.length; i++) {
  52299. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  52300. }
  52301. if (front.length) {
  52302. if (!this.front)
  52303. this.front = new Node();
  52304. this.front.build(front);
  52305. }
  52306. if (back.length) {
  52307. if (!this.back)
  52308. this.back = new Node();
  52309. this.back.build(back);
  52310. }
  52311. };
  52312. return Node;
  52313. })();
  52314. var CSG = (function () {
  52315. function CSG() {
  52316. this.polygons = new Array();
  52317. }
  52318. // Convert BABYLON.Mesh to BABYLON.CSG
  52319. CSG.FromMesh = function (mesh) {
  52320. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  52321. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  52322. if (mesh instanceof BABYLON.Mesh) {
  52323. mesh.computeWorldMatrix(true);
  52324. matrix = mesh.getWorldMatrix();
  52325. meshPosition = mesh.position.clone();
  52326. meshRotation = mesh.rotation.clone();
  52327. if (mesh.rotationQuaternion) {
  52328. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  52329. }
  52330. meshScaling = mesh.scaling.clone();
  52331. }
  52332. else {
  52333. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  52334. }
  52335. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52336. var subMeshes = mesh.subMeshes;
  52337. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  52338. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  52339. vertices = [];
  52340. for (var j = 0; j < 3; j++) {
  52341. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  52342. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  52343. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  52344. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  52345. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  52346. vertex = new Vertex(position, normal, uv);
  52347. vertices.push(vertex);
  52348. }
  52349. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  52350. // To handle the case of degenerated triangle
  52351. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  52352. if (polygon.plane)
  52353. polygons.push(polygon);
  52354. }
  52355. }
  52356. var csg = CSG.FromPolygons(polygons);
  52357. csg.matrix = matrix;
  52358. csg.position = meshPosition;
  52359. csg.rotation = meshRotation;
  52360. csg.scaling = meshScaling;
  52361. csg.rotationQuaternion = meshRotationQuaternion;
  52362. currentCSGMeshId++;
  52363. return csg;
  52364. };
  52365. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  52366. CSG.FromPolygons = function (polygons) {
  52367. var csg = new CSG();
  52368. csg.polygons = polygons;
  52369. return csg;
  52370. };
  52371. CSG.prototype.clone = function () {
  52372. var csg = new CSG();
  52373. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  52374. csg.copyTransformAttributes(this);
  52375. return csg;
  52376. };
  52377. CSG.prototype.toPolygons = function () {
  52378. return this.polygons;
  52379. };
  52380. CSG.prototype.union = function (csg) {
  52381. var a = new Node(this.clone().polygons);
  52382. var b = new Node(csg.clone().polygons);
  52383. a.clipTo(b);
  52384. b.clipTo(a);
  52385. b.invert();
  52386. b.clipTo(a);
  52387. b.invert();
  52388. a.build(b.allPolygons());
  52389. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52390. };
  52391. CSG.prototype.unionInPlace = function (csg) {
  52392. var a = new Node(this.polygons);
  52393. var b = new Node(csg.polygons);
  52394. a.clipTo(b);
  52395. b.clipTo(a);
  52396. b.invert();
  52397. b.clipTo(a);
  52398. b.invert();
  52399. a.build(b.allPolygons());
  52400. this.polygons = a.allPolygons();
  52401. };
  52402. CSG.prototype.subtract = function (csg) {
  52403. var a = new Node(this.clone().polygons);
  52404. var b = new Node(csg.clone().polygons);
  52405. a.invert();
  52406. a.clipTo(b);
  52407. b.clipTo(a);
  52408. b.invert();
  52409. b.clipTo(a);
  52410. b.invert();
  52411. a.build(b.allPolygons());
  52412. a.invert();
  52413. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52414. };
  52415. CSG.prototype.subtractInPlace = function (csg) {
  52416. var a = new Node(this.polygons);
  52417. var b = new Node(csg.polygons);
  52418. a.invert();
  52419. a.clipTo(b);
  52420. b.clipTo(a);
  52421. b.invert();
  52422. b.clipTo(a);
  52423. b.invert();
  52424. a.build(b.allPolygons());
  52425. a.invert();
  52426. this.polygons = a.allPolygons();
  52427. };
  52428. CSG.prototype.intersect = function (csg) {
  52429. var a = new Node(this.clone().polygons);
  52430. var b = new Node(csg.clone().polygons);
  52431. a.invert();
  52432. b.clipTo(a);
  52433. b.invert();
  52434. a.clipTo(b);
  52435. b.clipTo(a);
  52436. a.build(b.allPolygons());
  52437. a.invert();
  52438. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52439. };
  52440. CSG.prototype.intersectInPlace = function (csg) {
  52441. var a = new Node(this.polygons);
  52442. var b = new Node(csg.polygons);
  52443. a.invert();
  52444. b.clipTo(a);
  52445. b.invert();
  52446. a.clipTo(b);
  52447. b.clipTo(a);
  52448. a.build(b.allPolygons());
  52449. a.invert();
  52450. this.polygons = a.allPolygons();
  52451. };
  52452. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  52453. // not modified.
  52454. CSG.prototype.inverse = function () {
  52455. var csg = this.clone();
  52456. csg.inverseInPlace();
  52457. return csg;
  52458. };
  52459. CSG.prototype.inverseInPlace = function () {
  52460. this.polygons.map(function (p) { p.flip(); });
  52461. };
  52462. // This is used to keep meshes transformations so they can be restored
  52463. // when we build back a Babylon Mesh
  52464. // NB : All CSG operations are performed in world coordinates
  52465. CSG.prototype.copyTransformAttributes = function (csg) {
  52466. this.matrix = csg.matrix;
  52467. this.position = csg.position;
  52468. this.rotation = csg.rotation;
  52469. this.scaling = csg.scaling;
  52470. this.rotationQuaternion = csg.rotationQuaternion;
  52471. return this;
  52472. };
  52473. // Build Raw mesh from CSG
  52474. // Coordinates here are in world space
  52475. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  52476. var matrix = this.matrix.clone();
  52477. matrix.invert();
  52478. 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;
  52479. if (keepSubMeshes) {
  52480. // Sort Polygons, since subMeshes are indices range
  52481. polygons.sort(function (a, b) {
  52482. if (a.shared.meshId === b.shared.meshId) {
  52483. return a.shared.subMeshId - b.shared.subMeshId;
  52484. }
  52485. else {
  52486. return a.shared.meshId - b.shared.meshId;
  52487. }
  52488. });
  52489. }
  52490. for (var i = 0, il = polygons.length; i < il; i++) {
  52491. polygon = polygons[i];
  52492. // Building SubMeshes
  52493. if (!subMesh_dict[polygon.shared.meshId]) {
  52494. subMesh_dict[polygon.shared.meshId] = {};
  52495. }
  52496. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  52497. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  52498. indexStart: +Infinity,
  52499. indexEnd: -Infinity,
  52500. materialIndex: polygon.shared.materialIndex
  52501. };
  52502. }
  52503. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  52504. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  52505. polygonIndices[0] = 0;
  52506. polygonIndices[1] = j - 1;
  52507. polygonIndices[2] = j;
  52508. for (var k = 0; k < 3; k++) {
  52509. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  52510. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  52511. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  52512. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  52513. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  52514. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  52515. // Check if 2 points can be merged
  52516. if (!(typeof vertex_idx !== 'undefined' &&
  52517. normals[vertex_idx * 3] === localNormal.x &&
  52518. normals[vertex_idx * 3 + 1] === localNormal.y &&
  52519. normals[vertex_idx * 3 + 2] === localNormal.z &&
  52520. uvs[vertex_idx * 2] === uv.x &&
  52521. uvs[vertex_idx * 2 + 1] === uv.y)) {
  52522. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  52523. uvs.push(uv.x, uv.y);
  52524. normals.push(normal.x, normal.y, normal.z);
  52525. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  52526. }
  52527. indices.push(vertex_idx);
  52528. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  52529. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  52530. currentIndex++;
  52531. }
  52532. }
  52533. }
  52534. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  52535. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  52536. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  52537. mesh.setIndices(indices);
  52538. if (keepSubMeshes) {
  52539. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  52540. var materialIndexOffset = 0, materialMaxIndex;
  52541. mesh.subMeshes = new Array();
  52542. for (var m in subMesh_dict) {
  52543. materialMaxIndex = -1;
  52544. for (var sm in subMesh_dict[m]) {
  52545. subMesh_obj = subMesh_dict[m][sm];
  52546. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  52547. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  52548. }
  52549. materialIndexOffset += ++materialMaxIndex;
  52550. }
  52551. }
  52552. return mesh;
  52553. };
  52554. // Build Mesh from CSG taking material and transforms into account
  52555. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  52556. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  52557. mesh.material = material;
  52558. mesh.position.copyFrom(this.position);
  52559. mesh.rotation.copyFrom(this.rotation);
  52560. if (this.rotationQuaternion) {
  52561. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  52562. }
  52563. mesh.scaling.copyFrom(this.scaling);
  52564. mesh.computeWorldMatrix(true);
  52565. return mesh;
  52566. };
  52567. return CSG;
  52568. })();
  52569. BABYLON.CSG = CSG;
  52570. })(BABYLON || (BABYLON = {}));
  52571. var BABYLON;
  52572. (function (BABYLON) {
  52573. var VRDistortionCorrectionPostProcess = (function (_super) {
  52574. __extends(VRDistortionCorrectionPostProcess, _super);
  52575. //ANY
  52576. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  52577. var _this = this;
  52578. _super.call(this, name, "vrDistortionCorrection", [
  52579. 'LensCenter',
  52580. 'Scale',
  52581. 'ScaleIn',
  52582. 'HmdWarpParam'
  52583. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  52584. this._isRightEye = isRightEye;
  52585. this._distortionFactors = vrMetrics.distortionK;
  52586. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  52587. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  52588. this.onSizeChangedObservable.add(function () {
  52589. _this.aspectRatio = _this.width * .5 / _this.height;
  52590. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  52591. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  52592. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  52593. });
  52594. this.onApplyObservable.add(function (effect) {
  52595. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  52596. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  52597. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  52598. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  52599. });
  52600. }
  52601. return VRDistortionCorrectionPostProcess;
  52602. })(BABYLON.PostProcess);
  52603. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  52604. })(BABYLON || (BABYLON = {}));
  52605. // Mainly based on these 2 articles :
  52606. // 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
  52607. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  52608. var BABYLON;
  52609. (function (BABYLON) {
  52610. (function (JoystickAxis) {
  52611. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  52612. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  52613. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  52614. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  52615. var JoystickAxis = BABYLON.JoystickAxis;
  52616. var VirtualJoystick = (function () {
  52617. function VirtualJoystick(leftJoystick) {
  52618. var _this = this;
  52619. if (leftJoystick) {
  52620. this._leftJoystick = true;
  52621. }
  52622. else {
  52623. this._leftJoystick = false;
  52624. }
  52625. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  52626. VirtualJoystick._globalJoystickIndex++;
  52627. // By default left & right arrow keys are moving the X
  52628. // and up & down keys are moving the Y
  52629. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  52630. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  52631. this.reverseLeftRight = false;
  52632. this.reverseUpDown = false;
  52633. // collections of pointers
  52634. this._touches = new BABYLON.StringDictionary();
  52635. this.deltaPosition = BABYLON.Vector3.Zero();
  52636. this._joystickSensibility = 25;
  52637. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  52638. this._rotationSpeed = 25;
  52639. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  52640. this._rotateOnAxisRelativeToMesh = false;
  52641. this._onResize = function (evt) {
  52642. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  52643. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  52644. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  52645. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  52646. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  52647. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  52648. };
  52649. // injecting a canvas element on top of the canvas 3D game
  52650. if (!VirtualJoystick.vjCanvas) {
  52651. window.addEventListener("resize", this._onResize, false);
  52652. VirtualJoystick.vjCanvas = document.createElement("canvas");
  52653. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  52654. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  52655. VirtualJoystick.vjCanvas.width = window.innerWidth;
  52656. VirtualJoystick.vjCanvas.height = window.innerHeight;
  52657. VirtualJoystick.vjCanvas.style.width = "100%";
  52658. VirtualJoystick.vjCanvas.style.height = "100%";
  52659. VirtualJoystick.vjCanvas.style.position = "absolute";
  52660. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  52661. VirtualJoystick.vjCanvas.style.top = "0px";
  52662. VirtualJoystick.vjCanvas.style.left = "0px";
  52663. VirtualJoystick.vjCanvas.style.zIndex = "5";
  52664. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  52665. // Support for jQuery PEP polyfill
  52666. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  52667. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  52668. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  52669. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  52670. document.body.appendChild(VirtualJoystick.vjCanvas);
  52671. }
  52672. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  52673. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  52674. this.pressed = false;
  52675. // default joystick color
  52676. this._joystickColor = "cyan";
  52677. this._joystickPointerID = -1;
  52678. // current joystick position
  52679. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  52680. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  52681. // origin joystick position
  52682. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  52683. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  52684. this._onPointerDownHandlerRef = function (evt) {
  52685. _this._onPointerDown(evt);
  52686. };
  52687. this._onPointerMoveHandlerRef = function (evt) {
  52688. _this._onPointerMove(evt);
  52689. };
  52690. this._onPointerOutHandlerRef = function (evt) {
  52691. _this._onPointerUp(evt);
  52692. };
  52693. this._onPointerUpHandlerRef = function (evt) {
  52694. _this._onPointerUp(evt);
  52695. };
  52696. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  52697. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  52698. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  52699. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  52700. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  52701. evt.preventDefault(); // Disables system menu
  52702. }, false);
  52703. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  52704. }
  52705. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  52706. this._joystickSensibility = newJoystickSensibility;
  52707. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  52708. };
  52709. VirtualJoystick.prototype._onPointerDown = function (e) {
  52710. var positionOnScreenCondition;
  52711. e.preventDefault();
  52712. if (this._leftJoystick === true) {
  52713. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  52714. }
  52715. else {
  52716. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  52717. }
  52718. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  52719. // First contact will be dedicated to the virtual joystick
  52720. this._joystickPointerID = e.pointerId;
  52721. this._joystickPointerStartPos.x = e.clientX;
  52722. this._joystickPointerStartPos.y = e.clientY;
  52723. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  52724. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  52725. this._deltaJoystickVector.x = 0;
  52726. this._deltaJoystickVector.y = 0;
  52727. this.pressed = true;
  52728. this._touches.add(e.pointerId.toString(), e);
  52729. }
  52730. else {
  52731. // You can only trigger the action buttons with a joystick declared
  52732. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  52733. this._action();
  52734. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  52735. }
  52736. }
  52737. };
  52738. VirtualJoystick.prototype._onPointerMove = function (e) {
  52739. // If the current pointer is the one associated to the joystick (first touch contact)
  52740. if (this._joystickPointerID == e.pointerId) {
  52741. this._joystickPointerPos.x = e.clientX;
  52742. this._joystickPointerPos.y = e.clientY;
  52743. this._deltaJoystickVector = this._joystickPointerPos.clone();
  52744. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  52745. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  52746. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  52747. switch (this._axisTargetedByLeftAndRight) {
  52748. case JoystickAxis.X:
  52749. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  52750. break;
  52751. case JoystickAxis.Y:
  52752. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  52753. break;
  52754. case JoystickAxis.Z:
  52755. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  52756. break;
  52757. }
  52758. var directionUpDown = this.reverseUpDown ? 1 : -1;
  52759. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  52760. switch (this._axisTargetedByUpAndDown) {
  52761. case JoystickAxis.X:
  52762. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  52763. break;
  52764. case JoystickAxis.Y:
  52765. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  52766. break;
  52767. case JoystickAxis.Z:
  52768. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  52769. break;
  52770. }
  52771. }
  52772. else {
  52773. var data = this._touches.get(e.pointerId.toString());
  52774. if (data) {
  52775. data.x = e.clientX;
  52776. data.y = e.clientY;
  52777. }
  52778. }
  52779. };
  52780. VirtualJoystick.prototype._onPointerUp = function (e) {
  52781. if (this._joystickPointerID == e.pointerId) {
  52782. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  52783. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  52784. this._joystickPointerID = -1;
  52785. this.pressed = false;
  52786. }
  52787. else {
  52788. var touch = this._touches.get(e.pointerId.toString());
  52789. if (touch) {
  52790. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  52791. }
  52792. }
  52793. this._deltaJoystickVector.x = 0;
  52794. this._deltaJoystickVector.y = 0;
  52795. this._touches.remove(e.pointerId.toString());
  52796. };
  52797. /**
  52798. * Change the color of the virtual joystick
  52799. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  52800. */
  52801. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  52802. this._joystickColor = newColor;
  52803. };
  52804. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  52805. this._action = action;
  52806. };
  52807. // Define which axis you'd like to control for left & right
  52808. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  52809. switch (axis) {
  52810. case JoystickAxis.X:
  52811. case JoystickAxis.Y:
  52812. case JoystickAxis.Z:
  52813. this._axisTargetedByLeftAndRight = axis;
  52814. break;
  52815. default:
  52816. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  52817. break;
  52818. }
  52819. };
  52820. // Define which axis you'd like to control for up & down
  52821. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  52822. switch (axis) {
  52823. case JoystickAxis.X:
  52824. case JoystickAxis.Y:
  52825. case JoystickAxis.Z:
  52826. this._axisTargetedByUpAndDown = axis;
  52827. break;
  52828. default:
  52829. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  52830. break;
  52831. }
  52832. };
  52833. VirtualJoystick.prototype._clearCanvas = function () {
  52834. if (this._leftJoystick) {
  52835. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  52836. }
  52837. else {
  52838. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  52839. }
  52840. };
  52841. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  52842. var _this = this;
  52843. if (this.pressed) {
  52844. this._touches.forEach(function (touch) {
  52845. if (touch.pointerId === _this._joystickPointerID) {
  52846. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  52847. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  52848. VirtualJoystick.vjCanvasContext.beginPath();
  52849. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  52850. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52851. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  52852. VirtualJoystick.vjCanvasContext.stroke();
  52853. VirtualJoystick.vjCanvasContext.closePath();
  52854. VirtualJoystick.vjCanvasContext.beginPath();
  52855. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52856. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  52857. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  52858. VirtualJoystick.vjCanvasContext.stroke();
  52859. VirtualJoystick.vjCanvasContext.closePath();
  52860. VirtualJoystick.vjCanvasContext.beginPath();
  52861. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52862. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  52863. VirtualJoystick.vjCanvasContext.stroke();
  52864. VirtualJoystick.vjCanvasContext.closePath();
  52865. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  52866. }
  52867. else {
  52868. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  52869. VirtualJoystick.vjCanvasContext.beginPath();
  52870. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  52871. VirtualJoystick.vjCanvasContext.beginPath();
  52872. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  52873. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  52874. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  52875. VirtualJoystick.vjCanvasContext.stroke();
  52876. VirtualJoystick.vjCanvasContext.closePath();
  52877. touch.prevX = touch.x;
  52878. touch.prevY = touch.y;
  52879. }
  52880. ;
  52881. });
  52882. }
  52883. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  52884. };
  52885. VirtualJoystick.prototype.releaseCanvas = function () {
  52886. if (VirtualJoystick.vjCanvas) {
  52887. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  52888. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  52889. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  52890. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  52891. window.removeEventListener("resize", this._onResize);
  52892. document.body.removeChild(VirtualJoystick.vjCanvas);
  52893. VirtualJoystick.vjCanvas = null;
  52894. }
  52895. };
  52896. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  52897. VirtualJoystick._globalJoystickIndex = 0;
  52898. return VirtualJoystick;
  52899. })();
  52900. BABYLON.VirtualJoystick = VirtualJoystick;
  52901. })(BABYLON || (BABYLON = {}));
  52902. var BABYLON;
  52903. (function (BABYLON) {
  52904. // We're mainly based on the logic defined into the FreeCamera code
  52905. var VirtualJoysticksCamera = (function (_super) {
  52906. __extends(VirtualJoysticksCamera, _super);
  52907. function VirtualJoysticksCamera(name, position, scene) {
  52908. _super.call(this, name, position, scene);
  52909. this.inputs.addVirtualJoystick();
  52910. }
  52911. return VirtualJoysticksCamera;
  52912. })(BABYLON.FreeCamera);
  52913. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  52914. })(BABYLON || (BABYLON = {}));
  52915. var BABYLON;
  52916. (function (BABYLON) {
  52917. var FreeCameraVirtualJoystickInput = (function () {
  52918. function FreeCameraVirtualJoystickInput() {
  52919. }
  52920. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  52921. return this._leftjoystick;
  52922. };
  52923. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  52924. return this._rightjoystick;
  52925. };
  52926. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  52927. if (this._leftjoystick) {
  52928. var camera = this.camera;
  52929. var speed = camera._computeLocalCameraSpeed() * 50;
  52930. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  52931. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  52932. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  52933. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  52934. if (!this._leftjoystick.pressed) {
  52935. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  52936. }
  52937. if (!this._rightjoystick.pressed) {
  52938. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  52939. }
  52940. }
  52941. };
  52942. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  52943. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  52944. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  52945. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  52946. this._leftjoystick.setJoystickSensibility(0.15);
  52947. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  52948. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  52949. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  52950. this._rightjoystick.reverseUpDown = true;
  52951. this._rightjoystick.setJoystickSensibility(0.05);
  52952. this._rightjoystick.setJoystickColor("yellow");
  52953. };
  52954. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  52955. this._leftjoystick.releaseCanvas();
  52956. this._rightjoystick.releaseCanvas();
  52957. };
  52958. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  52959. return "FreeCameraVirtualJoystickInput";
  52960. };
  52961. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  52962. return "virtualJoystick";
  52963. };
  52964. return FreeCameraVirtualJoystickInput;
  52965. })();
  52966. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  52967. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  52968. })(BABYLON || (BABYLON = {}));
  52969. var BABYLON;
  52970. (function (BABYLON) {
  52971. var AnaglyphPostProcess = (function (_super) {
  52972. __extends(AnaglyphPostProcess, _super);
  52973. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  52974. var _this = this;
  52975. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  52976. this._passedProcess = rigCameras[0]._rigPostProcess;
  52977. this.onApplyObservable.add(function (effect) {
  52978. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  52979. });
  52980. }
  52981. return AnaglyphPostProcess;
  52982. })(BABYLON.PostProcess);
  52983. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  52984. })(BABYLON || (BABYLON = {}));
  52985. var BABYLON;
  52986. (function (BABYLON) {
  52987. var OutlineRenderer = (function () {
  52988. function OutlineRenderer(scene) {
  52989. this._scene = scene;
  52990. }
  52991. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  52992. var _this = this;
  52993. if (useOverlay === void 0) { useOverlay = false; }
  52994. var scene = this._scene;
  52995. var engine = this._scene.getEngine();
  52996. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52997. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  52998. return;
  52999. }
  53000. var mesh = subMesh.getRenderingMesh();
  53001. var material = subMesh.getMaterial();
  53002. engine.enableEffect(this._effect);
  53003. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  53004. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  53005. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53006. // Bones
  53007. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53008. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53009. }
  53010. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  53011. // Alpha test
  53012. if (material && material.needAlphaTesting()) {
  53013. var alphaTexture = material.getAlphaTestTexture();
  53014. this._effect.setTexture("diffuseSampler", alphaTexture);
  53015. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53016. }
  53017. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  53018. };
  53019. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  53020. var defines = [];
  53021. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  53022. var mesh = subMesh.getMesh();
  53023. var material = subMesh.getMaterial();
  53024. // Alpha test
  53025. if (material && material.needAlphaTesting()) {
  53026. defines.push("#define ALPHATEST");
  53027. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53028. attribs.push(BABYLON.VertexBuffer.UVKind);
  53029. defines.push("#define UV1");
  53030. }
  53031. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53032. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53033. defines.push("#define UV2");
  53034. }
  53035. }
  53036. // Bones
  53037. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53038. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53039. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53040. if (mesh.numBoneInfluencers > 4) {
  53041. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53042. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53043. }
  53044. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53045. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53046. }
  53047. else {
  53048. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53049. }
  53050. // Instances
  53051. if (useInstances) {
  53052. defines.push("#define INSTANCES");
  53053. attribs.push("world0");
  53054. attribs.push("world1");
  53055. attribs.push("world2");
  53056. attribs.push("world3");
  53057. }
  53058. // Get correct effect
  53059. var join = defines.join("\n");
  53060. if (this._cachedDefines !== join) {
  53061. this._cachedDefines = join;
  53062. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  53063. }
  53064. return this._effect.isReady();
  53065. };
  53066. return OutlineRenderer;
  53067. })();
  53068. BABYLON.OutlineRenderer = OutlineRenderer;
  53069. })(BABYLON || (BABYLON = {}));
  53070. var BABYLON;
  53071. (function (BABYLON) {
  53072. var MeshAssetTask = (function () {
  53073. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  53074. this.name = name;
  53075. this.meshesNames = meshesNames;
  53076. this.rootUrl = rootUrl;
  53077. this.sceneFilename = sceneFilename;
  53078. this.isCompleted = false;
  53079. }
  53080. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53081. var _this = this;
  53082. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  53083. _this.loadedMeshes = meshes;
  53084. _this.loadedParticleSystems = particleSystems;
  53085. _this.loadedSkeletons = skeletons;
  53086. _this.isCompleted = true;
  53087. if (_this.onSuccess) {
  53088. _this.onSuccess(_this);
  53089. }
  53090. onSuccess();
  53091. }, null, function () {
  53092. if (_this.onError) {
  53093. _this.onError(_this);
  53094. }
  53095. onError();
  53096. });
  53097. };
  53098. return MeshAssetTask;
  53099. })();
  53100. BABYLON.MeshAssetTask = MeshAssetTask;
  53101. var TextFileAssetTask = (function () {
  53102. function TextFileAssetTask(name, url) {
  53103. this.name = name;
  53104. this.url = url;
  53105. this.isCompleted = false;
  53106. }
  53107. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53108. var _this = this;
  53109. BABYLON.Tools.LoadFile(this.url, function (data) {
  53110. _this.text = data;
  53111. _this.isCompleted = true;
  53112. if (_this.onSuccess) {
  53113. _this.onSuccess(_this);
  53114. }
  53115. onSuccess();
  53116. }, null, scene.database, false, function () {
  53117. if (_this.onError) {
  53118. _this.onError(_this);
  53119. }
  53120. onError();
  53121. });
  53122. };
  53123. return TextFileAssetTask;
  53124. })();
  53125. BABYLON.TextFileAssetTask = TextFileAssetTask;
  53126. var BinaryFileAssetTask = (function () {
  53127. function BinaryFileAssetTask(name, url) {
  53128. this.name = name;
  53129. this.url = url;
  53130. this.isCompleted = false;
  53131. }
  53132. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53133. var _this = this;
  53134. BABYLON.Tools.LoadFile(this.url, function (data) {
  53135. _this.data = data;
  53136. _this.isCompleted = true;
  53137. if (_this.onSuccess) {
  53138. _this.onSuccess(_this);
  53139. }
  53140. onSuccess();
  53141. }, null, scene.database, true, function () {
  53142. if (_this.onError) {
  53143. _this.onError(_this);
  53144. }
  53145. onError();
  53146. });
  53147. };
  53148. return BinaryFileAssetTask;
  53149. })();
  53150. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  53151. var ImageAssetTask = (function () {
  53152. function ImageAssetTask(name, url) {
  53153. this.name = name;
  53154. this.url = url;
  53155. this.isCompleted = false;
  53156. }
  53157. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53158. var _this = this;
  53159. var img = new Image();
  53160. BABYLON.Tools.SetCorsBehavior(this.url, img);
  53161. img.onload = function () {
  53162. _this.image = img;
  53163. _this.isCompleted = true;
  53164. if (_this.onSuccess) {
  53165. _this.onSuccess(_this);
  53166. }
  53167. onSuccess();
  53168. };
  53169. img.onerror = function () {
  53170. if (_this.onError) {
  53171. _this.onError(_this);
  53172. }
  53173. onError();
  53174. };
  53175. img.src = this.url;
  53176. };
  53177. return ImageAssetTask;
  53178. })();
  53179. BABYLON.ImageAssetTask = ImageAssetTask;
  53180. var TextureAssetTask = (function () {
  53181. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  53182. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53183. this.name = name;
  53184. this.url = url;
  53185. this.noMipmap = noMipmap;
  53186. this.invertY = invertY;
  53187. this.samplingMode = samplingMode;
  53188. this.isCompleted = false;
  53189. }
  53190. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  53191. var _this = this;
  53192. var onload = function () {
  53193. _this.isCompleted = true;
  53194. if (_this.onSuccess) {
  53195. _this.onSuccess(_this);
  53196. }
  53197. onSuccess();
  53198. };
  53199. var onerror = function () {
  53200. if (_this.onError) {
  53201. _this.onError(_this);
  53202. }
  53203. onError();
  53204. };
  53205. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  53206. };
  53207. return TextureAssetTask;
  53208. })();
  53209. BABYLON.TextureAssetTask = TextureAssetTask;
  53210. var AssetsManager = (function () {
  53211. function AssetsManager(scene) {
  53212. this._tasks = new Array();
  53213. this._waitingTasksCount = 0;
  53214. this.useDefaultLoadingScreen = true;
  53215. this._scene = scene;
  53216. }
  53217. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  53218. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  53219. this._tasks.push(task);
  53220. return task;
  53221. };
  53222. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  53223. var task = new TextFileAssetTask(taskName, url);
  53224. this._tasks.push(task);
  53225. return task;
  53226. };
  53227. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  53228. var task = new BinaryFileAssetTask(taskName, url);
  53229. this._tasks.push(task);
  53230. return task;
  53231. };
  53232. AssetsManager.prototype.addImageTask = function (taskName, url) {
  53233. var task = new ImageAssetTask(taskName, url);
  53234. this._tasks.push(task);
  53235. return task;
  53236. };
  53237. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  53238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53239. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  53240. this._tasks.push(task);
  53241. return task;
  53242. };
  53243. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  53244. this._waitingTasksCount--;
  53245. if (this._waitingTasksCount === 0) {
  53246. if (this.onFinish) {
  53247. this.onFinish(this._tasks);
  53248. }
  53249. this._scene.getEngine().hideLoadingUI();
  53250. }
  53251. };
  53252. AssetsManager.prototype._runTask = function (task) {
  53253. var _this = this;
  53254. task.run(this._scene, function () {
  53255. if (_this.onTaskSuccess) {
  53256. _this.onTaskSuccess(task);
  53257. }
  53258. _this._decreaseWaitingTasksCount();
  53259. }, function () {
  53260. if (_this.onTaskError) {
  53261. _this.onTaskError(task);
  53262. }
  53263. _this._decreaseWaitingTasksCount();
  53264. });
  53265. };
  53266. AssetsManager.prototype.reset = function () {
  53267. this._tasks = new Array();
  53268. return this;
  53269. };
  53270. AssetsManager.prototype.load = function () {
  53271. this._waitingTasksCount = this._tasks.length;
  53272. if (this._waitingTasksCount === 0) {
  53273. if (this.onFinish) {
  53274. this.onFinish(this._tasks);
  53275. }
  53276. return this;
  53277. }
  53278. if (this.useDefaultLoadingScreen) {
  53279. this._scene.getEngine().displayLoadingUI();
  53280. }
  53281. for (var index = 0; index < this._tasks.length; index++) {
  53282. var task = this._tasks[index];
  53283. this._runTask(task);
  53284. }
  53285. return this;
  53286. };
  53287. return AssetsManager;
  53288. })();
  53289. BABYLON.AssetsManager = AssetsManager;
  53290. })(BABYLON || (BABYLON = {}));
  53291. var BABYLON;
  53292. (function (BABYLON) {
  53293. var VRCameraMetrics = (function () {
  53294. function VRCameraMetrics() {
  53295. this.compensateDistortion = true;
  53296. }
  53297. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  53298. get: function () {
  53299. return this.hResolution / (2 * this.vResolution);
  53300. },
  53301. enumerable: true,
  53302. configurable: true
  53303. });
  53304. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  53305. get: function () {
  53306. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  53307. },
  53308. enumerable: true,
  53309. configurable: true
  53310. });
  53311. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  53312. get: function () {
  53313. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  53314. var h = (4 * meters) / this.hScreenSize;
  53315. return BABYLON.Matrix.Translation(h, 0, 0);
  53316. },
  53317. enumerable: true,
  53318. configurable: true
  53319. });
  53320. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  53321. get: function () {
  53322. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  53323. var h = (4 * meters) / this.hScreenSize;
  53324. return BABYLON.Matrix.Translation(-h, 0, 0);
  53325. },
  53326. enumerable: true,
  53327. configurable: true
  53328. });
  53329. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  53330. get: function () {
  53331. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  53332. },
  53333. enumerable: true,
  53334. configurable: true
  53335. });
  53336. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  53337. get: function () {
  53338. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  53339. },
  53340. enumerable: true,
  53341. configurable: true
  53342. });
  53343. VRCameraMetrics.GetDefault = function () {
  53344. var result = new VRCameraMetrics();
  53345. result.hResolution = 1280;
  53346. result.vResolution = 800;
  53347. result.hScreenSize = 0.149759993;
  53348. result.vScreenSize = 0.0935999975;
  53349. result.vScreenCenter = 0.0467999987,
  53350. result.eyeToScreenDistance = 0.0410000011;
  53351. result.lensSeparationDistance = 0.0635000020;
  53352. result.interpupillaryDistance = 0.0640000030;
  53353. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  53354. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  53355. result.postProcessScaleFactor = 1.714605507808412;
  53356. result.lensCenterOffset = 0.151976421;
  53357. return result;
  53358. };
  53359. return VRCameraMetrics;
  53360. })();
  53361. BABYLON.VRCameraMetrics = VRCameraMetrics;
  53362. })(BABYLON || (BABYLON = {}));
  53363. var BABYLON;
  53364. (function (BABYLON) {
  53365. var WebVRFreeCamera = (function (_super) {
  53366. __extends(WebVRFreeCamera, _super);
  53367. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  53368. var _this = this;
  53369. if (compensateDistortion === void 0) { compensateDistortion = false; }
  53370. if (webVROptions === void 0) { webVROptions = {}; }
  53371. _super.call(this, name, position, scene);
  53372. this.webVROptions = webVROptions;
  53373. this._vrDevice = null;
  53374. this._cacheState = null;
  53375. this._vrEnabled = false;
  53376. //enable VR
  53377. this.getEngine().initWebVR();
  53378. if (!this.getEngine().vrDisplaysPromise) {
  53379. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  53380. }
  53381. else {
  53382. //TODO get the metrics updated using the device's eye parameters!
  53383. //TODO also check that the device has the right capabilities!
  53384. this.getEngine().vrDisplaysPromise.then(function (devices) {
  53385. if (devices.length > 0) {
  53386. _this._vrEnabled = true;
  53387. if (_this.webVROptions.displayName) {
  53388. var found = devices.some(function (device) {
  53389. if (device.displayName === _this.webVROptions.displayName) {
  53390. _this._vrDevice = device;
  53391. return true;
  53392. }
  53393. else {
  53394. return false;
  53395. }
  53396. });
  53397. if (!found) {
  53398. _this._vrDevice = devices[0];
  53399. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  53400. }
  53401. }
  53402. else {
  53403. //choose the first one
  53404. _this._vrDevice = devices[0];
  53405. }
  53406. //reset the rig parameters.
  53407. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice });
  53408. }
  53409. else {
  53410. BABYLON.Tools.Error("No WebVR devices found!");
  53411. }
  53412. });
  53413. }
  53414. this.rotationQuaternion = new BABYLON.Quaternion();
  53415. this._quaternionCache = new BABYLON.Quaternion();
  53416. }
  53417. WebVRFreeCamera.prototype._checkInputs = function () {
  53418. if (this._vrEnabled) {
  53419. var currentPost = this._vrDevice.getPose();
  53420. //make sure we have data
  53421. if (currentPost && currentPost.orientation) {
  53422. this._cacheState = currentPost;
  53423. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], this._cacheState.orientation[2], this._cacheState.orientation[3]);
  53424. if (this.webVROptions.trackPosition && this._cacheState.position) {
  53425. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  53426. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  53427. }
  53428. //Flip in XY plane
  53429. this.rotationQuaternion.z *= -1;
  53430. this.rotationQuaternion.w *= -1;
  53431. }
  53432. }
  53433. _super.prototype._checkInputs.call(this);
  53434. };
  53435. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  53436. _super.prototype.attachControl.call(this, element, noPreventDefault);
  53437. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  53438. if (this._vrEnabled) {
  53439. this.getEngine().enableVR(this._vrDevice);
  53440. }
  53441. };
  53442. WebVRFreeCamera.prototype.detachControl = function (element) {
  53443. _super.prototype.detachControl.call(this, element);
  53444. this._vrEnabled = false;
  53445. this.getEngine().disableVR();
  53446. };
  53447. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  53448. //Backwards comp.
  53449. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  53450. //this.getEngine().switchFullscreen(requestPointerlock);
  53451. };
  53452. WebVRFreeCamera.prototype.getTypeName = function () {
  53453. return "WebVRFreeCamera";
  53454. };
  53455. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  53456. //uses the vrDisplay's "resetPose()".
  53457. //pitch and roll won't be affected.
  53458. this._vrDevice.resetPose();
  53459. };
  53460. return WebVRFreeCamera;
  53461. })(BABYLON.FreeCamera);
  53462. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  53463. })(BABYLON || (BABYLON = {}));
  53464. var BABYLON;
  53465. (function (BABYLON) {
  53466. // Standard optimizations
  53467. var SceneOptimization = (function () {
  53468. function SceneOptimization(priority) {
  53469. if (priority === void 0) { priority = 0; }
  53470. this.priority = priority;
  53471. this.apply = function (scene) {
  53472. return true; // Return true if everything that can be done was applied
  53473. };
  53474. }
  53475. return SceneOptimization;
  53476. })();
  53477. BABYLON.SceneOptimization = SceneOptimization;
  53478. var TextureOptimization = (function (_super) {
  53479. __extends(TextureOptimization, _super);
  53480. function TextureOptimization(priority, maximumSize) {
  53481. var _this = this;
  53482. if (priority === void 0) { priority = 0; }
  53483. if (maximumSize === void 0) { maximumSize = 1024; }
  53484. _super.call(this, priority);
  53485. this.priority = priority;
  53486. this.maximumSize = maximumSize;
  53487. this.apply = function (scene) {
  53488. var allDone = true;
  53489. for (var index = 0; index < scene.textures.length; index++) {
  53490. var texture = scene.textures[index];
  53491. if (!texture.canRescale) {
  53492. continue;
  53493. }
  53494. var currentSize = texture.getSize();
  53495. var maxDimension = Math.max(currentSize.width, currentSize.height);
  53496. if (maxDimension > _this.maximumSize) {
  53497. texture.scale(0.5);
  53498. allDone = false;
  53499. }
  53500. }
  53501. return allDone;
  53502. };
  53503. }
  53504. return TextureOptimization;
  53505. })(SceneOptimization);
  53506. BABYLON.TextureOptimization = TextureOptimization;
  53507. var HardwareScalingOptimization = (function (_super) {
  53508. __extends(HardwareScalingOptimization, _super);
  53509. function HardwareScalingOptimization(priority, maximumScale) {
  53510. var _this = this;
  53511. if (priority === void 0) { priority = 0; }
  53512. if (maximumScale === void 0) { maximumScale = 2; }
  53513. _super.call(this, priority);
  53514. this.priority = priority;
  53515. this.maximumScale = maximumScale;
  53516. this._currentScale = 1;
  53517. this.apply = function (scene) {
  53518. _this._currentScale++;
  53519. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  53520. return _this._currentScale >= _this.maximumScale;
  53521. };
  53522. }
  53523. return HardwareScalingOptimization;
  53524. })(SceneOptimization);
  53525. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  53526. var ShadowsOptimization = (function (_super) {
  53527. __extends(ShadowsOptimization, _super);
  53528. function ShadowsOptimization() {
  53529. _super.apply(this, arguments);
  53530. this.apply = function (scene) {
  53531. scene.shadowsEnabled = false;
  53532. return true;
  53533. };
  53534. }
  53535. return ShadowsOptimization;
  53536. })(SceneOptimization);
  53537. BABYLON.ShadowsOptimization = ShadowsOptimization;
  53538. var PostProcessesOptimization = (function (_super) {
  53539. __extends(PostProcessesOptimization, _super);
  53540. function PostProcessesOptimization() {
  53541. _super.apply(this, arguments);
  53542. this.apply = function (scene) {
  53543. scene.postProcessesEnabled = false;
  53544. return true;
  53545. };
  53546. }
  53547. return PostProcessesOptimization;
  53548. })(SceneOptimization);
  53549. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  53550. var LensFlaresOptimization = (function (_super) {
  53551. __extends(LensFlaresOptimization, _super);
  53552. function LensFlaresOptimization() {
  53553. _super.apply(this, arguments);
  53554. this.apply = function (scene) {
  53555. scene.lensFlaresEnabled = false;
  53556. return true;
  53557. };
  53558. }
  53559. return LensFlaresOptimization;
  53560. })(SceneOptimization);
  53561. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  53562. var ParticlesOptimization = (function (_super) {
  53563. __extends(ParticlesOptimization, _super);
  53564. function ParticlesOptimization() {
  53565. _super.apply(this, arguments);
  53566. this.apply = function (scene) {
  53567. scene.particlesEnabled = false;
  53568. return true;
  53569. };
  53570. }
  53571. return ParticlesOptimization;
  53572. })(SceneOptimization);
  53573. BABYLON.ParticlesOptimization = ParticlesOptimization;
  53574. var RenderTargetsOptimization = (function (_super) {
  53575. __extends(RenderTargetsOptimization, _super);
  53576. function RenderTargetsOptimization() {
  53577. _super.apply(this, arguments);
  53578. this.apply = function (scene) {
  53579. scene.renderTargetsEnabled = false;
  53580. return true;
  53581. };
  53582. }
  53583. return RenderTargetsOptimization;
  53584. })(SceneOptimization);
  53585. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  53586. var MergeMeshesOptimization = (function (_super) {
  53587. __extends(MergeMeshesOptimization, _super);
  53588. function MergeMeshesOptimization() {
  53589. var _this = this;
  53590. _super.apply(this, arguments);
  53591. this._canBeMerged = function (abstractMesh) {
  53592. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  53593. return false;
  53594. }
  53595. var mesh = abstractMesh;
  53596. if (!mesh.isVisible || !mesh.isEnabled()) {
  53597. return false;
  53598. }
  53599. if (mesh.instances.length > 0) {
  53600. return false;
  53601. }
  53602. if (mesh.skeleton || mesh.hasLODLevels) {
  53603. return false;
  53604. }
  53605. if (mesh.parent) {
  53606. return false;
  53607. }
  53608. return true;
  53609. };
  53610. this.apply = function (scene, updateSelectionTree) {
  53611. var globalPool = scene.meshes.slice(0);
  53612. var globalLength = globalPool.length;
  53613. for (var index = 0; index < globalLength; index++) {
  53614. var currentPool = new Array();
  53615. var current = globalPool[index];
  53616. // Checks
  53617. if (!_this._canBeMerged(current)) {
  53618. continue;
  53619. }
  53620. currentPool.push(current);
  53621. // Find compatible meshes
  53622. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  53623. var otherMesh = globalPool[subIndex];
  53624. if (!_this._canBeMerged(otherMesh)) {
  53625. continue;
  53626. }
  53627. if (otherMesh.material !== current.material) {
  53628. continue;
  53629. }
  53630. if (otherMesh.checkCollisions !== current.checkCollisions) {
  53631. continue;
  53632. }
  53633. currentPool.push(otherMesh);
  53634. globalLength--;
  53635. globalPool.splice(subIndex, 1);
  53636. subIndex--;
  53637. }
  53638. if (currentPool.length < 2) {
  53639. continue;
  53640. }
  53641. // Merge meshes
  53642. BABYLON.Mesh.MergeMeshes(currentPool);
  53643. }
  53644. if (updateSelectionTree != undefined) {
  53645. if (updateSelectionTree) {
  53646. scene.createOrUpdateSelectionOctree();
  53647. }
  53648. }
  53649. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  53650. scene.createOrUpdateSelectionOctree();
  53651. }
  53652. return true;
  53653. };
  53654. }
  53655. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  53656. get: function () {
  53657. return MergeMeshesOptimization._UpdateSelectionTree;
  53658. },
  53659. set: function (value) {
  53660. MergeMeshesOptimization._UpdateSelectionTree = value;
  53661. },
  53662. enumerable: true,
  53663. configurable: true
  53664. });
  53665. MergeMeshesOptimization._UpdateSelectionTree = false;
  53666. return MergeMeshesOptimization;
  53667. })(SceneOptimization);
  53668. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  53669. // Options
  53670. var SceneOptimizerOptions = (function () {
  53671. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  53672. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  53673. if (trackerDuration === void 0) { trackerDuration = 2000; }
  53674. this.targetFrameRate = targetFrameRate;
  53675. this.trackerDuration = trackerDuration;
  53676. this.optimizations = new Array();
  53677. }
  53678. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  53679. var result = new SceneOptimizerOptions(targetFrameRate);
  53680. var priority = 0;
  53681. result.optimizations.push(new MergeMeshesOptimization(priority));
  53682. result.optimizations.push(new ShadowsOptimization(priority));
  53683. result.optimizations.push(new LensFlaresOptimization(priority));
  53684. // Next priority
  53685. priority++;
  53686. result.optimizations.push(new PostProcessesOptimization(priority));
  53687. result.optimizations.push(new ParticlesOptimization(priority));
  53688. // Next priority
  53689. priority++;
  53690. result.optimizations.push(new TextureOptimization(priority, 1024));
  53691. return result;
  53692. };
  53693. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  53694. var result = new SceneOptimizerOptions(targetFrameRate);
  53695. var priority = 0;
  53696. result.optimizations.push(new MergeMeshesOptimization(priority));
  53697. result.optimizations.push(new ShadowsOptimization(priority));
  53698. result.optimizations.push(new LensFlaresOptimization(priority));
  53699. // Next priority
  53700. priority++;
  53701. result.optimizations.push(new PostProcessesOptimization(priority));
  53702. result.optimizations.push(new ParticlesOptimization(priority));
  53703. // Next priority
  53704. priority++;
  53705. result.optimizations.push(new TextureOptimization(priority, 512));
  53706. // Next priority
  53707. priority++;
  53708. result.optimizations.push(new RenderTargetsOptimization(priority));
  53709. // Next priority
  53710. priority++;
  53711. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  53712. return result;
  53713. };
  53714. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  53715. var result = new SceneOptimizerOptions(targetFrameRate);
  53716. var priority = 0;
  53717. result.optimizations.push(new MergeMeshesOptimization(priority));
  53718. result.optimizations.push(new ShadowsOptimization(priority));
  53719. result.optimizations.push(new LensFlaresOptimization(priority));
  53720. // Next priority
  53721. priority++;
  53722. result.optimizations.push(new PostProcessesOptimization(priority));
  53723. result.optimizations.push(new ParticlesOptimization(priority));
  53724. // Next priority
  53725. priority++;
  53726. result.optimizations.push(new TextureOptimization(priority, 256));
  53727. // Next priority
  53728. priority++;
  53729. result.optimizations.push(new RenderTargetsOptimization(priority));
  53730. // Next priority
  53731. priority++;
  53732. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  53733. return result;
  53734. };
  53735. return SceneOptimizerOptions;
  53736. })();
  53737. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  53738. // Scene optimizer tool
  53739. var SceneOptimizer = (function () {
  53740. function SceneOptimizer() {
  53741. }
  53742. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  53743. // TODO: add an epsilon
  53744. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  53745. if (onSuccess) {
  53746. onSuccess();
  53747. }
  53748. return;
  53749. }
  53750. // Apply current level of optimizations
  53751. var allDone = true;
  53752. var noOptimizationApplied = true;
  53753. for (var index = 0; index < options.optimizations.length; index++) {
  53754. var optimization = options.optimizations[index];
  53755. if (optimization.priority === currentPriorityLevel) {
  53756. noOptimizationApplied = false;
  53757. allDone = allDone && optimization.apply(scene);
  53758. }
  53759. }
  53760. // If no optimization was applied, this is a failure :(
  53761. if (noOptimizationApplied) {
  53762. if (onFailure) {
  53763. onFailure();
  53764. }
  53765. return;
  53766. }
  53767. // If all optimizations were done, move to next level
  53768. if (allDone) {
  53769. currentPriorityLevel++;
  53770. }
  53771. // Let's the system running for a specific amount of time before checking FPS
  53772. scene.executeWhenReady(function () {
  53773. setTimeout(function () {
  53774. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  53775. }, options.trackerDuration);
  53776. });
  53777. };
  53778. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  53779. if (!options) {
  53780. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  53781. }
  53782. // Let's the system running for a specific amount of time before checking FPS
  53783. scene.executeWhenReady(function () {
  53784. setTimeout(function () {
  53785. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  53786. }, options.trackerDuration);
  53787. });
  53788. };
  53789. return SceneOptimizer;
  53790. })();
  53791. BABYLON.SceneOptimizer = SceneOptimizer;
  53792. })(BABYLON || (BABYLON = {}));
  53793. var BABYLON;
  53794. (function (BABYLON) {
  53795. var Internals;
  53796. (function (Internals) {
  53797. var MeshLODLevel = (function () {
  53798. function MeshLODLevel(distance, mesh) {
  53799. this.distance = distance;
  53800. this.mesh = mesh;
  53801. }
  53802. return MeshLODLevel;
  53803. })();
  53804. Internals.MeshLODLevel = MeshLODLevel;
  53805. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53806. })(BABYLON || (BABYLON = {}));
  53807. var BABYLON;
  53808. (function (BABYLON) {
  53809. var RawTexture = (function (_super) {
  53810. __extends(RawTexture, _super);
  53811. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  53812. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53813. if (invertY === void 0) { invertY = false; }
  53814. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53815. _super.call(this, null, scene, !generateMipMaps, invertY);
  53816. this.format = format;
  53817. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  53818. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53819. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53820. }
  53821. RawTexture.prototype.update = function (data) {
  53822. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  53823. };
  53824. // Statics
  53825. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53826. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53827. if (invertY === void 0) { invertY = false; }
  53828. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53829. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  53830. };
  53831. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53832. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53833. if (invertY === void 0) { invertY = false; }
  53834. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53835. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  53836. };
  53837. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53838. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53839. if (invertY === void 0) { invertY = false; }
  53840. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53841. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  53842. };
  53843. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53844. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53845. if (invertY === void 0) { invertY = false; }
  53846. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53847. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  53848. };
  53849. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53850. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53851. if (invertY === void 0) { invertY = false; }
  53852. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53853. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  53854. };
  53855. return RawTexture;
  53856. })(BABYLON.Texture);
  53857. BABYLON.RawTexture = RawTexture;
  53858. })(BABYLON || (BABYLON = {}));
  53859. var BABYLON;
  53860. (function (BABYLON) {
  53861. var IndexedVector2 = (function (_super) {
  53862. __extends(IndexedVector2, _super);
  53863. function IndexedVector2(original, index) {
  53864. _super.call(this, original.x, original.y);
  53865. this.index = index;
  53866. }
  53867. return IndexedVector2;
  53868. })(BABYLON.Vector2);
  53869. var PolygonPoints = (function () {
  53870. function PolygonPoints() {
  53871. this.elements = new Array();
  53872. }
  53873. PolygonPoints.prototype.add = function (originalPoints) {
  53874. var _this = this;
  53875. var result = new Array();
  53876. originalPoints.forEach(function (point) {
  53877. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  53878. var newPoint = new IndexedVector2(point, _this.elements.length);
  53879. result.push(newPoint);
  53880. _this.elements.push(newPoint);
  53881. }
  53882. });
  53883. return result;
  53884. };
  53885. PolygonPoints.prototype.computeBounds = function () {
  53886. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53887. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53888. this.elements.forEach(function (point) {
  53889. // x
  53890. if (point.x < lmin.x) {
  53891. lmin.x = point.x;
  53892. }
  53893. else if (point.x > lmax.x) {
  53894. lmax.x = point.x;
  53895. }
  53896. // y
  53897. if (point.y < lmin.y) {
  53898. lmin.y = point.y;
  53899. }
  53900. else if (point.y > lmax.y) {
  53901. lmax.y = point.y;
  53902. }
  53903. });
  53904. return {
  53905. min: lmin,
  53906. max: lmax,
  53907. width: lmax.x - lmin.x,
  53908. height: lmax.y - lmin.y
  53909. };
  53910. };
  53911. return PolygonPoints;
  53912. })();
  53913. var Polygon = (function () {
  53914. function Polygon() {
  53915. }
  53916. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  53917. return [
  53918. new BABYLON.Vector2(xmin, ymin),
  53919. new BABYLON.Vector2(xmax, ymin),
  53920. new BABYLON.Vector2(xmax, ymax),
  53921. new BABYLON.Vector2(xmin, ymax)
  53922. ];
  53923. };
  53924. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  53925. if (cx === void 0) { cx = 0; }
  53926. if (cy === void 0) { cy = 0; }
  53927. if (numberOfSides === void 0) { numberOfSides = 32; }
  53928. var result = new Array();
  53929. var angle = 0;
  53930. var increment = (Math.PI * 2) / numberOfSides;
  53931. for (var i = 0; i < numberOfSides; i++) {
  53932. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  53933. angle -= increment;
  53934. }
  53935. return result;
  53936. };
  53937. Polygon.Parse = function (input) {
  53938. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  53939. var i, result = [];
  53940. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  53941. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  53942. }
  53943. return result;
  53944. };
  53945. Polygon.StartingAt = function (x, y) {
  53946. return BABYLON.Path2.StartingAt(x, y);
  53947. };
  53948. return Polygon;
  53949. })();
  53950. BABYLON.Polygon = Polygon;
  53951. var PolygonMeshBuilder = (function () {
  53952. function PolygonMeshBuilder(name, contours, scene) {
  53953. this._points = new PolygonPoints();
  53954. this._outlinepoints = new PolygonPoints();
  53955. this._holes = [];
  53956. this._epoints = new Array();
  53957. this._eholes = new Array();
  53958. this._name = name;
  53959. this._scene = scene;
  53960. var points;
  53961. if (contours instanceof BABYLON.Path2) {
  53962. points = contours.getPoints();
  53963. }
  53964. else {
  53965. points = contours;
  53966. }
  53967. this._addToepoint(points);
  53968. this._points.add(points);
  53969. this._outlinepoints.add(points);
  53970. }
  53971. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  53972. for (var _i = 0; _i < points.length; _i++) {
  53973. var p = points[_i];
  53974. this._epoints.push(p.x, p.y);
  53975. }
  53976. };
  53977. PolygonMeshBuilder.prototype.addHole = function (hole) {
  53978. this._points.add(hole);
  53979. var holepoints = new PolygonPoints();
  53980. holepoints.add(hole);
  53981. this._holes.push(holepoints);
  53982. this._eholes.push(this._epoints.length / 2);
  53983. this._addToepoint(hole);
  53984. return this;
  53985. };
  53986. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  53987. var _this = this;
  53988. if (updatable === void 0) { updatable = false; }
  53989. var result = new BABYLON.Mesh(this._name, this._scene);
  53990. var normals = [];
  53991. var positions = [];
  53992. var uvs = [];
  53993. var bounds = this._points.computeBounds();
  53994. this._points.elements.forEach(function (p) {
  53995. normals.push(0, 1.0, 0);
  53996. positions.push(p.x, 0, p.y);
  53997. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  53998. });
  53999. var indices = [];
  54000. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  54001. for (var i = 0; i < res.length; i++) {
  54002. indices.push(res[i]);
  54003. }
  54004. if (depth > 0) {
  54005. var positionscount = (positions.length / 3); //get the current pointcount
  54006. this._points.elements.forEach(function (p) {
  54007. normals.push(0, -1.0, 0);
  54008. positions.push(p.x, -depth, p.y);
  54009. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  54010. });
  54011. var totalCount = indices.length;
  54012. for (var i = 0; i < totalCount; i += 3) {
  54013. var i0 = indices[i + 0];
  54014. var i1 = indices[i + 1];
  54015. var i2 = indices[i + 2];
  54016. indices.push(i2 + positionscount);
  54017. indices.push(i1 + positionscount);
  54018. indices.push(i0 + positionscount);
  54019. }
  54020. //Add the sides
  54021. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  54022. this._holes.forEach(function (hole) {
  54023. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  54024. });
  54025. }
  54026. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  54027. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  54028. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  54029. result.setIndices(indices);
  54030. return result;
  54031. };
  54032. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  54033. var StartIndex = positions.length / 3;
  54034. var ulength = 0;
  54035. for (var i = 0; i < points.elements.length; i++) {
  54036. var p = points.elements[i];
  54037. var p1;
  54038. if ((i + 1) > points.elements.length - 1) {
  54039. p1 = points.elements[0];
  54040. }
  54041. else {
  54042. p1 = points.elements[i + 1];
  54043. }
  54044. positions.push(p.x, 0, p.y);
  54045. positions.push(p.x, -depth, p.y);
  54046. positions.push(p1.x, 0, p1.y);
  54047. positions.push(p1.x, -depth, p1.y);
  54048. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  54049. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  54050. var v3 = v2.subtract(v1);
  54051. var v4 = new BABYLON.Vector3(0, 1, 0);
  54052. var vn = BABYLON.Vector3.Cross(v3, v4);
  54053. vn = vn.normalize();
  54054. uvs.push(ulength / bounds.width, 0);
  54055. uvs.push(ulength / bounds.width, 1);
  54056. ulength += v3.length();
  54057. uvs.push((ulength / bounds.width), 0);
  54058. uvs.push((ulength / bounds.width), 1);
  54059. if (!flip) {
  54060. normals.push(-vn.x, -vn.y, -vn.z);
  54061. normals.push(-vn.x, -vn.y, -vn.z);
  54062. normals.push(-vn.x, -vn.y, -vn.z);
  54063. normals.push(-vn.x, -vn.y, -vn.z);
  54064. indices.push(StartIndex);
  54065. indices.push(StartIndex + 1);
  54066. indices.push(StartIndex + 2);
  54067. indices.push(StartIndex + 1);
  54068. indices.push(StartIndex + 3);
  54069. indices.push(StartIndex + 2);
  54070. }
  54071. else {
  54072. normals.push(vn.x, vn.y, vn.z);
  54073. normals.push(vn.x, vn.y, vn.z);
  54074. normals.push(vn.x, vn.y, vn.z);
  54075. normals.push(vn.x, vn.y, vn.z);
  54076. indices.push(StartIndex);
  54077. indices.push(StartIndex + 2);
  54078. indices.push(StartIndex + 1);
  54079. indices.push(StartIndex + 1);
  54080. indices.push(StartIndex + 2);
  54081. indices.push(StartIndex + 3);
  54082. }
  54083. StartIndex += 4;
  54084. }
  54085. ;
  54086. };
  54087. return PolygonMeshBuilder;
  54088. })();
  54089. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  54090. })(BABYLON || (BABYLON = {}));
  54091. var BABYLON;
  54092. (function (BABYLON) {
  54093. var Octree = (function () {
  54094. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  54095. if (maxDepth === void 0) { maxDepth = 2; }
  54096. this.maxDepth = maxDepth;
  54097. this.dynamicContent = new Array();
  54098. this._maxBlockCapacity = maxBlockCapacity || 64;
  54099. this._selectionContent = new BABYLON.SmartArray(1024);
  54100. this._creationFunc = creationFunc;
  54101. }
  54102. // Methods
  54103. Octree.prototype.update = function (worldMin, worldMax, entries) {
  54104. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  54105. };
  54106. Octree.prototype.addMesh = function (entry) {
  54107. for (var index = 0; index < this.blocks.length; index++) {
  54108. var block = this.blocks[index];
  54109. block.addEntry(entry);
  54110. }
  54111. };
  54112. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  54113. this._selectionContent.reset();
  54114. for (var index = 0; index < this.blocks.length; index++) {
  54115. var block = this.blocks[index];
  54116. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  54117. }
  54118. if (allowDuplicate) {
  54119. this._selectionContent.concat(this.dynamicContent);
  54120. }
  54121. else {
  54122. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  54123. }
  54124. return this._selectionContent;
  54125. };
  54126. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  54127. this._selectionContent.reset();
  54128. for (var index = 0; index < this.blocks.length; index++) {
  54129. var block = this.blocks[index];
  54130. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  54131. }
  54132. if (allowDuplicate) {
  54133. this._selectionContent.concat(this.dynamicContent);
  54134. }
  54135. else {
  54136. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  54137. }
  54138. return this._selectionContent;
  54139. };
  54140. Octree.prototype.intersectsRay = function (ray) {
  54141. this._selectionContent.reset();
  54142. for (var index = 0; index < this.blocks.length; index++) {
  54143. var block = this.blocks[index];
  54144. block.intersectsRay(ray, this._selectionContent);
  54145. }
  54146. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  54147. return this._selectionContent;
  54148. };
  54149. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  54150. target.blocks = new Array();
  54151. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  54152. // Segmenting space
  54153. for (var x = 0; x < 2; x++) {
  54154. for (var y = 0; y < 2; y++) {
  54155. for (var z = 0; z < 2; z++) {
  54156. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  54157. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  54158. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  54159. block.addEntries(entries);
  54160. target.blocks.push(block);
  54161. }
  54162. }
  54163. }
  54164. };
  54165. Octree.CreationFuncForMeshes = function (entry, block) {
  54166. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  54167. block.entries.push(entry);
  54168. }
  54169. };
  54170. Octree.CreationFuncForSubMeshes = function (entry, block) {
  54171. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  54172. block.entries.push(entry);
  54173. }
  54174. };
  54175. return Octree;
  54176. })();
  54177. BABYLON.Octree = Octree;
  54178. })(BABYLON || (BABYLON = {}));
  54179. var BABYLON;
  54180. (function (BABYLON) {
  54181. var OctreeBlock = (function () {
  54182. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  54183. this.entries = new Array();
  54184. this._boundingVectors = new Array();
  54185. this._capacity = capacity;
  54186. this._depth = depth;
  54187. this._maxDepth = maxDepth;
  54188. this._creationFunc = creationFunc;
  54189. this._minPoint = minPoint;
  54190. this._maxPoint = maxPoint;
  54191. this._boundingVectors.push(minPoint.clone());
  54192. this._boundingVectors.push(maxPoint.clone());
  54193. this._boundingVectors.push(minPoint.clone());
  54194. this._boundingVectors[2].x = maxPoint.x;
  54195. this._boundingVectors.push(minPoint.clone());
  54196. this._boundingVectors[3].y = maxPoint.y;
  54197. this._boundingVectors.push(minPoint.clone());
  54198. this._boundingVectors[4].z = maxPoint.z;
  54199. this._boundingVectors.push(maxPoint.clone());
  54200. this._boundingVectors[5].z = minPoint.z;
  54201. this._boundingVectors.push(maxPoint.clone());
  54202. this._boundingVectors[6].x = minPoint.x;
  54203. this._boundingVectors.push(maxPoint.clone());
  54204. this._boundingVectors[7].y = minPoint.y;
  54205. }
  54206. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  54207. // Property
  54208. get: function () {
  54209. return this._capacity;
  54210. },
  54211. enumerable: true,
  54212. configurable: true
  54213. });
  54214. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  54215. get: function () {
  54216. return this._minPoint;
  54217. },
  54218. enumerable: true,
  54219. configurable: true
  54220. });
  54221. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  54222. get: function () {
  54223. return this._maxPoint;
  54224. },
  54225. enumerable: true,
  54226. configurable: true
  54227. });
  54228. // Methods
  54229. OctreeBlock.prototype.addEntry = function (entry) {
  54230. if (this.blocks) {
  54231. for (var index = 0; index < this.blocks.length; index++) {
  54232. var block = this.blocks[index];
  54233. block.addEntry(entry);
  54234. }
  54235. return;
  54236. }
  54237. this._creationFunc(entry, this);
  54238. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  54239. this.createInnerBlocks();
  54240. }
  54241. };
  54242. OctreeBlock.prototype.addEntries = function (entries) {
  54243. for (var index = 0; index < entries.length; index++) {
  54244. var mesh = entries[index];
  54245. this.addEntry(mesh);
  54246. }
  54247. };
  54248. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  54249. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  54250. if (this.blocks) {
  54251. for (var index = 0; index < this.blocks.length; index++) {
  54252. var block = this.blocks[index];
  54253. block.select(frustumPlanes, selection, allowDuplicate);
  54254. }
  54255. return;
  54256. }
  54257. if (allowDuplicate) {
  54258. selection.concat(this.entries);
  54259. }
  54260. else {
  54261. selection.concatWithNoDuplicate(this.entries);
  54262. }
  54263. }
  54264. };
  54265. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  54266. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  54267. if (this.blocks) {
  54268. for (var index = 0; index < this.blocks.length; index++) {
  54269. var block = this.blocks[index];
  54270. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  54271. }
  54272. return;
  54273. }
  54274. if (allowDuplicate) {
  54275. selection.concat(this.entries);
  54276. }
  54277. else {
  54278. selection.concatWithNoDuplicate(this.entries);
  54279. }
  54280. }
  54281. };
  54282. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  54283. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  54284. if (this.blocks) {
  54285. for (var index = 0; index < this.blocks.length; index++) {
  54286. var block = this.blocks[index];
  54287. block.intersectsRay(ray, selection);
  54288. }
  54289. return;
  54290. }
  54291. selection.concatWithNoDuplicate(this.entries);
  54292. }
  54293. };
  54294. OctreeBlock.prototype.createInnerBlocks = function () {
  54295. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  54296. };
  54297. return OctreeBlock;
  54298. })();
  54299. BABYLON.OctreeBlock = OctreeBlock;
  54300. })(BABYLON || (BABYLON = {}));
  54301. var BABYLON;
  54302. (function (BABYLON) {
  54303. var BlurPostProcess = (function (_super) {
  54304. __extends(BlurPostProcess, _super);
  54305. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  54306. var _this = this;
  54307. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54308. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  54309. this.direction = direction;
  54310. this.blurWidth = blurWidth;
  54311. this.onApplyObservable.add(function (effect) {
  54312. effect.setFloat2("screenSize", _this.width, _this.height);
  54313. effect.setVector2("direction", _this.direction);
  54314. effect.setFloat("blurWidth", _this.blurWidth);
  54315. });
  54316. }
  54317. return BlurPostProcess;
  54318. })(BABYLON.PostProcess);
  54319. BABYLON.BlurPostProcess = BlurPostProcess;
  54320. })(BABYLON || (BABYLON = {}));
  54321. var BABYLON;
  54322. (function (BABYLON) {
  54323. var RefractionPostProcess = (function (_super) {
  54324. __extends(RefractionPostProcess, _super);
  54325. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  54326. var _this = this;
  54327. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  54328. this.color = color;
  54329. this.depth = depth;
  54330. this.colorLevel = colorLevel;
  54331. this.onActivateObservable.add(function (cam) {
  54332. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  54333. });
  54334. this.onApplyObservable.add(function (effect) {
  54335. effect.setColor3("baseColor", _this.color);
  54336. effect.setFloat("depth", _this.depth);
  54337. effect.setFloat("colorLevel", _this.colorLevel);
  54338. effect.setTexture("refractionSampler", _this._refRexture);
  54339. });
  54340. }
  54341. // Methods
  54342. RefractionPostProcess.prototype.dispose = function (camera) {
  54343. if (this._refRexture) {
  54344. this._refRexture.dispose();
  54345. }
  54346. _super.prototype.dispose.call(this, camera);
  54347. };
  54348. return RefractionPostProcess;
  54349. })(BABYLON.PostProcess);
  54350. BABYLON.RefractionPostProcess = RefractionPostProcess;
  54351. })(BABYLON || (BABYLON = {}));
  54352. var BABYLON;
  54353. (function (BABYLON) {
  54354. var BlackAndWhitePostProcess = (function (_super) {
  54355. __extends(BlackAndWhitePostProcess, _super);
  54356. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  54357. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  54358. }
  54359. return BlackAndWhitePostProcess;
  54360. })(BABYLON.PostProcess);
  54361. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  54362. })(BABYLON || (BABYLON = {}));
  54363. var BABYLON;
  54364. (function (BABYLON) {
  54365. var ConvolutionPostProcess = (function (_super) {
  54366. __extends(ConvolutionPostProcess, _super);
  54367. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  54368. var _this = this;
  54369. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  54370. this.kernel = kernel;
  54371. this.onApply = function (effect) {
  54372. effect.setFloat2("screenSize", _this.width, _this.height);
  54373. effect.setArray("kernel", _this.kernel);
  54374. };
  54375. }
  54376. // Statics
  54377. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  54378. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  54379. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  54380. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  54381. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  54382. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  54383. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  54384. return ConvolutionPostProcess;
  54385. })(BABYLON.PostProcess);
  54386. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  54387. })(BABYLON || (BABYLON = {}));
  54388. var BABYLON;
  54389. (function (BABYLON) {
  54390. var FilterPostProcess = (function (_super) {
  54391. __extends(FilterPostProcess, _super);
  54392. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  54393. var _this = this;
  54394. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  54395. this.kernelMatrix = kernelMatrix;
  54396. this.onApply = function (effect) {
  54397. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  54398. };
  54399. }
  54400. return FilterPostProcess;
  54401. })(BABYLON.PostProcess);
  54402. BABYLON.FilterPostProcess = FilterPostProcess;
  54403. })(BABYLON || (BABYLON = {}));
  54404. var BABYLON;
  54405. (function (BABYLON) {
  54406. var FxaaPostProcess = (function (_super) {
  54407. __extends(FxaaPostProcess, _super);
  54408. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  54409. var _this = this;
  54410. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  54411. this.onSizeChangedObservable.add(function () {
  54412. _this.texelWidth = 1.0 / _this.width;
  54413. _this.texelHeight = 1.0 / _this.height;
  54414. });
  54415. this.onApplyObservable.add(function (effect) {
  54416. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  54417. });
  54418. }
  54419. return FxaaPostProcess;
  54420. })(BABYLON.PostProcess);
  54421. BABYLON.FxaaPostProcess = FxaaPostProcess;
  54422. })(BABYLON || (BABYLON = {}));
  54423. var BABYLON;
  54424. (function (BABYLON) {
  54425. var StereoscopicInterlacePostProcess = (function (_super) {
  54426. __extends(StereoscopicInterlacePostProcess, _super);
  54427. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  54428. var _this = this;
  54429. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  54430. this._passedProcess = rigCameras[0]._rigPostProcess;
  54431. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  54432. this.onSizeChangedObservable.add(function () {
  54433. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  54434. });
  54435. this.onApplyObservable.add(function (effect) {
  54436. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  54437. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  54438. });
  54439. }
  54440. return StereoscopicInterlacePostProcess;
  54441. })(BABYLON.PostProcess);
  54442. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  54443. })(BABYLON || (BABYLON = {}));
  54444. var BABYLON;
  54445. (function (BABYLON) {
  54446. var LensFlare = (function () {
  54447. function LensFlare(size, position, color, imgUrl, system) {
  54448. this.size = size;
  54449. this.position = position;
  54450. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  54451. this.dispose = function () {
  54452. if (this.texture) {
  54453. this.texture.dispose();
  54454. }
  54455. // Remove from scene
  54456. var index = this._system.lensFlares.indexOf(this);
  54457. this._system.lensFlares.splice(index, 1);
  54458. };
  54459. this.color = color || new BABYLON.Color3(1, 1, 1);
  54460. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  54461. this._system = system;
  54462. system.lensFlares.push(this);
  54463. }
  54464. return LensFlare;
  54465. })();
  54466. BABYLON.LensFlare = LensFlare;
  54467. })(BABYLON || (BABYLON = {}));
  54468. var BABYLON;
  54469. (function (BABYLON) {
  54470. var LensFlareSystem = (function () {
  54471. function LensFlareSystem(name, emitter, scene) {
  54472. this.name = name;
  54473. this.lensFlares = new Array();
  54474. this.borderLimit = 300;
  54475. this.layerMask = 0x0FFFFFFF;
  54476. this._vertexBuffers = {};
  54477. this._isEnabled = true;
  54478. this._scene = scene;
  54479. this._emitter = emitter;
  54480. this.id = name;
  54481. scene.lensFlareSystems.push(this);
  54482. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  54483. var engine = scene.getEngine();
  54484. // VBO
  54485. var vertices = [];
  54486. vertices.push(1, 1);
  54487. vertices.push(-1, 1);
  54488. vertices.push(-1, -1);
  54489. vertices.push(1, -1);
  54490. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54491. // Indices
  54492. var indices = [];
  54493. indices.push(0);
  54494. indices.push(1);
  54495. indices.push(2);
  54496. indices.push(0);
  54497. indices.push(2);
  54498. indices.push(3);
  54499. this._indexBuffer = engine.createIndexBuffer(indices);
  54500. // Effects
  54501. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  54502. }
  54503. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  54504. get: function () {
  54505. return this._isEnabled;
  54506. },
  54507. set: function (value) {
  54508. this._isEnabled = value;
  54509. },
  54510. enumerable: true,
  54511. configurable: true
  54512. });
  54513. LensFlareSystem.prototype.getScene = function () {
  54514. return this._scene;
  54515. };
  54516. LensFlareSystem.prototype.getEmitter = function () {
  54517. return this._emitter;
  54518. };
  54519. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  54520. this._emitter = newEmitter;
  54521. };
  54522. LensFlareSystem.prototype.getEmitterPosition = function () {
  54523. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  54524. };
  54525. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  54526. var position = this.getEmitterPosition();
  54527. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  54528. this._positionX = position.x;
  54529. this._positionY = position.y;
  54530. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  54531. if (position.z > 0) {
  54532. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  54533. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  54534. return true;
  54535. }
  54536. }
  54537. return false;
  54538. };
  54539. LensFlareSystem.prototype._isVisible = function () {
  54540. if (!this._isEnabled) {
  54541. return false;
  54542. }
  54543. var emitterPosition = this.getEmitterPosition();
  54544. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  54545. var distance = direction.length();
  54546. direction.normalize();
  54547. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  54548. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  54549. return !pickInfo.hit || pickInfo.distance > distance;
  54550. };
  54551. LensFlareSystem.prototype.render = function () {
  54552. if (!this._effect.isReady())
  54553. return false;
  54554. var engine = this._scene.getEngine();
  54555. var viewport = this._scene.activeCamera.viewport;
  54556. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  54557. // Position
  54558. if (!this.computeEffectivePosition(globalViewport)) {
  54559. return false;
  54560. }
  54561. // Visibility
  54562. if (!this._isVisible()) {
  54563. return false;
  54564. }
  54565. // Intensity
  54566. var awayX;
  54567. var awayY;
  54568. if (this._positionX < this.borderLimit + globalViewport.x) {
  54569. awayX = this.borderLimit + globalViewport.x - this._positionX;
  54570. }
  54571. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  54572. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  54573. }
  54574. else {
  54575. awayX = 0;
  54576. }
  54577. if (this._positionY < this.borderLimit + globalViewport.y) {
  54578. awayY = this.borderLimit + globalViewport.y - this._positionY;
  54579. }
  54580. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  54581. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  54582. }
  54583. else {
  54584. awayY = 0;
  54585. }
  54586. var away = (awayX > awayY) ? awayX : awayY;
  54587. if (away > this.borderLimit) {
  54588. away = this.borderLimit;
  54589. }
  54590. var intensity = 1.0 - (away / this.borderLimit);
  54591. if (intensity < 0) {
  54592. return false;
  54593. }
  54594. if (intensity > 1.0) {
  54595. intensity = 1.0;
  54596. }
  54597. // Position
  54598. var centerX = globalViewport.x + globalViewport.width / 2;
  54599. var centerY = globalViewport.y + globalViewport.height / 2;
  54600. var distX = centerX - this._positionX;
  54601. var distY = centerY - this._positionY;
  54602. // Effects
  54603. engine.enableEffect(this._effect);
  54604. engine.setState(false);
  54605. engine.setDepthBuffer(false);
  54606. // VBOs
  54607. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54608. // Flares
  54609. for (var index = 0; index < this.lensFlares.length; index++) {
  54610. var flare = this.lensFlares[index];
  54611. engine.setAlphaMode(flare.alphaMode);
  54612. var x = centerX - (distX * flare.position);
  54613. var y = centerY - (distY * flare.position);
  54614. var cw = flare.size;
  54615. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  54616. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  54617. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  54618. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  54619. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  54620. // Texture
  54621. this._effect.setTexture("textureSampler", flare.texture);
  54622. // Color
  54623. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  54624. // Draw order
  54625. engine.draw(true, 0, 6);
  54626. }
  54627. engine.setDepthBuffer(true);
  54628. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54629. return true;
  54630. };
  54631. LensFlareSystem.prototype.dispose = function () {
  54632. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54633. if (vertexBuffer) {
  54634. vertexBuffer.dispose();
  54635. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54636. }
  54637. if (this._indexBuffer) {
  54638. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54639. this._indexBuffer = null;
  54640. }
  54641. while (this.lensFlares.length) {
  54642. this.lensFlares[0].dispose();
  54643. }
  54644. // Remove from scene
  54645. var index = this._scene.lensFlareSystems.indexOf(this);
  54646. this._scene.lensFlareSystems.splice(index, 1);
  54647. };
  54648. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  54649. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  54650. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  54651. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  54652. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  54653. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  54654. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  54655. var parsedFlare = parsedLensFlareSystem.flares[index];
  54656. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  54657. }
  54658. return lensFlareSystem;
  54659. };
  54660. LensFlareSystem.prototype.serialize = function () {
  54661. var serializationObject = {};
  54662. serializationObject.id = this.id;
  54663. serializationObject.name = this.name;
  54664. serializationObject.emitterId = this.getEmitter().id;
  54665. serializationObject.borderLimit = this.borderLimit;
  54666. serializationObject.flares = [];
  54667. for (var index = 0; index < this.lensFlares.length; index++) {
  54668. var flare = this.lensFlares[index];
  54669. serializationObject.flares.push({
  54670. size: flare.size,
  54671. position: flare.position,
  54672. color: flare.color.asArray(),
  54673. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  54674. });
  54675. }
  54676. return serializationObject;
  54677. };
  54678. return LensFlareSystem;
  54679. })();
  54680. BABYLON.LensFlareSystem = LensFlareSystem;
  54681. })(BABYLON || (BABYLON = {}));
  54682. var BABYLON;
  54683. (function (BABYLON) {
  54684. // We're mainly based on the logic defined into the FreeCamera code
  54685. var DeviceOrientationCamera = (function (_super) {
  54686. __extends(DeviceOrientationCamera, _super);
  54687. function DeviceOrientationCamera(name, position, scene) {
  54688. _super.call(this, name, position, scene);
  54689. this.inputs.addDeviceOrientation();
  54690. }
  54691. DeviceOrientationCamera.prototype.getTypeName = function () {
  54692. return "DeviceOrientationCamera";
  54693. };
  54694. DeviceOrientationCamera.prototype._checkInputs = function () {
  54695. _super.prototype._checkInputs.call(this);
  54696. if (this._initialQuaternion) {
  54697. this._quaternionCache.copyFrom(this.rotationQuaternion);
  54698. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  54699. }
  54700. };
  54701. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  54702. var _this = this;
  54703. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  54704. //can only work if this camera has a rotation quaternion already.
  54705. if (!this.rotationQuaternion)
  54706. return;
  54707. if (!this._initialQuaternion) {
  54708. this._initialQuaternion = new BABYLON.Quaternion();
  54709. }
  54710. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  54711. ['x', 'y', 'z'].forEach(function (axisName) {
  54712. if (!axis[axisName]) {
  54713. _this._initialQuaternion[axisName] = 0;
  54714. }
  54715. else {
  54716. _this._initialQuaternion[axisName] *= -1;
  54717. }
  54718. });
  54719. this._initialQuaternion.normalize();
  54720. };
  54721. return DeviceOrientationCamera;
  54722. })(BABYLON.FreeCamera);
  54723. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  54724. })(BABYLON || (BABYLON = {}));
  54725. var BABYLON;
  54726. (function (BABYLON) {
  54727. var VRDeviceOrientationFreeCamera = (function (_super) {
  54728. __extends(VRDeviceOrientationFreeCamera, _super);
  54729. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  54730. if (compensateDistortion === void 0) { compensateDistortion = true; }
  54731. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  54732. _super.call(this, name, position, scene);
  54733. vrCameraMetrics.compensateDistortion = compensateDistortion;
  54734. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  54735. }
  54736. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  54737. return "VRDeviceOrientationFreeCamera";
  54738. };
  54739. return VRDeviceOrientationFreeCamera;
  54740. })(BABYLON.DeviceOrientationCamera);
  54741. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  54742. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  54743. __extends(VRDeviceOrientationArcRotateCamera, _super);
  54744. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  54745. if (compensateDistortion === void 0) { compensateDistortion = true; }
  54746. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  54747. _super.call(this, name, alpha, beta, radius, target, scene);
  54748. vrCameraMetrics.compensateDistortion = compensateDistortion;
  54749. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  54750. this.inputs.addVRDeviceOrientation();
  54751. }
  54752. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  54753. return "VRDeviceOrientationArcRotateCamera";
  54754. };
  54755. return VRDeviceOrientationArcRotateCamera;
  54756. })(BABYLON.ArcRotateCamera);
  54757. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  54758. })(BABYLON || (BABYLON = {}));
  54759. var BABYLON;
  54760. (function (BABYLON) {
  54761. // We're mainly based on the logic defined into the FreeCamera code
  54762. var UniversalCamera = (function (_super) {
  54763. __extends(UniversalCamera, _super);
  54764. //-- end properties for backward compatibility for inputs
  54765. function UniversalCamera(name, position, scene) {
  54766. _super.call(this, name, position, scene);
  54767. this.inputs.addGamepad();
  54768. }
  54769. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  54770. //-- Begin properties for backward compatibility for inputs
  54771. get: function () {
  54772. var gamepad = this.inputs.attached["gamepad"];
  54773. if (gamepad)
  54774. return gamepad.gamepadAngularSensibility;
  54775. },
  54776. set: function (value) {
  54777. var gamepad = this.inputs.attached["gamepad"];
  54778. if (gamepad)
  54779. gamepad.gamepadAngularSensibility = value;
  54780. },
  54781. enumerable: true,
  54782. configurable: true
  54783. });
  54784. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  54785. get: function () {
  54786. var gamepad = this.inputs.attached["gamepad"];
  54787. if (gamepad)
  54788. return gamepad.gamepadMoveSensibility;
  54789. },
  54790. set: function (value) {
  54791. var gamepad = this.inputs.attached["gamepad"];
  54792. if (gamepad)
  54793. gamepad.gamepadMoveSensibility = value;
  54794. },
  54795. enumerable: true,
  54796. configurable: true
  54797. });
  54798. UniversalCamera.prototype.getTypeName = function () {
  54799. return "UniversalCamera";
  54800. };
  54801. return UniversalCamera;
  54802. })(BABYLON.TouchCamera);
  54803. BABYLON.UniversalCamera = UniversalCamera;
  54804. })(BABYLON || (BABYLON = {}));
  54805. var BABYLON;
  54806. (function (BABYLON) {
  54807. var Gamepads = (function () {
  54808. function Gamepads(ongamedpadconnected) {
  54809. var _this = this;
  54810. this.babylonGamepads = [];
  54811. this.oneGamepadConnected = false;
  54812. this.isMonitoring = false;
  54813. this.gamepadEventSupported = 'GamepadEvent' in window;
  54814. this.gamepadSupportAvailable = (navigator.getGamepads ||
  54815. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  54816. this._callbackGamepadConnected = ongamedpadconnected;
  54817. if (this.gamepadSupportAvailable) {
  54818. // Checking if the gamepad connected event is supported (like in Firefox)
  54819. if (this.gamepadEventSupported) {
  54820. this._onGamepadConnectedEvent = function (evt) {
  54821. _this._onGamepadConnected(evt);
  54822. };
  54823. this._onGamepadDisonnectedEvent = function (evt) {
  54824. _this._onGamepadDisconnected(evt);
  54825. };
  54826. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54827. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  54828. }
  54829. else {
  54830. this._startMonitoringGamepads();
  54831. }
  54832. }
  54833. }
  54834. Gamepads.prototype.dispose = function () {
  54835. if (Gamepads.gamepadDOMInfo) {
  54836. document.body.removeChild(Gamepads.gamepadDOMInfo);
  54837. }
  54838. if (this._onGamepadConnectedEvent) {
  54839. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54840. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  54841. this._onGamepadConnectedEvent = null;
  54842. this._onGamepadDisonnectedEvent = null;
  54843. }
  54844. };
  54845. Gamepads.prototype._onGamepadConnected = function (evt) {
  54846. var newGamepad = this._addNewGamepad(evt.gamepad);
  54847. if (this._callbackGamepadConnected)
  54848. this._callbackGamepadConnected(newGamepad);
  54849. this._startMonitoringGamepads();
  54850. };
  54851. Gamepads.prototype._addNewGamepad = function (gamepad) {
  54852. if (!this.oneGamepadConnected) {
  54853. this.oneGamepadConnected = true;
  54854. if (Gamepads.gamepadDOMInfo) {
  54855. document.body.removeChild(Gamepads.gamepadDOMInfo);
  54856. Gamepads.gamepadDOMInfo = null;
  54857. }
  54858. }
  54859. var newGamepad;
  54860. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54861. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  54862. }
  54863. else {
  54864. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  54865. }
  54866. this.babylonGamepads.push(newGamepad);
  54867. return newGamepad;
  54868. };
  54869. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  54870. // Remove the gamepad from the list of gamepads to monitor.
  54871. for (var i in this.babylonGamepads) {
  54872. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  54873. this.babylonGamepads.splice(+i, 1);
  54874. break;
  54875. }
  54876. }
  54877. // If no gamepads are left, stop the polling loop.
  54878. if (this.babylonGamepads.length == 0) {
  54879. this._stopMonitoringGamepads();
  54880. }
  54881. };
  54882. Gamepads.prototype._startMonitoringGamepads = function () {
  54883. if (!this.isMonitoring) {
  54884. this.isMonitoring = true;
  54885. this._checkGamepadsStatus();
  54886. }
  54887. };
  54888. Gamepads.prototype._stopMonitoringGamepads = function () {
  54889. this.isMonitoring = false;
  54890. };
  54891. Gamepads.prototype._checkGamepadsStatus = function () {
  54892. var _this = this;
  54893. // updating gamepad objects
  54894. this._updateGamepadObjects();
  54895. for (var i in this.babylonGamepads) {
  54896. this.babylonGamepads[i].update();
  54897. }
  54898. if (this.isMonitoring) {
  54899. if (window.requestAnimationFrame) {
  54900. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54901. }
  54902. else if (window.mozRequestAnimationFrame) {
  54903. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54904. }
  54905. else if (window.webkitRequestAnimationFrame) {
  54906. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54907. }
  54908. }
  54909. };
  54910. // This function is called only on Chrome, which does not yet support
  54911. // connection/disconnection events, but requires you to monitor
  54912. // an array for changes.
  54913. Gamepads.prototype._updateGamepadObjects = function () {
  54914. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54915. for (var i = 0; i < gamepads.length; i++) {
  54916. if (gamepads[i]) {
  54917. if (!(gamepads[i].index in this.babylonGamepads)) {
  54918. var newGamepad = this._addNewGamepad(gamepads[i]);
  54919. if (this._callbackGamepadConnected) {
  54920. this._callbackGamepadConnected(newGamepad);
  54921. }
  54922. }
  54923. else {
  54924. this.babylonGamepads[i].browserGamepad = gamepads[i];
  54925. }
  54926. }
  54927. }
  54928. };
  54929. return Gamepads;
  54930. })();
  54931. BABYLON.Gamepads = Gamepads;
  54932. var StickValues = (function () {
  54933. function StickValues(x, y) {
  54934. this.x = x;
  54935. this.y = y;
  54936. }
  54937. return StickValues;
  54938. })();
  54939. BABYLON.StickValues = StickValues;
  54940. var Gamepad = (function () {
  54941. function Gamepad(id, index, browserGamepad) {
  54942. this.id = id;
  54943. this.index = index;
  54944. this.browserGamepad = browserGamepad;
  54945. if (this.browserGamepad.axes.length >= 2) {
  54946. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  54947. }
  54948. if (this.browserGamepad.axes.length >= 4) {
  54949. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  54950. }
  54951. }
  54952. Gamepad.prototype.onleftstickchanged = function (callback) {
  54953. this._onleftstickchanged = callback;
  54954. };
  54955. Gamepad.prototype.onrightstickchanged = function (callback) {
  54956. this._onrightstickchanged = callback;
  54957. };
  54958. Object.defineProperty(Gamepad.prototype, "leftStick", {
  54959. get: function () {
  54960. return this._leftStick;
  54961. },
  54962. set: function (newValues) {
  54963. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  54964. this._onleftstickchanged(newValues);
  54965. }
  54966. this._leftStick = newValues;
  54967. },
  54968. enumerable: true,
  54969. configurable: true
  54970. });
  54971. Object.defineProperty(Gamepad.prototype, "rightStick", {
  54972. get: function () {
  54973. return this._rightStick;
  54974. },
  54975. set: function (newValues) {
  54976. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  54977. this._onrightstickchanged(newValues);
  54978. }
  54979. this._rightStick = newValues;
  54980. },
  54981. enumerable: true,
  54982. configurable: true
  54983. });
  54984. Gamepad.prototype.update = function () {
  54985. if (this._leftStick) {
  54986. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  54987. }
  54988. if (this._rightStick) {
  54989. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  54990. }
  54991. };
  54992. return Gamepad;
  54993. })();
  54994. BABYLON.Gamepad = Gamepad;
  54995. var GenericPad = (function (_super) {
  54996. __extends(GenericPad, _super);
  54997. function GenericPad(id, index, gamepad) {
  54998. _super.call(this, id, index, gamepad);
  54999. this.id = id;
  55000. this.index = index;
  55001. this.gamepad = gamepad;
  55002. this._buttons = new Array(gamepad.buttons.length);
  55003. }
  55004. GenericPad.prototype.onbuttondown = function (callback) {
  55005. this._onbuttondown = callback;
  55006. };
  55007. GenericPad.prototype.onbuttonup = function (callback) {
  55008. this._onbuttonup = callback;
  55009. };
  55010. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55011. if (newValue !== currentValue) {
  55012. if (this._onbuttondown && newValue === 1) {
  55013. this._onbuttondown(buttonIndex);
  55014. }
  55015. if (this._onbuttonup && newValue === 0) {
  55016. this._onbuttonup(buttonIndex);
  55017. }
  55018. }
  55019. return newValue;
  55020. };
  55021. GenericPad.prototype.update = function () {
  55022. _super.prototype.update.call(this);
  55023. for (var index = 0; index < this._buttons.length; index++) {
  55024. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  55025. }
  55026. };
  55027. return GenericPad;
  55028. })(Gamepad);
  55029. BABYLON.GenericPad = GenericPad;
  55030. (function (Xbox360Button) {
  55031. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55032. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55033. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55034. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55035. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55036. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55037. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55038. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55039. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55040. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55041. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55042. var Xbox360Button = BABYLON.Xbox360Button;
  55043. (function (Xbox360Dpad) {
  55044. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55045. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55046. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55047. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55048. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55049. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  55050. var Xbox360Pad = (function (_super) {
  55051. __extends(Xbox360Pad, _super);
  55052. function Xbox360Pad() {
  55053. _super.apply(this, arguments);
  55054. this._leftTrigger = 0;
  55055. this._rightTrigger = 0;
  55056. this._buttonA = 0;
  55057. this._buttonB = 0;
  55058. this._buttonX = 0;
  55059. this._buttonY = 0;
  55060. this._buttonBack = 0;
  55061. this._buttonStart = 0;
  55062. this._buttonLB = 0;
  55063. this._buttonRB = 0;
  55064. this._buttonLeftStick = 0;
  55065. this._buttonRightStick = 0;
  55066. this._dPadUp = 0;
  55067. this._dPadDown = 0;
  55068. this._dPadLeft = 0;
  55069. this._dPadRight = 0;
  55070. }
  55071. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55072. this._onlefttriggerchanged = callback;
  55073. };
  55074. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55075. this._onrighttriggerchanged = callback;
  55076. };
  55077. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55078. get: function () {
  55079. return this._leftTrigger;
  55080. },
  55081. set: function (newValue) {
  55082. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55083. this._onlefttriggerchanged(newValue);
  55084. }
  55085. this._leftTrigger = newValue;
  55086. },
  55087. enumerable: true,
  55088. configurable: true
  55089. });
  55090. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55091. get: function () {
  55092. return this._rightTrigger;
  55093. },
  55094. set: function (newValue) {
  55095. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55096. this._onrighttriggerchanged(newValue);
  55097. }
  55098. this._rightTrigger = newValue;
  55099. },
  55100. enumerable: true,
  55101. configurable: true
  55102. });
  55103. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55104. this._onbuttondown = callback;
  55105. };
  55106. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55107. this._onbuttonup = callback;
  55108. };
  55109. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55110. this._ondpaddown = callback;
  55111. };
  55112. Xbox360Pad.prototype.ondpadup = function (callback) {
  55113. this._ondpadup = callback;
  55114. };
  55115. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55116. if (newValue !== currentValue) {
  55117. if (this._onbuttondown && newValue === 1) {
  55118. this._onbuttondown(buttonType);
  55119. }
  55120. if (this._onbuttonup && newValue === 0) {
  55121. this._onbuttonup(buttonType);
  55122. }
  55123. }
  55124. return newValue;
  55125. };
  55126. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55127. if (newValue !== currentValue) {
  55128. if (this._ondpaddown && newValue === 1) {
  55129. this._ondpaddown(buttonType);
  55130. }
  55131. if (this._ondpadup && newValue === 0) {
  55132. this._ondpadup(buttonType);
  55133. }
  55134. }
  55135. return newValue;
  55136. };
  55137. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55138. get: function () {
  55139. return this._buttonA;
  55140. },
  55141. set: function (value) {
  55142. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55143. },
  55144. enumerable: true,
  55145. configurable: true
  55146. });
  55147. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55148. get: function () {
  55149. return this._buttonB;
  55150. },
  55151. set: function (value) {
  55152. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55153. },
  55154. enumerable: true,
  55155. configurable: true
  55156. });
  55157. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55158. get: function () {
  55159. return this._buttonX;
  55160. },
  55161. set: function (value) {
  55162. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55163. },
  55164. enumerable: true,
  55165. configurable: true
  55166. });
  55167. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55168. get: function () {
  55169. return this._buttonY;
  55170. },
  55171. set: function (value) {
  55172. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55173. },
  55174. enumerable: true,
  55175. configurable: true
  55176. });
  55177. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55178. get: function () {
  55179. return this._buttonStart;
  55180. },
  55181. set: function (value) {
  55182. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55183. },
  55184. enumerable: true,
  55185. configurable: true
  55186. });
  55187. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55188. get: function () {
  55189. return this._buttonBack;
  55190. },
  55191. set: function (value) {
  55192. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55193. },
  55194. enumerable: true,
  55195. configurable: true
  55196. });
  55197. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55198. get: function () {
  55199. return this._buttonLB;
  55200. },
  55201. set: function (value) {
  55202. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55203. },
  55204. enumerable: true,
  55205. configurable: true
  55206. });
  55207. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55208. get: function () {
  55209. return this._buttonRB;
  55210. },
  55211. set: function (value) {
  55212. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55213. },
  55214. enumerable: true,
  55215. configurable: true
  55216. });
  55217. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55218. get: function () {
  55219. return this._buttonLeftStick;
  55220. },
  55221. set: function (value) {
  55222. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55223. },
  55224. enumerable: true,
  55225. configurable: true
  55226. });
  55227. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55228. get: function () {
  55229. return this._buttonRightStick;
  55230. },
  55231. set: function (value) {
  55232. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55233. },
  55234. enumerable: true,
  55235. configurable: true
  55236. });
  55237. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55238. get: function () {
  55239. return this._dPadUp;
  55240. },
  55241. set: function (value) {
  55242. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55243. },
  55244. enumerable: true,
  55245. configurable: true
  55246. });
  55247. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55248. get: function () {
  55249. return this._dPadDown;
  55250. },
  55251. set: function (value) {
  55252. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55253. },
  55254. enumerable: true,
  55255. configurable: true
  55256. });
  55257. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55258. get: function () {
  55259. return this._dPadLeft;
  55260. },
  55261. set: function (value) {
  55262. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55263. },
  55264. enumerable: true,
  55265. configurable: true
  55266. });
  55267. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55268. get: function () {
  55269. return this._dPadRight;
  55270. },
  55271. set: function (value) {
  55272. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55273. },
  55274. enumerable: true,
  55275. configurable: true
  55276. });
  55277. Xbox360Pad.prototype.update = function () {
  55278. _super.prototype.update.call(this);
  55279. this.buttonA = this.browserGamepad.buttons[0].value;
  55280. this.buttonB = this.browserGamepad.buttons[1].value;
  55281. this.buttonX = this.browserGamepad.buttons[2].value;
  55282. this.buttonY = this.browserGamepad.buttons[3].value;
  55283. this.buttonLB = this.browserGamepad.buttons[4].value;
  55284. this.buttonRB = this.browserGamepad.buttons[5].value;
  55285. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55286. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55287. this.buttonBack = this.browserGamepad.buttons[8].value;
  55288. this.buttonStart = this.browserGamepad.buttons[9].value;
  55289. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55290. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55291. this.dPadUp = this.browserGamepad.buttons[12].value;
  55292. this.dPadDown = this.browserGamepad.buttons[13].value;
  55293. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55294. this.dPadRight = this.browserGamepad.buttons[15].value;
  55295. };
  55296. return Xbox360Pad;
  55297. })(Gamepad);
  55298. BABYLON.Xbox360Pad = Xbox360Pad;
  55299. })(BABYLON || (BABYLON = {}));
  55300. var BABYLON;
  55301. (function (BABYLON) {
  55302. // We're mainly based on the logic defined into the FreeCamera code
  55303. var GamepadCamera = (function (_super) {
  55304. __extends(GamepadCamera, _super);
  55305. //-- end properties for backward compatibility for inputs
  55306. function GamepadCamera(name, position, scene) {
  55307. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  55308. _super.call(this, name, position, scene);
  55309. }
  55310. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  55311. //-- Begin properties for backward compatibility for inputs
  55312. get: function () {
  55313. var gamepad = this.inputs.attached["gamepad"];
  55314. if (gamepad)
  55315. return gamepad.gamepadAngularSensibility;
  55316. },
  55317. set: function (value) {
  55318. var gamepad = this.inputs.attached["gamepad"];
  55319. if (gamepad)
  55320. gamepad.gamepadAngularSensibility = value;
  55321. },
  55322. enumerable: true,
  55323. configurable: true
  55324. });
  55325. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  55326. get: function () {
  55327. var gamepad = this.inputs.attached["gamepad"];
  55328. if (gamepad)
  55329. return gamepad.gamepadMoveSensibility;
  55330. },
  55331. set: function (value) {
  55332. var gamepad = this.inputs.attached["gamepad"];
  55333. if (gamepad)
  55334. gamepad.gamepadMoveSensibility = value;
  55335. },
  55336. enumerable: true,
  55337. configurable: true
  55338. });
  55339. GamepadCamera.prototype.getTypeName = function () {
  55340. return "GamepadCamera";
  55341. };
  55342. return GamepadCamera;
  55343. })(BABYLON.UniversalCamera);
  55344. BABYLON.GamepadCamera = GamepadCamera;
  55345. })(BABYLON || (BABYLON = {}));
  55346. var BABYLON;
  55347. (function (BABYLON) {
  55348. var Analyser = (function () {
  55349. function Analyser(scene) {
  55350. this.SMOOTHING = 0.75;
  55351. this.FFT_SIZE = 512;
  55352. this.BARGRAPHAMPLITUDE = 256;
  55353. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55354. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55355. this._scene = scene;
  55356. this._audioEngine = BABYLON.Engine.audioEngine;
  55357. if (this._audioEngine.canUseWebAudio) {
  55358. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55359. this._webAudioAnalyser.minDecibels = -140;
  55360. this._webAudioAnalyser.maxDecibels = 0;
  55361. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55362. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55363. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55364. }
  55365. }
  55366. Analyser.prototype.getFrequencyBinCount = function () {
  55367. if (this._audioEngine.canUseWebAudio) {
  55368. return this._webAudioAnalyser.frequencyBinCount;
  55369. }
  55370. else {
  55371. return 0;
  55372. }
  55373. };
  55374. Analyser.prototype.getByteFrequencyData = function () {
  55375. if (this._audioEngine.canUseWebAudio) {
  55376. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55377. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55378. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55379. }
  55380. return this._byteFreqs;
  55381. };
  55382. Analyser.prototype.getByteTimeDomainData = function () {
  55383. if (this._audioEngine.canUseWebAudio) {
  55384. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55385. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55386. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55387. }
  55388. return this._byteTime;
  55389. };
  55390. Analyser.prototype.getFloatFrequencyData = function () {
  55391. if (this._audioEngine.canUseWebAudio) {
  55392. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55393. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55394. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  55395. }
  55396. return this._floatFreqs;
  55397. };
  55398. Analyser.prototype.drawDebugCanvas = function () {
  55399. var _this = this;
  55400. if (this._audioEngine.canUseWebAudio) {
  55401. if (!this._debugCanvas) {
  55402. this._debugCanvas = document.createElement("canvas");
  55403. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  55404. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  55405. this._debugCanvas.style.position = "absolute";
  55406. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  55407. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  55408. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  55409. document.body.appendChild(this._debugCanvas);
  55410. this._registerFunc = function () {
  55411. _this.drawDebugCanvas();
  55412. };
  55413. this._scene.registerBeforeRender(this._registerFunc);
  55414. }
  55415. if (this._registerFunc) {
  55416. var workingArray = this.getByteFrequencyData();
  55417. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  55418. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  55419. // Draw the frequency domain chart.
  55420. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  55421. var value = workingArray[i];
  55422. var percent = value / this.BARGRAPHAMPLITUDE;
  55423. var height = this.DEBUGCANVASSIZE.height * percent;
  55424. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  55425. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  55426. var hue = i / this.getFrequencyBinCount() * 360;
  55427. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  55428. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  55429. }
  55430. }
  55431. }
  55432. };
  55433. Analyser.prototype.stopDebugCanvas = function () {
  55434. if (this._debugCanvas) {
  55435. this._scene.unregisterBeforeRender(this._registerFunc);
  55436. this._registerFunc = null;
  55437. document.body.removeChild(this._debugCanvas);
  55438. this._debugCanvas = null;
  55439. this._debugCanvasContext = null;
  55440. }
  55441. };
  55442. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  55443. if (this._audioEngine.canUseWebAudio) {
  55444. inputAudioNode.connect(this._webAudioAnalyser);
  55445. this._webAudioAnalyser.connect(outputAudioNode);
  55446. }
  55447. };
  55448. Analyser.prototype.dispose = function () {
  55449. if (this._audioEngine.canUseWebAudio) {
  55450. this._webAudioAnalyser.disconnect();
  55451. }
  55452. };
  55453. return Analyser;
  55454. })();
  55455. BABYLON.Analyser = Analyser;
  55456. })(BABYLON || (BABYLON = {}));
  55457. var BABYLON;
  55458. (function (BABYLON) {
  55459. var DepthRenderer = (function () {
  55460. function DepthRenderer(scene, type) {
  55461. var _this = this;
  55462. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  55463. this._viewMatrix = BABYLON.Matrix.Zero();
  55464. this._projectionMatrix = BABYLON.Matrix.Zero();
  55465. this._transformMatrix = BABYLON.Matrix.Zero();
  55466. this._worldViewProjection = BABYLON.Matrix.Zero();
  55467. this._scene = scene;
  55468. var engine = scene.getEngine();
  55469. // Render target
  55470. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  55471. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55472. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55473. this._depthMap.refreshRate = 1;
  55474. this._depthMap.renderParticles = false;
  55475. this._depthMap.renderList = null;
  55476. // set default depth value to 1.0 (far away)
  55477. this._depthMap.onClearObservable.add(function (engine) {
  55478. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55479. });
  55480. // Custom render function
  55481. var renderSubMesh = function (subMesh) {
  55482. var mesh = subMesh.getRenderingMesh();
  55483. var scene = _this._scene;
  55484. var engine = scene.getEngine();
  55485. // Culling
  55486. engine.setState(subMesh.getMaterial().backFaceCulling);
  55487. // Managing instances
  55488. var batch = mesh._getInstancesRenderList(subMesh._id);
  55489. if (batch.mustReturn) {
  55490. return;
  55491. }
  55492. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  55493. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55494. engine.enableEffect(_this._effect);
  55495. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  55496. var material = subMesh.getMaterial();
  55497. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  55498. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  55499. // Alpha test
  55500. if (material && material.needAlphaTesting()) {
  55501. var alphaTexture = material.getAlphaTestTexture();
  55502. _this._effect.setTexture("diffuseSampler", alphaTexture);
  55503. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55504. }
  55505. // Bones
  55506. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55507. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55508. }
  55509. // Draw
  55510. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55511. }
  55512. };
  55513. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  55514. var index;
  55515. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55516. renderSubMesh(opaqueSubMeshes.data[index]);
  55517. }
  55518. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55519. renderSubMesh(alphaTestSubMeshes.data[index]);
  55520. }
  55521. };
  55522. }
  55523. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  55524. var material = subMesh.getMaterial();
  55525. if (material.disableDepthWrite) {
  55526. return false;
  55527. }
  55528. var defines = [];
  55529. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55530. var mesh = subMesh.getMesh();
  55531. var scene = mesh.getScene();
  55532. // Alpha test
  55533. if (material && material.needAlphaTesting()) {
  55534. defines.push("#define ALPHATEST");
  55535. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55536. attribs.push(BABYLON.VertexBuffer.UVKind);
  55537. defines.push("#define UV1");
  55538. }
  55539. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55540. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55541. defines.push("#define UV2");
  55542. }
  55543. }
  55544. // Bones
  55545. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55546. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55547. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55548. if (mesh.numBoneInfluencers > 4) {
  55549. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55550. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55551. }
  55552. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55553. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55554. }
  55555. else {
  55556. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55557. }
  55558. // Instances
  55559. if (useInstances) {
  55560. defines.push("#define INSTANCES");
  55561. attribs.push("world0");
  55562. attribs.push("world1");
  55563. attribs.push("world2");
  55564. attribs.push("world3");
  55565. }
  55566. // Get correct effect
  55567. var join = defines.join("\n");
  55568. if (this._cachedDefines !== join) {
  55569. this._cachedDefines = join;
  55570. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  55571. }
  55572. return this._effect.isReady();
  55573. };
  55574. DepthRenderer.prototype.getDepthMap = function () {
  55575. return this._depthMap;
  55576. };
  55577. // Methods
  55578. DepthRenderer.prototype.dispose = function () {
  55579. this._depthMap.dispose();
  55580. };
  55581. return DepthRenderer;
  55582. })();
  55583. BABYLON.DepthRenderer = DepthRenderer;
  55584. })(BABYLON || (BABYLON = {}));
  55585. var BABYLON;
  55586. (function (BABYLON) {
  55587. var SSAORenderingPipeline = (function (_super) {
  55588. __extends(SSAORenderingPipeline, _super);
  55589. /**
  55590. * @constructor
  55591. * @param {string} name - The rendering pipeline name
  55592. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55593. * @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 }
  55594. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55595. */
  55596. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  55597. var _this = this;
  55598. _super.call(this, scene.getEngine(), name);
  55599. // Members
  55600. /**
  55601. * The PassPostProcess id in the pipeline that contains the original scene color
  55602. * @type {string}
  55603. */
  55604. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  55605. /**
  55606. * The SSAO PostProcess id in the pipeline
  55607. * @type {string}
  55608. */
  55609. this.SSAORenderEffect = "SSAORenderEffect";
  55610. /**
  55611. * The horizontal blur PostProcess id in the pipeline
  55612. * @type {string}
  55613. */
  55614. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  55615. /**
  55616. * The vertical blur PostProcess id in the pipeline
  55617. * @type {string}
  55618. */
  55619. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  55620. /**
  55621. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  55622. * @type {string}
  55623. */
  55624. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  55625. /**
  55626. * The output strength of the SSAO post-process. Default value is 1.0.
  55627. * @type {number}
  55628. */
  55629. this.totalStrength = 1.0;
  55630. /**
  55631. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  55632. * @type {number}
  55633. */
  55634. this.radius = 0.0001;
  55635. /**
  55636. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  55637. * Must not be equal to fallOff and superior to fallOff.
  55638. * Default value is 0.975
  55639. * @type {number}
  55640. */
  55641. this.area = 0.0075;
  55642. /**
  55643. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  55644. * Must not be equal to area and inferior to area.
  55645. * Default value is 0.0
  55646. * @type {number}
  55647. */
  55648. this.fallOff = 0.000001;
  55649. /**
  55650. * The base color of the SSAO post-process
  55651. * The final result is "base + ssao" between [0, 1]
  55652. * @type {number}
  55653. */
  55654. this.base = 0.5;
  55655. this._firstUpdate = true;
  55656. this._scene = scene;
  55657. // Set up assets
  55658. this._createRandomTexture();
  55659. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55660. var ssaoRatio = ratio.ssaoRatio || ratio;
  55661. var combineRatio = ratio.combineRatio || ratio;
  55662. this._ratio = {
  55663. ssaoRatio: ssaoRatio,
  55664. combineRatio: combineRatio
  55665. };
  55666. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55667. this._createSSAOPostProcess(ssaoRatio);
  55668. this._createBlurPostProcess(ssaoRatio);
  55669. this._createSSAOCombinePostProcess(combineRatio);
  55670. // Set up pipeline
  55671. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  55672. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  55673. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  55674. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  55675. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  55676. // Finish
  55677. scene.postProcessRenderPipelineManager.addPipeline(this);
  55678. if (cameras)
  55679. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55680. }
  55681. // Public Methods
  55682. /**
  55683. * Returns the horizontal blur PostProcess
  55684. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  55685. */
  55686. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  55687. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  55688. return null;
  55689. };
  55690. /**
  55691. * Returns the vertical blur PostProcess
  55692. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  55693. */
  55694. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  55695. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  55696. return null;
  55697. };
  55698. /**
  55699. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  55700. */
  55701. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55702. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55703. for (var i = 0; i < this._scene.cameras.length; i++) {
  55704. var camera = this._scene.cameras[i];
  55705. this._originalColorPostProcess.dispose(camera);
  55706. this._ssaoPostProcess.dispose(camera);
  55707. this._blurHPostProcess.dispose(camera);
  55708. this._blurVPostProcess.dispose(camera);
  55709. this._ssaoCombinePostProcess.dispose(camera);
  55710. }
  55711. this._randomTexture.dispose();
  55712. if (disableDepthRender)
  55713. this._scene.disableDepthRenderer();
  55714. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55715. };
  55716. // Private Methods
  55717. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  55718. var _this = this;
  55719. /*
  55720. var samplerOffsets = [
  55721. -8.0, -6.0, -4.0, -2.0,
  55722. 0.0,
  55723. 2.0, 4.0, 6.0, 8.0
  55724. ];
  55725. */
  55726. var samples = 16;
  55727. var samplerOffsets = [];
  55728. for (var i = -8; i < 8; i++) {
  55729. samplerOffsets.push(i * 2);
  55730. }
  55731. 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");
  55732. this._blurHPostProcess.onApply = function (effect) {
  55733. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  55734. effect.setTexture("depthSampler", _this._depthTexture);
  55735. if (_this._firstUpdate) {
  55736. effect.setArray("samplerOffsets", samplerOffsets);
  55737. }
  55738. };
  55739. 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");
  55740. this._blurVPostProcess.onApply = function (effect) {
  55741. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  55742. effect.setTexture("depthSampler", _this._depthTexture);
  55743. if (_this._firstUpdate) {
  55744. effect.setArray("samplerOffsets", samplerOffsets);
  55745. _this._firstUpdate = false;
  55746. }
  55747. };
  55748. };
  55749. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  55750. var _this = this;
  55751. var numSamples = 16;
  55752. var sampleSphere = [
  55753. 0.5381, 0.1856, -0.4319,
  55754. 0.1379, 0.2486, 0.4430,
  55755. 0.3371, 0.5679, -0.0057,
  55756. -0.6999, -0.0451, -0.0019,
  55757. 0.0689, -0.1598, -0.8547,
  55758. 0.0560, 0.0069, -0.1843,
  55759. -0.0146, 0.1402, 0.0762,
  55760. 0.0100, -0.1924, -0.0344,
  55761. -0.3577, -0.5301, -0.4358,
  55762. -0.3169, 0.1063, 0.0158,
  55763. 0.0103, -0.5869, 0.0046,
  55764. -0.0897, -0.4940, 0.3287,
  55765. 0.7119, -0.0154, -0.0918,
  55766. -0.0533, 0.0596, -0.5411,
  55767. 0.0352, -0.0631, 0.5460,
  55768. -0.4776, 0.2847, -0.0271
  55769. ];
  55770. var samplesFactor = 1.0 / numSamples;
  55771. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  55772. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  55773. "area", "fallOff", "base", "range", "viewport"
  55774. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  55775. var viewport = new BABYLON.Vector2(0, 0);
  55776. this._ssaoPostProcess.onApply = function (effect) {
  55777. if (_this._firstUpdate) {
  55778. effect.setArray3("sampleSphere", sampleSphere);
  55779. effect.setFloat("samplesFactor", samplesFactor);
  55780. effect.setFloat("randTextureTiles", 4.0);
  55781. }
  55782. effect.setFloat("totalStrength", _this.totalStrength);
  55783. effect.setFloat("radius", _this.radius);
  55784. effect.setFloat("area", _this.area);
  55785. effect.setFloat("fallOff", _this.fallOff);
  55786. effect.setFloat("base", _this.base);
  55787. effect.setTexture("textureSampler", _this._depthTexture);
  55788. effect.setTexture("randomSampler", _this._randomTexture);
  55789. };
  55790. };
  55791. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  55792. var _this = this;
  55793. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55794. this._ssaoCombinePostProcess.onApply = function (effect) {
  55795. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  55796. };
  55797. };
  55798. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  55799. var size = 512;
  55800. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55801. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55802. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55803. var context = this._randomTexture.getContext();
  55804. var rand = function (min, max) {
  55805. return Math.random() * (max - min) + min;
  55806. };
  55807. var randVector = BABYLON.Vector3.Zero();
  55808. for (var x = 0; x < size; x++) {
  55809. for (var y = 0; y < size; y++) {
  55810. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  55811. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  55812. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  55813. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  55814. context.fillRect(x, y, 1, 1);
  55815. }
  55816. }
  55817. this._randomTexture.update(false);
  55818. };
  55819. __decorate([
  55820. BABYLON.serialize()
  55821. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  55822. __decorate([
  55823. BABYLON.serialize()
  55824. ], SSAORenderingPipeline.prototype, "radius", void 0);
  55825. __decorate([
  55826. BABYLON.serialize()
  55827. ], SSAORenderingPipeline.prototype, "area", void 0);
  55828. __decorate([
  55829. BABYLON.serialize()
  55830. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  55831. __decorate([
  55832. BABYLON.serialize()
  55833. ], SSAORenderingPipeline.prototype, "base", void 0);
  55834. __decorate([
  55835. BABYLON.serialize()
  55836. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  55837. return SSAORenderingPipeline;
  55838. })(BABYLON.PostProcessRenderPipeline);
  55839. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  55840. })(BABYLON || (BABYLON = {}));
  55841. var BABYLON;
  55842. (function (BABYLON) {
  55843. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  55844. var VolumetricLightScatteringPostProcess = (function (_super) {
  55845. __extends(VolumetricLightScatteringPostProcess, _super);
  55846. /**
  55847. * @constructor
  55848. * @param {string} name - The post-process name
  55849. * @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)
  55850. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  55851. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  55852. * @param {number} samples - The post-process quality, default 100
  55853. * @param {number} samplingMode - The post-process filtering mode
  55854. * @param {BABYLON.Engine} engine - The babylon engine
  55855. * @param {boolean} reusable - If the post-process is reusable
  55856. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  55857. */
  55858. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  55859. var _this = this;
  55860. if (samples === void 0) { samples = 100; }
  55861. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55862. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  55863. this._screenCoordinates = BABYLON.Vector2.Zero();
  55864. /**
  55865. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  55866. * @type {Vector3}
  55867. */
  55868. this.customMeshPosition = BABYLON.Vector3.Zero();
  55869. /**
  55870. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  55871. * @type {boolean}
  55872. */
  55873. this.useCustomMeshPosition = false;
  55874. /**
  55875. * If the post-process should inverse the light scattering direction
  55876. * @type {boolean}
  55877. */
  55878. this.invert = true;
  55879. /**
  55880. * Array containing the excluded meshes not rendered in the internal pass
  55881. */
  55882. this.excludedMeshes = new Array();
  55883. /**
  55884. * Controls the overall intensity of the post-process
  55885. * @type {number}
  55886. */
  55887. this.exposure = 0.3;
  55888. /**
  55889. * Dissipates each sample's contribution in range [0, 1]
  55890. * @type {number}
  55891. */
  55892. this.decay = 0.96815;
  55893. /**
  55894. * Controls the overall intensity of each sample
  55895. * @type {number}
  55896. */
  55897. this.weight = 0.58767;
  55898. /**
  55899. * Controls the density of each sample
  55900. * @type {number}
  55901. */
  55902. this.density = 0.926;
  55903. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  55904. var engine = scene.getEngine();
  55905. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  55906. // Configure mesh
  55907. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  55908. // Configure
  55909. this._createPass(scene, ratio.passRatio || ratio);
  55910. this.onActivate = function (camera) {
  55911. if (!_this.isSupported) {
  55912. _this.dispose(camera);
  55913. }
  55914. _this.onActivate = null;
  55915. };
  55916. this.onApplyObservable.add(function (effect) {
  55917. _this._updateMeshScreenCoordinates(scene);
  55918. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  55919. effect.setFloat("exposure", _this.exposure);
  55920. effect.setFloat("decay", _this.decay);
  55921. effect.setFloat("weight", _this.weight);
  55922. effect.setFloat("density", _this.density);
  55923. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  55924. });
  55925. }
  55926. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  55927. get: function () {
  55928. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55929. return false;
  55930. },
  55931. set: function (useDiffuseColor) {
  55932. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55933. },
  55934. enumerable: true,
  55935. configurable: true
  55936. });
  55937. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  55938. var mesh = subMesh.getMesh();
  55939. // Render this.mesh as default
  55940. if (mesh === this.mesh) {
  55941. return mesh.material.isReady(mesh);
  55942. }
  55943. var defines = [];
  55944. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55945. var material = subMesh.getMaterial();
  55946. var needUV = false;
  55947. // Alpha test
  55948. if (material) {
  55949. if (material.needAlphaTesting()) {
  55950. defines.push("#define ALPHATEST");
  55951. }
  55952. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55953. attribs.push(BABYLON.VertexBuffer.UVKind);
  55954. defines.push("#define UV1");
  55955. }
  55956. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55957. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55958. defines.push("#define UV2");
  55959. }
  55960. }
  55961. // Bones
  55962. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55963. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55964. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55965. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55966. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55967. }
  55968. else {
  55969. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55970. }
  55971. // Instances
  55972. if (useInstances) {
  55973. defines.push("#define INSTANCES");
  55974. attribs.push("world0");
  55975. attribs.push("world1");
  55976. attribs.push("world2");
  55977. attribs.push("world3");
  55978. }
  55979. // Get correct effect
  55980. var join = defines.join("\n");
  55981. if (this._cachedDefines !== join) {
  55982. this._cachedDefines = join;
  55983. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  55984. }
  55985. return this._volumetricLightScatteringPass.isReady();
  55986. };
  55987. /**
  55988. * Sets the new light position for light scattering effect
  55989. * @param {BABYLON.Vector3} The new custom light position
  55990. */
  55991. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  55992. this.customMeshPosition = position;
  55993. };
  55994. /**
  55995. * Returns the light position for light scattering effect
  55996. * @return {BABYLON.Vector3} The custom light position
  55997. */
  55998. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  55999. return this.customMeshPosition;
  56000. };
  56001. /**
  56002. * Disposes the internal assets and detaches the post-process from the camera
  56003. */
  56004. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  56005. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  56006. if (rttIndex !== -1) {
  56007. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  56008. }
  56009. this._volumetricLightScatteringRTT.dispose();
  56010. _super.prototype.dispose.call(this, camera);
  56011. };
  56012. /**
  56013. * Returns the render target texture used by the post-process
  56014. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  56015. */
  56016. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  56017. return this._volumetricLightScatteringRTT;
  56018. };
  56019. // Private methods
  56020. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  56021. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  56022. return true;
  56023. }
  56024. return false;
  56025. };
  56026. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  56027. var _this = this;
  56028. var engine = scene.getEngine();
  56029. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56030. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56031. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56032. this._volumetricLightScatteringRTT.renderList = null;
  56033. this._volumetricLightScatteringRTT.renderParticles = false;
  56034. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  56035. // Custom render function for submeshes
  56036. var renderSubMesh = function (subMesh) {
  56037. var mesh = subMesh.getRenderingMesh();
  56038. if (_this._meshExcluded(mesh)) {
  56039. return;
  56040. }
  56041. var scene = mesh.getScene();
  56042. var engine = scene.getEngine();
  56043. // Culling
  56044. engine.setState(subMesh.getMaterial().backFaceCulling);
  56045. // Managing instances
  56046. var batch = mesh._getInstancesRenderList(subMesh._id);
  56047. if (batch.mustReturn) {
  56048. return;
  56049. }
  56050. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  56051. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  56052. var effect = _this._volumetricLightScatteringPass;
  56053. if (mesh === _this.mesh) {
  56054. effect = subMesh.getMaterial().getEffect();
  56055. }
  56056. engine.enableEffect(effect);
  56057. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  56058. if (mesh === _this.mesh) {
  56059. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  56060. }
  56061. else {
  56062. var material = subMesh.getMaterial();
  56063. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  56064. // Alpha test
  56065. if (material && material.needAlphaTesting()) {
  56066. var alphaTexture = material.getAlphaTestTexture();
  56067. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  56068. if (alphaTexture) {
  56069. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  56070. }
  56071. }
  56072. // Bones
  56073. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56074. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  56075. }
  56076. }
  56077. // Draw
  56078. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  56079. }
  56080. };
  56081. // Render target texture callbacks
  56082. var savedSceneClearColor;
  56083. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  56084. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  56085. savedSceneClearColor = scene.clearColor;
  56086. scene.clearColor = sceneClearColor;
  56087. });
  56088. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  56089. scene.clearColor = savedSceneClearColor;
  56090. });
  56091. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  56092. var engine = scene.getEngine();
  56093. var index;
  56094. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56095. renderSubMesh(opaqueSubMeshes.data[index]);
  56096. }
  56097. engine.setAlphaTesting(true);
  56098. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56099. renderSubMesh(alphaTestSubMeshes.data[index]);
  56100. }
  56101. engine.setAlphaTesting(false);
  56102. if (transparentSubMeshes.length) {
  56103. // Sort sub meshes
  56104. for (index = 0; index < transparentSubMeshes.length; index++) {
  56105. var submesh = transparentSubMeshes.data[index];
  56106. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  56107. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  56108. }
  56109. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  56110. sortedArray.sort(function (a, b) {
  56111. // Alpha index first
  56112. if (a._alphaIndex > b._alphaIndex) {
  56113. return 1;
  56114. }
  56115. if (a._alphaIndex < b._alphaIndex) {
  56116. return -1;
  56117. }
  56118. // Then distance to camera
  56119. if (a._distanceToCamera < b._distanceToCamera) {
  56120. return 1;
  56121. }
  56122. if (a._distanceToCamera > b._distanceToCamera) {
  56123. return -1;
  56124. }
  56125. return 0;
  56126. });
  56127. // Render sub meshes
  56128. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56129. for (index = 0; index < sortedArray.length; index++) {
  56130. renderSubMesh(sortedArray[index]);
  56131. }
  56132. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56133. }
  56134. };
  56135. };
  56136. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  56137. var transform = scene.getTransformMatrix();
  56138. var meshPosition;
  56139. if (this.useCustomMeshPosition) {
  56140. meshPosition = this.customMeshPosition;
  56141. }
  56142. else if (this.attachedNode) {
  56143. meshPosition = this.attachedNode.position;
  56144. }
  56145. else {
  56146. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  56147. }
  56148. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  56149. this._screenCoordinates.x = pos.x / this._viewPort.width;
  56150. this._screenCoordinates.y = pos.y / this._viewPort.height;
  56151. if (this.invert)
  56152. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  56153. };
  56154. // Static methods
  56155. /**
  56156. * Creates a default mesh for the Volumeric Light Scattering post-process
  56157. * @param {string} The mesh name
  56158. * @param {BABYLON.Scene} The scene where to create the mesh
  56159. * @return {BABYLON.Mesh} the default mesh
  56160. */
  56161. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  56162. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  56163. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  56164. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  56165. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  56166. mesh.material = material;
  56167. return mesh;
  56168. };
  56169. __decorate([
  56170. BABYLON.serializeAsVector3()
  56171. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  56172. __decorate([
  56173. BABYLON.serialize()
  56174. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  56175. __decorate([
  56176. BABYLON.serialize()
  56177. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  56178. __decorate([
  56179. BABYLON.serializeAsMeshReference()
  56180. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  56181. __decorate([
  56182. BABYLON.serialize()
  56183. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  56184. __decorate([
  56185. BABYLON.serialize()
  56186. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  56187. __decorate([
  56188. BABYLON.serialize()
  56189. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  56190. __decorate([
  56191. BABYLON.serialize()
  56192. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  56193. __decorate([
  56194. BABYLON.serialize()
  56195. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  56196. return VolumetricLightScatteringPostProcess;
  56197. })(BABYLON.PostProcess);
  56198. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  56199. })(BABYLON || (BABYLON = {}));
  56200. // BABYLON.JS Chromatic Aberration GLSL Shader
  56201. // Author: Olivier Guyot
  56202. // Separates very slightly R, G and B colors on the edges of the screen
  56203. // Inspired by Francois Tarlier & Martins Upitis
  56204. var BABYLON;
  56205. (function (BABYLON) {
  56206. var LensRenderingPipeline = (function (_super) {
  56207. __extends(LensRenderingPipeline, _super);
  56208. /**
  56209. * @constructor
  56210. *
  56211. * Effect parameters are as follow:
  56212. * {
  56213. * chromatic_aberration: number; // from 0 to x (1 for realism)
  56214. * edge_blur: number; // from 0 to x (1 for realism)
  56215. * distortion: number; // from 0 to x (1 for realism)
  56216. * grain_amount: number; // from 0 to 1
  56217. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  56218. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  56219. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  56220. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  56221. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  56222. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  56223. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  56224. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  56225. * }
  56226. * Note: if an effect parameter is unset, effect is disabled
  56227. *
  56228. * @param {string} name - The rendering pipeline name
  56229. * @param {object} parameters - An object containing all parameters (see above)
  56230. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56231. * @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)
  56232. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56233. */
  56234. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  56235. var _this = this;
  56236. if (ratio === void 0) { ratio = 1.0; }
  56237. _super.call(this, scene.getEngine(), name);
  56238. // Lens effects can be of the following:
  56239. // - chromatic aberration (slight shift of RGB colors)
  56240. // - blur on the edge of the lens
  56241. // - lens distortion
  56242. // - depth-of-field blur & highlights enhancing
  56243. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  56244. // - grain effect (noise or custom texture)
  56245. // Two additional texture samplers are needed:
  56246. // - depth map (for depth-of-field)
  56247. // - grain texture
  56248. /**
  56249. * The chromatic aberration PostProcess id in the pipeline
  56250. * @type {string}
  56251. */
  56252. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  56253. /**
  56254. * The highlights enhancing PostProcess id in the pipeline
  56255. * @type {string}
  56256. */
  56257. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  56258. /**
  56259. * The depth-of-field PostProcess id in the pipeline
  56260. * @type {string}
  56261. */
  56262. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  56263. this._scene = scene;
  56264. // Fetch texture samplers
  56265. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  56266. if (parameters.grain_texture) {
  56267. this._grainTexture = parameters.grain_texture;
  56268. }
  56269. else {
  56270. this._createGrainTexture();
  56271. }
  56272. // save parameters
  56273. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  56274. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  56275. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  56276. this._distortion = parameters.distortion ? parameters.distortion : 0;
  56277. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  56278. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  56279. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  56280. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  56281. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  56282. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  56283. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  56284. // Create effects
  56285. this._createChromaticAberrationPostProcess(ratio);
  56286. this._createHighlightsPostProcess(ratio);
  56287. this._createDepthOfFieldPostProcess(ratio / 4);
  56288. // Set up pipeline
  56289. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  56290. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  56291. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  56292. if (this._highlightsGain === -1) {
  56293. this._disableEffect(this.HighlightsEnhancingEffect, null);
  56294. }
  56295. // Finish
  56296. scene.postProcessRenderPipelineManager.addPipeline(this);
  56297. if (cameras) {
  56298. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56299. }
  56300. }
  56301. // public methods (self explanatory)
  56302. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  56303. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  56304. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  56305. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  56306. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  56307. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  56308. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  56309. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  56310. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  56311. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  56312. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  56313. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  56314. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  56315. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  56316. };
  56317. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  56318. this._highlightsPostProcess.updateEffect();
  56319. };
  56320. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  56321. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  56322. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  56323. this._highlightsGain = amount;
  56324. };
  56325. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  56326. if (this._highlightsGain === -1) {
  56327. this._highlightsGain = 1.0;
  56328. }
  56329. this._highlightsThreshold = amount;
  56330. };
  56331. LensRenderingPipeline.prototype.disableHighlights = function () {
  56332. this._highlightsGain = -1;
  56333. };
  56334. /**
  56335. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  56336. */
  56337. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  56338. if (disableDepthRender === void 0) { disableDepthRender = false; }
  56339. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56340. this._chromaticAberrationPostProcess = undefined;
  56341. this._highlightsPostProcess = undefined;
  56342. this._depthOfFieldPostProcess = undefined;
  56343. this._grainTexture.dispose();
  56344. if (disableDepthRender)
  56345. this._scene.disableDepthRenderer();
  56346. };
  56347. // colors shifting and distortion
  56348. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  56349. var _this = this;
  56350. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  56351. [], // samplers
  56352. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56353. this._chromaticAberrationPostProcess.onApply = function (effect) {
  56354. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  56355. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56356. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56357. };
  56358. };
  56359. // highlights enhancing
  56360. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  56361. var _this = this;
  56362. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  56363. [], // samplers
  56364. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  56365. this._highlightsPostProcess.onApply = function (effect) {
  56366. effect.setFloat('gain', _this._highlightsGain);
  56367. effect.setFloat('threshold', _this._highlightsThreshold);
  56368. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  56369. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56370. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56371. };
  56372. };
  56373. // colors shifting and distortion
  56374. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  56375. var _this = this;
  56376. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  56377. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  56378. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  56379. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56380. this._depthOfFieldPostProcess.onApply = function (effect) {
  56381. effect.setTexture("depthSampler", _this._depthTexture);
  56382. effect.setTexture("grainSampler", _this._grainTexture);
  56383. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  56384. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  56385. effect.setFloat('grain_amount', _this._grainAmount);
  56386. effect.setBool('blur_noise', _this._blurNoise);
  56387. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56388. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56389. effect.setFloat('distortion', _this._distortion);
  56390. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  56391. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  56392. effect.setFloat('aperture', _this._dofAperture);
  56393. effect.setFloat('darken', _this._dofDarken);
  56394. effect.setFloat('edge_blur', _this._edgeBlur);
  56395. effect.setBool('highlights', (_this._highlightsGain !== -1));
  56396. effect.setFloat('near', _this._scene.activeCamera.minZ);
  56397. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  56398. };
  56399. };
  56400. // creates a black and white random noise texture, 512x512
  56401. LensRenderingPipeline.prototype._createGrainTexture = function () {
  56402. var size = 512;
  56403. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56404. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56405. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56406. var context = this._grainTexture.getContext();
  56407. var rand = function (min, max) {
  56408. return Math.random() * (max - min) + min;
  56409. };
  56410. var value;
  56411. for (var x = 0; x < size; x++) {
  56412. for (var y = 0; y < size; y++) {
  56413. value = Math.floor(rand(0.42, 0.58) * 255);
  56414. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  56415. context.fillRect(x, y, 1, 1);
  56416. }
  56417. }
  56418. this._grainTexture.update(false);
  56419. };
  56420. return LensRenderingPipeline;
  56421. })(BABYLON.PostProcessRenderPipeline);
  56422. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  56423. })(BABYLON || (BABYLON = {}));
  56424. //
  56425. // This post-process allows the modification of rendered colors by using
  56426. // a 'look-up table' (LUT). This effect is also called Color Grading.
  56427. //
  56428. // The object needs to be provided an url to a texture containing the color
  56429. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  56430. // Use an image editing software to tweak the LUT to match your needs.
  56431. //
  56432. // For an example of a color LUT, see here:
  56433. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  56434. // For explanations on color grading, see here:
  56435. // http://udn.epicgames.com/Three/ColorGrading.html
  56436. //
  56437. var BABYLON;
  56438. (function (BABYLON) {
  56439. var ColorCorrectionPostProcess = (function (_super) {
  56440. __extends(ColorCorrectionPostProcess, _super);
  56441. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  56442. var _this = this;
  56443. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  56444. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56445. this._colorTableTexture.anisotropicFilteringLevel = 1;
  56446. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56447. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56448. this.onApply = function (effect) {
  56449. effect.setTexture("colorTable", _this._colorTableTexture);
  56450. };
  56451. }
  56452. return ColorCorrectionPostProcess;
  56453. })(BABYLON.PostProcess);
  56454. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  56455. })(BABYLON || (BABYLON = {}));
  56456. var BABYLON;
  56457. (function (BABYLON) {
  56458. var AnaglyphFreeCamera = (function (_super) {
  56459. __extends(AnaglyphFreeCamera, _super);
  56460. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  56461. _super.call(this, name, position, scene);
  56462. this.interaxialDistance = interaxialDistance;
  56463. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56464. }
  56465. AnaglyphFreeCamera.prototype.getTypeName = function () {
  56466. return "AnaglyphFreeCamera";
  56467. };
  56468. return AnaglyphFreeCamera;
  56469. })(BABYLON.FreeCamera);
  56470. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  56471. var AnaglyphArcRotateCamera = (function (_super) {
  56472. __extends(AnaglyphArcRotateCamera, _super);
  56473. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  56474. _super.call(this, name, alpha, beta, radius, target, scene);
  56475. this.interaxialDistance = interaxialDistance;
  56476. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56477. }
  56478. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  56479. return "AnaglyphArcRotateCamera";
  56480. };
  56481. return AnaglyphArcRotateCamera;
  56482. })(BABYLON.ArcRotateCamera);
  56483. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  56484. var AnaglyphGamepadCamera = (function (_super) {
  56485. __extends(AnaglyphGamepadCamera, _super);
  56486. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  56487. _super.call(this, name, position, scene);
  56488. this.interaxialDistance = interaxialDistance;
  56489. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56490. }
  56491. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  56492. return "AnaglyphGamepadCamera";
  56493. };
  56494. return AnaglyphGamepadCamera;
  56495. })(BABYLON.GamepadCamera);
  56496. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  56497. var AnaglyphUniversalCamera = (function (_super) {
  56498. __extends(AnaglyphUniversalCamera, _super);
  56499. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  56500. _super.call(this, name, position, scene);
  56501. this.interaxialDistance = interaxialDistance;
  56502. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  56503. }
  56504. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  56505. return "AnaglyphUniversalCamera";
  56506. };
  56507. return AnaglyphUniversalCamera;
  56508. })(BABYLON.UniversalCamera);
  56509. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  56510. var StereoscopicFreeCamera = (function (_super) {
  56511. __extends(StereoscopicFreeCamera, _super);
  56512. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56513. _super.call(this, name, position, scene);
  56514. this.interaxialDistance = interaxialDistance;
  56515. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56516. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56517. }
  56518. StereoscopicFreeCamera.prototype.getTypeName = function () {
  56519. return "StereoscopicFreeCamera";
  56520. };
  56521. return StereoscopicFreeCamera;
  56522. })(BABYLON.FreeCamera);
  56523. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  56524. var StereoscopicArcRotateCamera = (function (_super) {
  56525. __extends(StereoscopicArcRotateCamera, _super);
  56526. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  56527. _super.call(this, name, alpha, beta, radius, target, scene);
  56528. this.interaxialDistance = interaxialDistance;
  56529. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56530. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56531. }
  56532. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  56533. return "StereoscopicArcRotateCamera";
  56534. };
  56535. return StereoscopicArcRotateCamera;
  56536. })(BABYLON.ArcRotateCamera);
  56537. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  56538. var StereoscopicGamepadCamera = (function (_super) {
  56539. __extends(StereoscopicGamepadCamera, _super);
  56540. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56541. _super.call(this, name, position, scene);
  56542. this.interaxialDistance = interaxialDistance;
  56543. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56544. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56545. }
  56546. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  56547. return "StereoscopicGamepadCamera";
  56548. };
  56549. return StereoscopicGamepadCamera;
  56550. })(BABYLON.GamepadCamera);
  56551. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  56552. var StereoscopicUniversalCamera = (function (_super) {
  56553. __extends(StereoscopicUniversalCamera, _super);
  56554. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56555. _super.call(this, name, position, scene);
  56556. this.interaxialDistance = interaxialDistance;
  56557. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56558. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56559. }
  56560. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  56561. return "StereoscopicUniversalCamera";
  56562. };
  56563. return StereoscopicUniversalCamera;
  56564. })(BABYLON.UniversalCamera);
  56565. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  56566. })(BABYLON || (BABYLON = {}));
  56567. var BABYLON;
  56568. (function (BABYLON) {
  56569. var HDRRenderingPipeline = (function (_super) {
  56570. __extends(HDRRenderingPipeline, _super);
  56571. /**
  56572. * @constructor
  56573. * @param {string} name - The rendering pipeline name
  56574. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56575. * @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)
  56576. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  56577. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56578. */
  56579. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  56580. var _this = this;
  56581. if (originalPostProcess === void 0) { originalPostProcess = null; }
  56582. _super.call(this, scene.getEngine(), name);
  56583. /**
  56584. * Public members
  56585. */
  56586. // Gaussian Blur
  56587. /**
  56588. * Gaussian blur coefficient
  56589. * @type {number}
  56590. */
  56591. this.gaussCoeff = 0.3;
  56592. /**
  56593. * Gaussian blur mean
  56594. * @type {number}
  56595. */
  56596. this.gaussMean = 1.0;
  56597. /**
  56598. * Gaussian blur standard deviation
  56599. * @type {number}
  56600. */
  56601. this.gaussStandDev = 0.8;
  56602. /**
  56603. * Gaussian blur multiplier. Multiplies the blur effect
  56604. * @type {number}
  56605. */
  56606. this.gaussMultiplier = 4.0;
  56607. // HDR
  56608. /**
  56609. * Exposure, controls the overall intensity of the pipeline
  56610. * @type {number}
  56611. */
  56612. this.exposure = 1.0;
  56613. /**
  56614. * Minimum luminance that the post-process can output. Luminance is >= 0
  56615. * @type {number}
  56616. */
  56617. this.minimumLuminance = 1.0;
  56618. /**
  56619. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  56620. * @type {number}
  56621. */
  56622. this.maximumLuminance = 1e20;
  56623. /**
  56624. * Increase rate for luminance: eye adaptation speed to dark
  56625. * @type {number}
  56626. */
  56627. this.luminanceIncreaserate = 0.5;
  56628. /**
  56629. * Decrease rate for luminance: eye adaptation speed to bright
  56630. * @type {number}
  56631. */
  56632. this.luminanceDecreaseRate = 0.5;
  56633. // Bright pass
  56634. /**
  56635. * Minimum luminance needed to compute HDR
  56636. * @type {number}
  56637. */
  56638. this.brightThreshold = 0.8;
  56639. this._needUpdate = true;
  56640. this._scene = scene;
  56641. // Bright pass
  56642. this._createBrightPassPostProcess(scene, ratio);
  56643. // Down sample X4
  56644. this._createDownSampleX4PostProcess(scene, ratio);
  56645. // Create gaussian blur post-processes
  56646. this._createGaussianBlurPostProcess(scene, ratio);
  56647. // Texture adder
  56648. this._createTextureAdderPostProcess(scene, ratio);
  56649. // Luminance generator
  56650. this._createLuminanceGeneratorPostProcess(scene);
  56651. // HDR
  56652. this._createHDRPostProcess(scene, ratio);
  56653. // Pass postprocess
  56654. if (originalPostProcess === null) {
  56655. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  56656. }
  56657. else {
  56658. this._originalPostProcess = originalPostProcess;
  56659. }
  56660. // Configure pipeline
  56661. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  56662. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  56663. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  56664. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  56665. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  56666. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  56667. var addDownSamplerPostProcess = function (id) {
  56668. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  56669. };
  56670. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  56671. addDownSamplerPostProcess(i);
  56672. }
  56673. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  56674. // Finish
  56675. scene.postProcessRenderPipelineManager.addPipeline(this);
  56676. if (cameras !== null) {
  56677. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56678. }
  56679. this.update();
  56680. }
  56681. /**
  56682. * Tells the pipeline to update its post-processes
  56683. */
  56684. HDRRenderingPipeline.prototype.update = function () {
  56685. this._needUpdate = true;
  56686. };
  56687. /**
  56688. * Returns the current calculated luminance
  56689. */
  56690. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  56691. return this._hdrCurrentLuminance;
  56692. };
  56693. /**
  56694. * Returns the currently drawn luminance
  56695. */
  56696. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  56697. return this._hdrOutputLuminance;
  56698. };
  56699. /**
  56700. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  56701. */
  56702. HDRRenderingPipeline.prototype.dispose = function () {
  56703. this._originalPostProcess = undefined;
  56704. this._brightPassPostProcess = undefined;
  56705. this._downSampleX4PostProcess = undefined;
  56706. this._guassianBlurHPostProcess = undefined;
  56707. this._guassianBlurVPostProcess = undefined;
  56708. this._textureAdderPostProcess = undefined;
  56709. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  56710. this._downSamplePostProcesses[i] = undefined;
  56711. }
  56712. this._hdrPostProcess = undefined;
  56713. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56714. };
  56715. /**
  56716. * Creates the HDR post-process and computes the luminance adaptation
  56717. */
  56718. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  56719. var _this = this;
  56720. var hdrLastLuminance = 0.0;
  56721. this._hdrOutputLuminance = -1.0;
  56722. this._hdrCurrentLuminance = 1.0;
  56723. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  56724. this._hdrPostProcess.onApply = function (effect) {
  56725. if (_this._hdrOutputLuminance < 0.0) {
  56726. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  56727. }
  56728. else {
  56729. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  56730. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  56731. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  56732. }
  56733. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  56734. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  56735. }
  56736. else {
  56737. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  56738. }
  56739. }
  56740. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  56741. hdrLastLuminance += scene.getEngine().getDeltaTime();
  56742. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  56743. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  56744. effect.setFloat("exposure", _this.exposure);
  56745. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  56746. _this._needUpdate = false;
  56747. };
  56748. };
  56749. /**
  56750. * Texture Adder post-process
  56751. */
  56752. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  56753. var _this = this;
  56754. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  56755. this._textureAdderPostProcess.onApply = function (effect) {
  56756. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  56757. };
  56758. };
  56759. /**
  56760. * Down sample X4 post-process
  56761. */
  56762. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  56763. var _this = this;
  56764. var downSampleX4Offsets = new Array(32);
  56765. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  56766. this._downSampleX4PostProcess.onApply = function (effect) {
  56767. if (_this._needUpdate) {
  56768. var id = 0;
  56769. for (var i = -2; i < 2; i++) {
  56770. for (var j = -2; j < 2; j++) {
  56771. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  56772. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  56773. id += 2;
  56774. }
  56775. }
  56776. }
  56777. effect.setArray2("dsOffsets", downSampleX4Offsets);
  56778. };
  56779. };
  56780. /**
  56781. * Bright pass post-process
  56782. */
  56783. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  56784. var _this = this;
  56785. var brightOffsets = new Array(8);
  56786. var brightPassCallback = function (effect) {
  56787. if (_this._needUpdate) {
  56788. var sU = (1.0 / _this._brightPassPostProcess.width);
  56789. var sV = (1.0 / _this._brightPassPostProcess.height);
  56790. brightOffsets[0] = -0.5 * sU;
  56791. brightOffsets[1] = 0.5 * sV;
  56792. brightOffsets[2] = 0.5 * sU;
  56793. brightOffsets[3] = 0.5 * sV;
  56794. brightOffsets[4] = -0.5 * sU;
  56795. brightOffsets[5] = -0.5 * sV;
  56796. brightOffsets[6] = 0.5 * sU;
  56797. brightOffsets[7] = -0.5 * sV;
  56798. }
  56799. effect.setArray2("dsOffsets", brightOffsets);
  56800. effect.setFloat("brightThreshold", _this.brightThreshold);
  56801. };
  56802. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  56803. this._brightPassPostProcess.onApply = brightPassCallback;
  56804. };
  56805. /**
  56806. * Luminance generator. Creates the luminance post-process and down sample post-processes
  56807. */
  56808. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  56809. var _this = this;
  56810. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  56811. var luminanceOffsets = new Array(8);
  56812. var downSampleOffsets = new Array(18);
  56813. var halfDestPixelSize;
  56814. this._downSamplePostProcesses = new Array(lumSteps);
  56815. // Utils for luminance
  56816. var luminanceUpdateSourceOffsets = function (width, height) {
  56817. var sU = (1.0 / width);
  56818. var sV = (1.0 / height);
  56819. luminanceOffsets[0] = -0.5 * sU;
  56820. luminanceOffsets[1] = 0.5 * sV;
  56821. luminanceOffsets[2] = 0.5 * sU;
  56822. luminanceOffsets[3] = 0.5 * sV;
  56823. luminanceOffsets[4] = -0.5 * sU;
  56824. luminanceOffsets[5] = -0.5 * sV;
  56825. luminanceOffsets[6] = 0.5 * sU;
  56826. luminanceOffsets[7] = -0.5 * sV;
  56827. };
  56828. var luminanceUpdateDestOffsets = function (width, height) {
  56829. var id = 0;
  56830. for (var x = -1; x < 2; x++) {
  56831. for (var y = -1; y < 2; y++) {
  56832. downSampleOffsets[id] = (x) / width;
  56833. downSampleOffsets[id + 1] = (y) / height;
  56834. id += 2;
  56835. }
  56836. }
  56837. };
  56838. // Luminance callback
  56839. var luminanceCallback = function (effect) {
  56840. if (_this._needUpdate) {
  56841. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  56842. }
  56843. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  56844. effect.setArray2("lumOffsets", luminanceOffsets);
  56845. };
  56846. // Down sample callbacks
  56847. var downSampleCallback = function (indice) {
  56848. var i = indice;
  56849. return function (effect) {
  56850. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  56851. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  56852. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  56853. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  56854. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  56855. effect.setArray2("dsOffsets", downSampleOffsets);
  56856. };
  56857. };
  56858. var downSampleAfterRenderCallback = function (effect) {
  56859. // Unpack result
  56860. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  56861. 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);
  56862. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  56863. };
  56864. // Create luminance post-process
  56865. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  56866. 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);
  56867. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  56868. // Create down sample post-processes
  56869. for (var i = lumSteps - 2; i >= 0; i--) {
  56870. var length = Math.pow(3, i);
  56871. ratio = { width: length, height: length };
  56872. var defines = "#define DOWN_SAMPLE\n";
  56873. if (i === 0) {
  56874. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  56875. }
  56876. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  56877. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  56878. if (i === 0) {
  56879. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  56880. }
  56881. }
  56882. };
  56883. /**
  56884. * Gaussian blur post-processes. Horizontal and Vertical
  56885. */
  56886. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  56887. var _this = this;
  56888. var blurOffsetsW = new Array(9);
  56889. var blurOffsetsH = new Array(9);
  56890. var blurWeights = new Array(9);
  56891. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  56892. // Utils for gaussian blur
  56893. var calculateBlurOffsets = function (height) {
  56894. var lastOutputDimensions = {
  56895. width: scene.getEngine().getRenderWidth(),
  56896. height: scene.getEngine().getRenderHeight()
  56897. };
  56898. for (var i = 0; i < 9; i++) {
  56899. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  56900. if (height) {
  56901. blurOffsetsH[i] = value;
  56902. }
  56903. else {
  56904. blurOffsetsW[i] = value;
  56905. }
  56906. }
  56907. };
  56908. var calculateWeights = function () {
  56909. var x = 0.0;
  56910. for (var i = 0; i < 9; i++) {
  56911. x = (i - 4.0) / 4.0;
  56912. 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));
  56913. }
  56914. };
  56915. // Callback
  56916. var gaussianBlurCallback = function (height) {
  56917. return function (effect) {
  56918. if (_this._needUpdate) {
  56919. calculateWeights();
  56920. calculateBlurOffsets(height);
  56921. }
  56922. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  56923. effect.setArray("blurWeights", blurWeights);
  56924. effect.setFloat("multiplier", _this.gaussMultiplier);
  56925. };
  56926. };
  56927. // Create horizontal gaussian blur post-processes
  56928. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  56929. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  56930. // Create vertical gaussian blur post-process
  56931. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  56932. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  56933. };
  56934. // Luminance generator
  56935. HDRRenderingPipeline.LUM_STEPS = 6;
  56936. return HDRRenderingPipeline;
  56937. })(BABYLON.PostProcessRenderPipeline);
  56938. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  56939. })(BABYLON || (BABYLON = {}));
  56940. var BABYLON;
  56941. (function (BABYLON) {
  56942. var FaceAdjacencies = (function () {
  56943. function FaceAdjacencies() {
  56944. this.edges = new Array();
  56945. this.edgesConnectedCount = 0;
  56946. }
  56947. return FaceAdjacencies;
  56948. })();
  56949. var EdgesRenderer = (function () {
  56950. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  56951. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  56952. if (epsilon === void 0) { epsilon = 0.95; }
  56953. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  56954. this.edgesWidthScalerForOrthographic = 1000.0;
  56955. this.edgesWidthScalerForPerspective = 50.0;
  56956. this._linesPositions = new Array();
  56957. this._linesNormals = new Array();
  56958. this._linesIndices = new Array();
  56959. this._buffers = {};
  56960. this._checkVerticesInsteadOfIndices = false;
  56961. this._source = source;
  56962. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  56963. this._epsilon = epsilon;
  56964. this._prepareRessources();
  56965. this._generateEdgesLines();
  56966. }
  56967. EdgesRenderer.prototype._prepareRessources = function () {
  56968. if (this._lineShader) {
  56969. return;
  56970. }
  56971. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  56972. attributes: ["position", "normal"],
  56973. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  56974. });
  56975. this._lineShader.disableDepthWrite = true;
  56976. this._lineShader.backFaceCulling = false;
  56977. };
  56978. EdgesRenderer.prototype.dispose = function () {
  56979. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  56980. if (buffer) {
  56981. buffer.dispose();
  56982. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  56983. }
  56984. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  56985. if (buffer) {
  56986. buffer.dispose();
  56987. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  56988. }
  56989. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  56990. this._lineShader.dispose();
  56991. };
  56992. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  56993. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  56994. return 0;
  56995. }
  56996. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  56997. return 1;
  56998. }
  56999. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  57000. return 2;
  57001. }
  57002. return -1;
  57003. };
  57004. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  57005. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  57006. return 0;
  57007. }
  57008. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  57009. return 1;
  57010. }
  57011. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  57012. return 2;
  57013. }
  57014. return -1;
  57015. };
  57016. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  57017. var needToCreateLine;
  57018. if (edge === undefined) {
  57019. needToCreateLine = true;
  57020. }
  57021. else {
  57022. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  57023. needToCreateLine = dotProduct < this._epsilon;
  57024. }
  57025. if (needToCreateLine) {
  57026. var offset = this._linesPositions.length / 3;
  57027. var normal = p0.subtract(p1);
  57028. normal.normalize();
  57029. // Positions
  57030. this._linesPositions.push(p0.x);
  57031. this._linesPositions.push(p0.y);
  57032. this._linesPositions.push(p0.z);
  57033. this._linesPositions.push(p0.x);
  57034. this._linesPositions.push(p0.y);
  57035. this._linesPositions.push(p0.z);
  57036. this._linesPositions.push(p1.x);
  57037. this._linesPositions.push(p1.y);
  57038. this._linesPositions.push(p1.z);
  57039. this._linesPositions.push(p1.x);
  57040. this._linesPositions.push(p1.y);
  57041. this._linesPositions.push(p1.z);
  57042. // Normals
  57043. this._linesNormals.push(p1.x);
  57044. this._linesNormals.push(p1.y);
  57045. this._linesNormals.push(p1.z);
  57046. this._linesNormals.push(-1);
  57047. this._linesNormals.push(p1.x);
  57048. this._linesNormals.push(p1.y);
  57049. this._linesNormals.push(p1.z);
  57050. this._linesNormals.push(1);
  57051. this._linesNormals.push(p0.x);
  57052. this._linesNormals.push(p0.y);
  57053. this._linesNormals.push(p0.z);
  57054. this._linesNormals.push(-1);
  57055. this._linesNormals.push(p0.x);
  57056. this._linesNormals.push(p0.y);
  57057. this._linesNormals.push(p0.z);
  57058. this._linesNormals.push(1);
  57059. // Indices
  57060. this._linesIndices.push(offset);
  57061. this._linesIndices.push(offset + 1);
  57062. this._linesIndices.push(offset + 2);
  57063. this._linesIndices.push(offset);
  57064. this._linesIndices.push(offset + 2);
  57065. this._linesIndices.push(offset + 3);
  57066. }
  57067. };
  57068. EdgesRenderer.prototype._generateEdgesLines = function () {
  57069. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57070. var indices = this._source.getIndices();
  57071. // First let's find adjacencies
  57072. var adjacencies = new Array();
  57073. var faceNormals = new Array();
  57074. var index;
  57075. var faceAdjacencies;
  57076. // Prepare faces
  57077. for (index = 0; index < indices.length; index += 3) {
  57078. faceAdjacencies = new FaceAdjacencies();
  57079. var p0Index = indices[index];
  57080. var p1Index = indices[index + 1];
  57081. var p2Index = indices[index + 2];
  57082. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  57083. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  57084. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  57085. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  57086. faceNormal.normalize();
  57087. faceNormals.push(faceNormal);
  57088. adjacencies.push(faceAdjacencies);
  57089. }
  57090. // Scan
  57091. for (index = 0; index < adjacencies.length; index++) {
  57092. faceAdjacencies = adjacencies[index];
  57093. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  57094. var otherFaceAdjacencies = adjacencies[otherIndex];
  57095. if (faceAdjacencies.edgesConnectedCount === 3) {
  57096. break;
  57097. }
  57098. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  57099. continue;
  57100. }
  57101. var otherP0 = indices[otherIndex * 3];
  57102. var otherP1 = indices[otherIndex * 3 + 1];
  57103. var otherP2 = indices[otherIndex * 3 + 2];
  57104. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  57105. var otherEdgeIndex;
  57106. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  57107. continue;
  57108. }
  57109. switch (edgeIndex) {
  57110. case 0:
  57111. if (this._checkVerticesInsteadOfIndices) {
  57112. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  57113. }
  57114. else {
  57115. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  57116. }
  57117. break;
  57118. case 1:
  57119. if (this._checkVerticesInsteadOfIndices) {
  57120. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  57121. }
  57122. else {
  57123. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  57124. }
  57125. break;
  57126. case 2:
  57127. if (this._checkVerticesInsteadOfIndices) {
  57128. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  57129. }
  57130. else {
  57131. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  57132. }
  57133. break;
  57134. }
  57135. if (otherEdgeIndex === -1) {
  57136. continue;
  57137. }
  57138. faceAdjacencies.edges[edgeIndex] = otherIndex;
  57139. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  57140. faceAdjacencies.edgesConnectedCount++;
  57141. otherFaceAdjacencies.edgesConnectedCount++;
  57142. if (faceAdjacencies.edgesConnectedCount === 3) {
  57143. break;
  57144. }
  57145. }
  57146. }
  57147. }
  57148. // Create lines
  57149. for (index = 0; index < adjacencies.length; index++) {
  57150. // 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
  57151. var current = adjacencies[index];
  57152. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  57153. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  57154. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  57155. }
  57156. // Merge into a single mesh
  57157. var engine = this._source.getScene().getEngine();
  57158. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  57159. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  57160. this._ib = engine.createIndexBuffer(this._linesIndices);
  57161. this._indicesCount = this._linesIndices.length;
  57162. };
  57163. EdgesRenderer.prototype.render = function () {
  57164. if (!this._lineShader.isReady()) {
  57165. return;
  57166. }
  57167. var scene = this._source.getScene();
  57168. var engine = scene.getEngine();
  57169. this._lineShader._preBind();
  57170. // VBOs
  57171. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  57172. scene.resetCachedMaterial();
  57173. this._lineShader.setColor4("color", this._source.edgesColor);
  57174. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  57175. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  57176. }
  57177. else {
  57178. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  57179. }
  57180. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  57181. this._lineShader.bind(this._source.getWorldMatrix());
  57182. // Draw order
  57183. engine.draw(true, 0, this._indicesCount);
  57184. this._lineShader.unbind();
  57185. engine.setDepthWrite(true);
  57186. };
  57187. return EdgesRenderer;
  57188. })();
  57189. BABYLON.EdgesRenderer = EdgesRenderer;
  57190. })(BABYLON || (BABYLON = {}));
  57191. var BABYLON;
  57192. (function (BABYLON) {
  57193. (function (TonemappingOperator) {
  57194. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  57195. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  57196. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  57197. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  57198. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  57199. var TonemappingOperator = BABYLON.TonemappingOperator;
  57200. ;
  57201. var TonemapPostProcess = (function (_super) {
  57202. __extends(TonemapPostProcess, _super);
  57203. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  57204. var _this = this;
  57205. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57206. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57207. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  57208. this._operator = _operator;
  57209. this.exposureAdjustment = exposureAdjustment;
  57210. var defines = "#define ";
  57211. if (this._operator === TonemappingOperator.Hable)
  57212. defines += "HABLE_TONEMAPPING";
  57213. else if (this._operator === TonemappingOperator.Reinhard)
  57214. defines += "REINHARD_TONEMAPPING";
  57215. else if (this._operator === TonemappingOperator.HejiDawson)
  57216. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  57217. else if (this._operator === TonemappingOperator.Photographic)
  57218. defines += "PHOTOGRAPHIC_TONEMAPPING";
  57219. //sadly a second call to create the effect.
  57220. this.updateEffect(defines);
  57221. this.onApply = function (effect) {
  57222. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  57223. };
  57224. }
  57225. return TonemapPostProcess;
  57226. })(BABYLON.PostProcess);
  57227. BABYLON.TonemapPostProcess = TonemapPostProcess;
  57228. })(BABYLON || (BABYLON = {}));
  57229. var BABYLON;
  57230. (function (BABYLON) {
  57231. var ReflectionProbe = (function () {
  57232. function ReflectionProbe(name, size, scene, generateMipMaps) {
  57233. var _this = this;
  57234. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57235. this.name = name;
  57236. this._viewMatrix = BABYLON.Matrix.Identity();
  57237. this._target = BABYLON.Vector3.Zero();
  57238. this._add = BABYLON.Vector3.Zero();
  57239. this.invertYAxis = false;
  57240. this.position = BABYLON.Vector3.Zero();
  57241. this._scene = scene;
  57242. this._scene.reflectionProbes.push(this);
  57243. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  57244. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  57245. switch (faceIndex) {
  57246. case 0:
  57247. _this._add.copyFromFloats(1, 0, 0);
  57248. break;
  57249. case 1:
  57250. _this._add.copyFromFloats(-1, 0, 0);
  57251. break;
  57252. case 2:
  57253. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  57254. break;
  57255. case 3:
  57256. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  57257. break;
  57258. case 4:
  57259. _this._add.copyFromFloats(0, 0, 1);
  57260. break;
  57261. case 5:
  57262. _this._add.copyFromFloats(0, 0, -1);
  57263. break;
  57264. }
  57265. if (_this._attachedMesh) {
  57266. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  57267. }
  57268. _this.position.addToRef(_this._add, _this._target);
  57269. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  57270. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  57271. });
  57272. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  57273. scene.updateTransformMatrix(true);
  57274. });
  57275. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  57276. }
  57277. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  57278. get: function () {
  57279. return this._renderTargetTexture.refreshRate;
  57280. },
  57281. set: function (value) {
  57282. this._renderTargetTexture.refreshRate = value;
  57283. },
  57284. enumerable: true,
  57285. configurable: true
  57286. });
  57287. ReflectionProbe.prototype.getScene = function () {
  57288. return this._scene;
  57289. };
  57290. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  57291. get: function () {
  57292. return this._renderTargetTexture;
  57293. },
  57294. enumerable: true,
  57295. configurable: true
  57296. });
  57297. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  57298. get: function () {
  57299. return this._renderTargetTexture.renderList;
  57300. },
  57301. enumerable: true,
  57302. configurable: true
  57303. });
  57304. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  57305. this._attachedMesh = mesh;
  57306. };
  57307. ReflectionProbe.prototype.dispose = function () {
  57308. var index = this._scene.reflectionProbes.indexOf(this);
  57309. if (index !== -1) {
  57310. // Remove from the scene if found
  57311. this._scene.reflectionProbes.splice(index, 1);
  57312. }
  57313. if (this._renderTargetTexture) {
  57314. this._renderTargetTexture.dispose();
  57315. this._renderTargetTexture = null;
  57316. }
  57317. };
  57318. return ReflectionProbe;
  57319. })();
  57320. BABYLON.ReflectionProbe = ReflectionProbe;
  57321. })(BABYLON || (BABYLON = {}));
  57322. var BABYLON;
  57323. (function (BABYLON) {
  57324. var SolidParticle = (function () {
  57325. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  57326. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  57327. this.position = BABYLON.Vector3.Zero(); // position
  57328. this.rotation = BABYLON.Vector3.Zero(); // rotation
  57329. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  57330. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  57331. this.velocity = BABYLON.Vector3.Zero(); // velocity
  57332. this.alive = true; // alive
  57333. this.isVisible = true; // visibility
  57334. this.idx = particleIndex;
  57335. this._pos = positionIndex;
  57336. this._model = model;
  57337. this.shapeId = shapeId;
  57338. this.idxInShape = idxInShape;
  57339. }
  57340. Object.defineProperty(SolidParticle.prototype, "scale", {
  57341. //legacy support, changed scale to scaling
  57342. get: function () {
  57343. return this.scaling;
  57344. },
  57345. set: function (scale) {
  57346. this.scaling = scale;
  57347. },
  57348. enumerable: true,
  57349. configurable: true
  57350. });
  57351. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57352. //legacy support, changed quaternion to rotationQuaternion
  57353. get: function () {
  57354. return this.rotationQuaternion;
  57355. },
  57356. set: function (q) {
  57357. this.rotationQuaternion = q;
  57358. },
  57359. enumerable: true,
  57360. configurable: true
  57361. });
  57362. return SolidParticle;
  57363. })();
  57364. BABYLON.SolidParticle = SolidParticle;
  57365. var ModelShape = (function () {
  57366. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  57367. this.shapeID = id;
  57368. this._shape = shape;
  57369. this._shapeUV = shapeUV;
  57370. this._positionFunction = posFunction;
  57371. this._vertexFunction = vtxFunction;
  57372. }
  57373. return ModelShape;
  57374. })();
  57375. BABYLON.ModelShape = ModelShape;
  57376. })(BABYLON || (BABYLON = {}));
  57377. var BABYLON;
  57378. (function (BABYLON) {
  57379. /**
  57380. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57381. */
  57382. var SolidParticleSystem = (function () {
  57383. /**
  57384. * Creates a SPS (Solid Particle System) object.
  57385. * `name` (String) is the SPS name, this will be the underlying mesh name.
  57386. * `scene` (Scene) is the scene in which the SPS is added.
  57387. * `updatable` (default true) : if the SPS must be updatable or immutable.
  57388. * `isPickable` (default false) : if the solid particles must be pickable.
  57389. */
  57390. function SolidParticleSystem(name, scene, options) {
  57391. // public members
  57392. /**
  57393. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57394. * Example : var p = SPS.particles[i];
  57395. */
  57396. this.particles = new Array();
  57397. /**
  57398. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57399. */
  57400. this.nbParticles = 0;
  57401. /**
  57402. * If the particles must ever face the camera (default false). Useful for planar particles.
  57403. */
  57404. this.billboard = false;
  57405. /**
  57406. * This a counter ofr your own usage. It's not set by any SPS functions.
  57407. */
  57408. this.counter = 0;
  57409. /**
  57410. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57411. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57412. */
  57413. this.vars = {};
  57414. this._positions = new Array();
  57415. this._indices = new Array();
  57416. this._normals = new Array();
  57417. this._colors = new Array();
  57418. this._uvs = new Array();
  57419. this._index = 0; // indices index
  57420. this._updatable = true;
  57421. this._pickable = false;
  57422. this._isVisibilityBoxLocked = false;
  57423. this._alwaysVisible = false;
  57424. this._shapeCounter = 0;
  57425. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  57426. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57427. this._computeParticleColor = true;
  57428. this._computeParticleTexture = true;
  57429. this._computeParticleRotation = true;
  57430. this._computeParticleVertex = false;
  57431. this._computeBoundingBox = false;
  57432. this._cam_axisZ = BABYLON.Vector3.Zero();
  57433. this._cam_axisY = BABYLON.Vector3.Zero();
  57434. this._cam_axisX = BABYLON.Vector3.Zero();
  57435. this._axisX = BABYLON.Axis.X;
  57436. this._axisY = BABYLON.Axis.Y;
  57437. this._axisZ = BABYLON.Axis.Z;
  57438. this._camDir = BABYLON.Vector3.Zero();
  57439. this._rotMatrix = new BABYLON.Matrix();
  57440. this._invertMatrix = new BABYLON.Matrix();
  57441. this._rotated = BABYLON.Vector3.Zero();
  57442. this._quaternion = new BABYLON.Quaternion();
  57443. this._vertex = BABYLON.Vector3.Zero();
  57444. this._normal = BABYLON.Vector3.Zero();
  57445. this._yaw = 0.0;
  57446. this._pitch = 0.0;
  57447. this._roll = 0.0;
  57448. this._halfroll = 0.0;
  57449. this._halfpitch = 0.0;
  57450. this._halfyaw = 0.0;
  57451. this._sinRoll = 0.0;
  57452. this._cosRoll = 0.0;
  57453. this._sinPitch = 0.0;
  57454. this._cosPitch = 0.0;
  57455. this._sinYaw = 0.0;
  57456. this._cosYaw = 0.0;
  57457. this._w = 0.0;
  57458. this._minimum = BABYLON.Tmp.Vector3[0];
  57459. this._maximum = BABYLON.Tmp.Vector3[1];
  57460. this.name = name;
  57461. this._scene = scene;
  57462. this._camera = scene.activeCamera;
  57463. this._pickable = options ? options.isPickable : false;
  57464. if (options && options.updatable) {
  57465. this._updatable = options.updatable;
  57466. }
  57467. else {
  57468. this._updatable = true;
  57469. }
  57470. if (this._pickable) {
  57471. this.pickedParticles = [];
  57472. }
  57473. }
  57474. /**
  57475. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57476. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57477. */
  57478. SolidParticleSystem.prototype.buildMesh = function () {
  57479. if (this.nbParticles === 0) {
  57480. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57481. this.addShape(triangle, 1);
  57482. triangle.dispose();
  57483. }
  57484. this._positions32 = new Float32Array(this._positions);
  57485. this._uvs32 = new Float32Array(this._uvs);
  57486. this._colors32 = new Float32Array(this._colors);
  57487. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  57488. this._normals32 = new Float32Array(this._normals);
  57489. this._fixedNormal32 = new Float32Array(this._normals);
  57490. var vertexData = new BABYLON.VertexData();
  57491. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57492. vertexData.indices = this._indices;
  57493. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57494. if (this._uvs32) {
  57495. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57496. ;
  57497. }
  57498. if (this._colors32) {
  57499. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57500. }
  57501. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57502. vertexData.applyToMesh(mesh, this._updatable);
  57503. this.mesh = mesh;
  57504. this.mesh.isPickable = this._pickable;
  57505. // free memory
  57506. this._positions = null;
  57507. this._normals = null;
  57508. this._uvs = null;
  57509. this._colors = null;
  57510. if (!this._updatable) {
  57511. this.particles.length = 0;
  57512. }
  57513. return mesh;
  57514. };
  57515. /**
  57516. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57517. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57518. * Thus the particles generated from `digest()` have their property `position` set yet.
  57519. * `mesh` ( Mesh ) is the mesh to be digested
  57520. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  57521. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57522. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57523. */
  57524. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57525. var size = (options && options.facetNb) || 1;
  57526. var number = (options && options.number);
  57527. var delta = (options && options.delta) || 0;
  57528. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57529. var meshInd = mesh.getIndices();
  57530. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57531. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57532. var f = 0; // facet counter
  57533. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57534. // compute size from number
  57535. if (number) {
  57536. number = (number > totalFacets) ? totalFacets : number;
  57537. size = Math.round(totalFacets / number);
  57538. delta = 0;
  57539. }
  57540. else {
  57541. size = (size > totalFacets) ? totalFacets : size;
  57542. }
  57543. var facetPos = []; // submesh positions
  57544. var facetInd = []; // submesh indices
  57545. var facetUV = []; // submesh UV
  57546. var facetCol = []; // submesh colors
  57547. var barycenter = BABYLON.Tmp.Vector3[0];
  57548. var rand;
  57549. var sizeO = size;
  57550. while (f < totalFacets) {
  57551. size = sizeO + Math.floor((1 + delta) * Math.random());
  57552. if (f > totalFacets - size) {
  57553. size = totalFacets - f;
  57554. }
  57555. // reset temp arrays
  57556. facetPos.length = 0;
  57557. facetInd.length = 0;
  57558. facetUV.length = 0;
  57559. facetCol.length = 0;
  57560. // iterate over "size" facets
  57561. var fi = 0;
  57562. for (var j = f * 3; j < (f + size) * 3; j++) {
  57563. facetInd.push(fi);
  57564. var i = meshInd[j];
  57565. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57566. if (meshUV) {
  57567. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57568. }
  57569. if (meshCol) {
  57570. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57571. }
  57572. fi++;
  57573. }
  57574. // create a model shape for each single particle
  57575. var idx = this.nbParticles;
  57576. var shape = this._posToShape(facetPos);
  57577. var shapeUV = this._uvsToShapeUV(facetUV);
  57578. // compute the barycenter of the shape
  57579. var v;
  57580. for (v = 0; v < shape.length; v++) {
  57581. barycenter.addInPlace(shape[v]);
  57582. }
  57583. barycenter.scaleInPlace(1 / shape.length);
  57584. // shift the shape from its barycenter to the origin
  57585. for (v = 0; v < shape.length; v++) {
  57586. shape[v].subtractInPlace(barycenter);
  57587. }
  57588. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  57589. // add the particle in the SPS
  57590. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  57591. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  57592. // initialize the particle position
  57593. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57594. this._index += shape.length;
  57595. idx++;
  57596. this.nbParticles++;
  57597. this._shapeCounter++;
  57598. f += size;
  57599. }
  57600. return this;
  57601. };
  57602. //reset copy
  57603. SolidParticleSystem.prototype._resetCopy = function () {
  57604. this._copy.position.x = 0;
  57605. this._copy.position.y = 0;
  57606. this._copy.position.z = 0;
  57607. this._copy.rotation.x = 0;
  57608. this._copy.rotation.y = 0;
  57609. this._copy.rotation.z = 0;
  57610. this._copy.rotationQuaternion = null;
  57611. this._copy.scaling.x = 1;
  57612. this._copy.scaling.y = 1;
  57613. this._copy.scaling.z = 1;
  57614. this._copy.uvs.x = 0;
  57615. this._copy.uvs.y = 0;
  57616. this._copy.uvs.z = 1;
  57617. this._copy.uvs.w = 1;
  57618. this._copy.color = null;
  57619. };
  57620. // _meshBuilder : inserts the shape model in the global SPS mesh
  57621. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  57622. var i;
  57623. var u = 0;
  57624. var c = 0;
  57625. this._resetCopy();
  57626. if (options && options.positionFunction) {
  57627. options.positionFunction(this._copy, idx, idxInShape);
  57628. }
  57629. if (this._copy.rotationQuaternion) {
  57630. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57631. }
  57632. else {
  57633. this._yaw = this._copy.rotation.y;
  57634. this._pitch = this._copy.rotation.x;
  57635. this._roll = this._copy.rotation.z;
  57636. this._quaternionRotationYPR();
  57637. }
  57638. this._quaternionToRotationMatrix();
  57639. for (i = 0; i < shape.length; i++) {
  57640. this._vertex.x = shape[i].x;
  57641. this._vertex.y = shape[i].y;
  57642. this._vertex.z = shape[i].z;
  57643. if (options && options.vertexFunction) {
  57644. options.vertexFunction(this._copy, this._vertex, i);
  57645. }
  57646. this._vertex.x *= this._copy.scaling.x;
  57647. this._vertex.y *= this._copy.scaling.y;
  57648. this._vertex.z *= this._copy.scaling.z;
  57649. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57650. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57651. if (meshUV) {
  57652. 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);
  57653. u += 2;
  57654. }
  57655. if (this._copy.color) {
  57656. this._color = this._copy.color;
  57657. }
  57658. else if (meshCol && meshCol[c] !== undefined) {
  57659. this._color.r = meshCol[c];
  57660. this._color.g = meshCol[c + 1];
  57661. this._color.b = meshCol[c + 2];
  57662. this._color.a = meshCol[c + 3];
  57663. }
  57664. else {
  57665. this._color.r = 1;
  57666. this._color.g = 1;
  57667. this._color.b = 1;
  57668. this._color.a = 1;
  57669. }
  57670. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57671. c += 4;
  57672. }
  57673. for (i = 0; i < meshInd.length; i++) {
  57674. indices.push(p + meshInd[i]);
  57675. }
  57676. if (this._pickable) {
  57677. var nbfaces = meshInd.length / 3;
  57678. for (i = 0; i < nbfaces; i++) {
  57679. this.pickedParticles.push({ idx: idx, faceId: i });
  57680. }
  57681. }
  57682. };
  57683. // returns a shape array from positions array
  57684. SolidParticleSystem.prototype._posToShape = function (positions) {
  57685. var shape = [];
  57686. for (var i = 0; i < positions.length; i += 3) {
  57687. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57688. }
  57689. return shape;
  57690. };
  57691. // returns a shapeUV array from a Vector4 uvs
  57692. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57693. var shapeUV = [];
  57694. if (uvs) {
  57695. for (var i = 0; i < uvs.length; i++)
  57696. shapeUV.push(uvs[i]);
  57697. }
  57698. return shapeUV;
  57699. };
  57700. // adds a new particle object in the particles array
  57701. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  57702. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  57703. };
  57704. /**
  57705. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57706. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57707. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  57708. * `nb` (positive integer) the number of particles to be created from this model
  57709. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  57710. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  57711. */
  57712. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57713. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57714. var meshInd = mesh.getIndices();
  57715. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57716. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57717. var shape = this._posToShape(meshPos);
  57718. var shapeUV = this._uvsToShapeUV(meshUV);
  57719. var posfunc = options ? options.positionFunction : null;
  57720. var vtxfunc = options ? options.vertexFunction : null;
  57721. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  57722. // particles
  57723. var idx = this.nbParticles;
  57724. for (var i = 0; i < nb; i++) {
  57725. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  57726. if (this._updatable) {
  57727. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  57728. }
  57729. this._index += shape.length;
  57730. idx++;
  57731. }
  57732. this.nbParticles += nb;
  57733. this._shapeCounter++;
  57734. return this._shapeCounter - 1;
  57735. };
  57736. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57737. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57738. this._resetCopy();
  57739. if (particle._model._positionFunction) {
  57740. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57741. }
  57742. if (this._copy.rotationQuaternion) {
  57743. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57744. }
  57745. else {
  57746. this._yaw = this._copy.rotation.y;
  57747. this._pitch = this._copy.rotation.x;
  57748. this._roll = this._copy.rotation.z;
  57749. this._quaternionRotationYPR();
  57750. }
  57751. this._quaternionToRotationMatrix();
  57752. this._shape = particle._model._shape;
  57753. for (var pt = 0; pt < this._shape.length; pt++) {
  57754. this._vertex.x = this._shape[pt].x;
  57755. this._vertex.y = this._shape[pt].y;
  57756. this._vertex.z = this._shape[pt].z;
  57757. if (particle._model._vertexFunction) {
  57758. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57759. }
  57760. this._vertex.x *= this._copy.scaling.x;
  57761. this._vertex.y *= this._copy.scaling.y;
  57762. this._vertex.z *= this._copy.scaling.z;
  57763. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57764. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57765. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57766. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57767. }
  57768. particle.position.x = 0;
  57769. particle.position.y = 0;
  57770. particle.position.z = 0;
  57771. particle.rotation.x = 0;
  57772. particle.rotation.y = 0;
  57773. particle.rotation.z = 0;
  57774. particle.rotationQuaternion = null;
  57775. particle.scaling.x = 1;
  57776. particle.scaling.y = 1;
  57777. particle.scaling.z = 1;
  57778. };
  57779. /**
  57780. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57781. */
  57782. SolidParticleSystem.prototype.rebuildMesh = function () {
  57783. for (var p = 0; p < this.particles.length; p++) {
  57784. this._rebuildParticle(this.particles[p]);
  57785. }
  57786. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57787. };
  57788. /**
  57789. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57790. * This method calls `updateParticle()` for each particle of the SPS.
  57791. * For an animated SPS, it is usually called within the render loop.
  57792. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57793. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57794. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57795. */
  57796. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57797. if (start === void 0) { start = 0; }
  57798. if (end === void 0) { end = this.nbParticles - 1; }
  57799. if (update === void 0) { update = true; }
  57800. if (!this._updatable) {
  57801. return;
  57802. }
  57803. // custom beforeUpdate
  57804. this.beforeUpdateParticles(start, end, update);
  57805. this._cam_axisX.x = 1.0;
  57806. this._cam_axisX.y = 0.0;
  57807. this._cam_axisX.z = 0.0;
  57808. this._cam_axisY.x = 0.0;
  57809. this._cam_axisY.y = 1.0;
  57810. this._cam_axisY.z = 0.0;
  57811. this._cam_axisZ.x = 0.0;
  57812. this._cam_axisZ.y = 0.0;
  57813. this._cam_axisZ.z = 1.0;
  57814. // if the particles will always face the camera
  57815. if (this.billboard) {
  57816. // compute the camera position and un-rotate it by the current mesh rotation
  57817. this._yaw = this.mesh.rotation.y;
  57818. this._pitch = this.mesh.rotation.x;
  57819. this._roll = this.mesh.rotation.z;
  57820. this._quaternionRotationYPR();
  57821. this._quaternionToRotationMatrix();
  57822. this._rotMatrix.invertToRef(this._invertMatrix);
  57823. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  57824. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57825. this._cam_axisZ.normalize();
  57826. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  57827. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  57828. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57829. this._cam_axisY.normalize();
  57830. this._cam_axisX.normalize();
  57831. }
  57832. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57833. var idx = 0;
  57834. var index = 0;
  57835. var colidx = 0;
  57836. var colorIndex = 0;
  57837. var uvidx = 0;
  57838. var uvIndex = 0;
  57839. var pt = 0;
  57840. if (this._computeBoundingBox) {
  57841. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57842. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57843. }
  57844. // particle loop
  57845. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  57846. for (var p = start; p <= end; p++) {
  57847. this._particle = this.particles[p];
  57848. this._shape = this._particle._model._shape;
  57849. this._shapeUV = this._particle._model._shapeUV;
  57850. // call to custom user function to update the particle properties
  57851. this.updateParticle(this._particle);
  57852. if (this._particle.isVisible) {
  57853. // particle rotation matrix
  57854. if (this.billboard) {
  57855. this._particle.rotation.x = 0.0;
  57856. this._particle.rotation.y = 0.0;
  57857. }
  57858. if (this._computeParticleRotation || this.billboard) {
  57859. if (this._particle.rotationQuaternion) {
  57860. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57861. }
  57862. else {
  57863. this._yaw = this._particle.rotation.y;
  57864. this._pitch = this._particle.rotation.x;
  57865. this._roll = this._particle.rotation.z;
  57866. this._quaternionRotationYPR();
  57867. }
  57868. this._quaternionToRotationMatrix();
  57869. }
  57870. // particle vertex loop
  57871. for (pt = 0; pt < this._shape.length; pt++) {
  57872. idx = index + pt * 3;
  57873. colidx = colorIndex + pt * 4;
  57874. uvidx = uvIndex + pt * 2;
  57875. this._vertex.x = this._shape[pt].x;
  57876. this._vertex.y = this._shape[pt].y;
  57877. this._vertex.z = this._shape[pt].z;
  57878. if (this._computeParticleVertex) {
  57879. this.updateParticleVertex(this._particle, this._vertex, pt);
  57880. }
  57881. // positions
  57882. this._vertex.x *= this._particle.scaling.x;
  57883. this._vertex.y *= this._particle.scaling.y;
  57884. this._vertex.z *= this._particle.scaling.z;
  57885. 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];
  57886. 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;
  57887. 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;
  57888. 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;
  57889. 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;
  57890. 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;
  57891. 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;
  57892. if (this._computeBoundingBox) {
  57893. if (this._positions32[idx] < this._minimum.x) {
  57894. this._minimum.x = this._positions32[idx];
  57895. }
  57896. if (this._positions32[idx] > this._maximum.x) {
  57897. this._maximum.x = this._positions32[idx];
  57898. }
  57899. if (this._positions32[idx + 1] < this._minimum.y) {
  57900. this._minimum.y = this._positions32[idx + 1];
  57901. }
  57902. if (this._positions32[idx + 1] > this._maximum.y) {
  57903. this._maximum.y = this._positions32[idx + 1];
  57904. }
  57905. if (this._positions32[idx + 2] < this._minimum.z) {
  57906. this._minimum.z = this._positions32[idx + 2];
  57907. }
  57908. if (this._positions32[idx + 2] > this._maximum.z) {
  57909. this._maximum.z = this._positions32[idx + 2];
  57910. }
  57911. }
  57912. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  57913. if (!this._computeParticleVertex) {
  57914. this._normal.x = this._fixedNormal32[idx];
  57915. this._normal.y = this._fixedNormal32[idx + 1];
  57916. this._normal.z = this._fixedNormal32[idx + 2];
  57917. 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];
  57918. 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;
  57919. 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;
  57920. 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;
  57921. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  57922. 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;
  57923. 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;
  57924. }
  57925. if (this._computeParticleColor) {
  57926. this._colors32[colidx] = this._particle.color.r;
  57927. this._colors32[colidx + 1] = this._particle.color.g;
  57928. this._colors32[colidx + 2] = this._particle.color.b;
  57929. this._colors32[colidx + 3] = this._particle.color.a;
  57930. }
  57931. if (this._computeParticleTexture) {
  57932. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57933. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57934. }
  57935. }
  57936. }
  57937. else {
  57938. for (pt = 0; pt < this._shape.length; pt++) {
  57939. idx = index + pt * 3;
  57940. colidx = colorIndex + pt * 4;
  57941. uvidx = uvIndex + pt * 2;
  57942. this._positions32[idx] = this._camera.position.x;
  57943. this._positions32[idx + 1] = this._camera.position.y;
  57944. this._positions32[idx + 2] = this._camera.position.z;
  57945. this._normals32[idx] = 0.0;
  57946. this._normals32[idx + 1] = 0.0;
  57947. this._normals32[idx + 2] = 0.0;
  57948. if (this._computeParticleColor) {
  57949. this._colors32[colidx] = this._particle.color.r;
  57950. this._colors32[colidx + 1] = this._particle.color.g;
  57951. this._colors32[colidx + 2] = this._particle.color.b;
  57952. this._colors32[colidx + 3] = this._particle.color.a;
  57953. }
  57954. if (this._computeParticleTexture) {
  57955. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57956. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57957. }
  57958. }
  57959. }
  57960. // increment indexes for the next particle
  57961. index = idx + 3;
  57962. colorIndex = colidx + 4;
  57963. uvIndex = uvidx + 2;
  57964. }
  57965. // if the VBO must be updated
  57966. if (update) {
  57967. if (this._computeParticleColor) {
  57968. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57969. }
  57970. if (this._computeParticleTexture) {
  57971. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57972. }
  57973. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57974. if (!this.mesh.areNormalsFrozen) {
  57975. if (this._computeParticleVertex) {
  57976. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57977. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  57978. for (var i = 0; i < this._normals32.length; i++) {
  57979. this._fixedNormal32[i] = this._normals32[i];
  57980. }
  57981. }
  57982. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57983. }
  57984. }
  57985. if (this._computeBoundingBox) {
  57986. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57987. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57988. }
  57989. this.afterUpdateParticles(start, end, update);
  57990. };
  57991. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57992. this._halfroll = this._roll * 0.5;
  57993. this._halfpitch = this._pitch * 0.5;
  57994. this._halfyaw = this._yaw * 0.5;
  57995. this._sinRoll = Math.sin(this._halfroll);
  57996. this._cosRoll = Math.cos(this._halfroll);
  57997. this._sinPitch = Math.sin(this._halfpitch);
  57998. this._cosPitch = Math.cos(this._halfpitch);
  57999. this._sinYaw = Math.sin(this._halfyaw);
  58000. this._cosYaw = Math.cos(this._halfyaw);
  58001. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  58002. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  58003. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  58004. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  58005. };
  58006. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58007. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58008. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58009. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58010. this._rotMatrix.m[3] = 0;
  58011. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58012. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58013. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58014. this._rotMatrix.m[7] = 0;
  58015. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58016. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58017. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58018. this._rotMatrix.m[11] = 0;
  58019. this._rotMatrix.m[12] = 0;
  58020. this._rotMatrix.m[13] = 0;
  58021. this._rotMatrix.m[14] = 0;
  58022. this._rotMatrix.m[15] = 1.0;
  58023. };
  58024. /**
  58025. * Disposes the SPS
  58026. */
  58027. SolidParticleSystem.prototype.dispose = function () {
  58028. this.mesh.dispose();
  58029. this.vars = null;
  58030. // drop references to internal big arrays for the GC
  58031. this._positions = null;
  58032. this._indices = null;
  58033. this._normals = null;
  58034. this._uvs = null;
  58035. this._colors = null;
  58036. this._positions32 = null;
  58037. this._normals32 = null;
  58038. this._fixedNormal32 = null;
  58039. this._uvs32 = null;
  58040. this._colors32 = null;
  58041. this.pickedParticles = null;
  58042. };
  58043. /**
  58044. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58045. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58046. */
  58047. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58048. if (!this._isVisibilityBoxLocked) {
  58049. this.mesh.refreshBoundingInfo();
  58050. }
  58051. };
  58052. /**
  58053. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58054. * @param size the size (float) of the visibility box
  58055. * note : this doesn't lock the SPS mesh bounding box.
  58056. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58057. */
  58058. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58059. var vis = size / 2;
  58060. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58061. };
  58062. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58063. // getter and setter
  58064. get: function () {
  58065. return this._alwaysVisible;
  58066. },
  58067. /**
  58068. * Sets the SPS as always visible or not
  58069. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58070. */
  58071. set: function (val) {
  58072. this._alwaysVisible = val;
  58073. this.mesh.alwaysSelectAsActiveMesh = val;
  58074. },
  58075. enumerable: true,
  58076. configurable: true
  58077. });
  58078. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58079. get: function () {
  58080. return this._isVisibilityBoxLocked;
  58081. },
  58082. /**
  58083. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58084. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58085. */
  58086. set: function (val) {
  58087. this._isVisibilityBoxLocked = val;
  58088. this.mesh.getBoundingInfo().isLocked = val;
  58089. },
  58090. enumerable: true,
  58091. configurable: true
  58092. });
  58093. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58094. // getters
  58095. get: function () {
  58096. return this._computeParticleRotation;
  58097. },
  58098. // Optimizer setters
  58099. /**
  58100. * Tells to `setParticles()` to compute the particle rotations or not.
  58101. * Default value : true. The SPS is faster when it's set to false.
  58102. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58103. */
  58104. set: function (val) {
  58105. this._computeParticleRotation = val;
  58106. },
  58107. enumerable: true,
  58108. configurable: true
  58109. });
  58110. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58111. get: function () {
  58112. return this._computeParticleColor;
  58113. },
  58114. /**
  58115. * Tells to `setParticles()` to compute the particle colors or not.
  58116. * Default value : true. The SPS is faster when it's set to false.
  58117. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58118. */
  58119. set: function (val) {
  58120. this._computeParticleColor = val;
  58121. },
  58122. enumerable: true,
  58123. configurable: true
  58124. });
  58125. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58126. get: function () {
  58127. return this._computeParticleTexture;
  58128. },
  58129. /**
  58130. * Tells to `setParticles()` to compute the particle textures or not.
  58131. * Default value : true. The SPS is faster when it's set to false.
  58132. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58133. */
  58134. set: function (val) {
  58135. this._computeParticleTexture = val;
  58136. },
  58137. enumerable: true,
  58138. configurable: true
  58139. });
  58140. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58141. get: function () {
  58142. return this._computeParticleVertex;
  58143. },
  58144. /**
  58145. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58146. * Default value : false. The SPS is faster when it's set to false.
  58147. * Note : the particle custom vertex positions aren't stored values.
  58148. */
  58149. set: function (val) {
  58150. this._computeParticleVertex = val;
  58151. },
  58152. enumerable: true,
  58153. configurable: true
  58154. });
  58155. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58156. get: function () {
  58157. return this._computeBoundingBox;
  58158. },
  58159. /**
  58160. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58161. */
  58162. set: function (val) {
  58163. this._computeBoundingBox = val;
  58164. },
  58165. enumerable: true,
  58166. configurable: true
  58167. });
  58168. // =======================================================================
  58169. // Particle behavior logic
  58170. // these following methods may be overwritten by the user to fit his needs
  58171. /**
  58172. * This function does nothing. It may be overwritten to set all the particle first values.
  58173. * The SPS doesn't call this function, you may have to call it by your own.
  58174. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58175. */
  58176. SolidParticleSystem.prototype.initParticles = function () {
  58177. };
  58178. /**
  58179. * This function does nothing. It may be overwritten to recycle a particle.
  58180. * The SPS doesn't call this function, you may have to call it by your own.
  58181. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58182. */
  58183. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58184. return particle;
  58185. };
  58186. /**
  58187. * Updates a particle : this function should be overwritten by the user.
  58188. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58189. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58190. * ex : just set a particle position or velocity and recycle conditions
  58191. */
  58192. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58193. return particle;
  58194. };
  58195. /**
  58196. * Updates a vertex of a particle : it can be overwritten by the user.
  58197. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58198. * @param particle the current particle
  58199. * @param vertex the current index of the current particle
  58200. * @param pt the index of the current vertex in the particle shape
  58201. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58202. * ex : just set a vertex particle position
  58203. */
  58204. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58205. return vertex;
  58206. };
  58207. /**
  58208. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58209. * This does nothing and may be overwritten by the user.
  58210. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58211. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58212. * @param update the boolean update value actually passed to setParticles()
  58213. */
  58214. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58215. };
  58216. /**
  58217. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58218. * This will be passed three parameters.
  58219. * This does nothing and may be overwritten by the user.
  58220. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58221. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58222. * @param update the boolean update value actually passed to setParticles()
  58223. */
  58224. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58225. };
  58226. return SolidParticleSystem;
  58227. })();
  58228. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58229. })(BABYLON || (BABYLON = {}));
  58230. var BABYLON;
  58231. (function (BABYLON) {
  58232. var Internals;
  58233. (function (Internals) {
  58234. var FileFaceOrientation = (function () {
  58235. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  58236. this.name = name;
  58237. this.worldAxisForNormal = worldAxisForNormal;
  58238. this.worldAxisForFileX = worldAxisForFileX;
  58239. this.worldAxisForFileY = worldAxisForFileY;
  58240. }
  58241. return FileFaceOrientation;
  58242. })();
  58243. ;
  58244. /**
  58245. * Helper class dealing with the extraction of spherical polynomial dataArray
  58246. * from a cube map.
  58247. */
  58248. var CubeMapToSphericalPolynomialTools = (function () {
  58249. function CubeMapToSphericalPolynomialTools() {
  58250. }
  58251. /**
  58252. * Converts a cubemap to the according Spherical Polynomial data.
  58253. * This extracts the first 3 orders only as they are the only one used in the lighting.
  58254. *
  58255. * @param cubeInfo The Cube map to extract the information from.
  58256. * @return The Spherical Polynomial data.
  58257. */
  58258. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  58259. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  58260. var totalSolidAngle = 0.0;
  58261. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  58262. var du = 2.0 / cubeInfo.size;
  58263. var dv = du;
  58264. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  58265. var minUV = du * 0.5 - 1.0;
  58266. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58267. var fileFace = this.FileFaces[faceIndex];
  58268. var dataArray = cubeInfo[fileFace.name];
  58269. var v = minUV;
  58270. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  58271. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  58272. // Because SP is still linear, so summation is fine in that basis.
  58273. for (var y = 0; y < cubeInfo.size; y++) {
  58274. var u = minUV;
  58275. for (var x = 0; x < cubeInfo.size; x++) {
  58276. // World direction (not normalised)
  58277. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  58278. worldDirection.normalize();
  58279. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  58280. if (1) {
  58281. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  58282. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  58283. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  58284. var color = new BABYLON.Color3(r, g, b);
  58285. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  58286. }
  58287. else {
  58288. if (faceIndex == 0) {
  58289. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  58290. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  58291. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  58292. }
  58293. else if (faceIndex == 1) {
  58294. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  58295. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  58296. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  58297. }
  58298. else if (faceIndex == 2) {
  58299. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  58300. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  58301. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  58302. }
  58303. else if (faceIndex == 3) {
  58304. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  58305. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  58306. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  58307. }
  58308. else if (faceIndex == 4) {
  58309. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  58310. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  58311. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  58312. }
  58313. else if (faceIndex == 5) {
  58314. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  58315. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  58316. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  58317. }
  58318. 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]);
  58319. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  58320. }
  58321. totalSolidAngle += deltaSolidAngle;
  58322. u += du;
  58323. }
  58324. v += dv;
  58325. }
  58326. }
  58327. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  58328. var correction = correctSolidAngle / totalSolidAngle;
  58329. sphericalHarmonics.scale(correction);
  58330. // Additionally scale by pi -- audit needed
  58331. sphericalHarmonics.scale(1.0 / Math.PI);
  58332. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  58333. };
  58334. CubeMapToSphericalPolynomialTools.FileFaces = [
  58335. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  58336. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  58337. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  58338. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  58339. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  58340. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  58341. ];
  58342. return CubeMapToSphericalPolynomialTools;
  58343. })();
  58344. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  58345. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58346. })(BABYLON || (BABYLON = {}));
  58347. var BABYLON;
  58348. (function (BABYLON) {
  58349. var Internals;
  58350. (function (Internals) {
  58351. /**
  58352. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  58353. */
  58354. var PanoramaToCubeMapTools = (function () {
  58355. function PanoramaToCubeMapTools() {
  58356. }
  58357. /**
  58358. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  58359. *
  58360. * @param float32Array The source data.
  58361. * @param inputWidth The width of the input panorama.
  58362. * @param inputhHeight The height of the input panorama.
  58363. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  58364. * @return The cubemap data
  58365. */
  58366. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  58367. if (!float32Array) {
  58368. throw "ConvertPanoramaToCubemap: input cannot be null";
  58369. }
  58370. if (float32Array.length != inputWidth * inputHeight * 3) {
  58371. throw "ConvertPanoramaToCubemap: input size is wrong";
  58372. }
  58373. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  58374. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  58375. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  58376. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  58377. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  58378. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  58379. return {
  58380. front: textureFront,
  58381. back: textureBack,
  58382. left: textureLeft,
  58383. right: textureRight,
  58384. up: textureUp,
  58385. down: textureDown,
  58386. size: size
  58387. };
  58388. };
  58389. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  58390. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  58391. var textureArray = new Float32Array(buffer);
  58392. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  58393. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  58394. var dy = 1 / texSize;
  58395. var fy = 0;
  58396. for (var y = 0; y < texSize; y++) {
  58397. var xv1 = faceData[0];
  58398. var xv2 = faceData[2];
  58399. for (var x = 0; x < texSize; x++) {
  58400. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  58401. v.normalize();
  58402. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  58403. // 3 channels per pixels
  58404. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  58405. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  58406. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  58407. xv1 = xv1.add(rotDX1);
  58408. xv2 = xv2.add(rotDX2);
  58409. }
  58410. fy += dy;
  58411. }
  58412. return textureArray;
  58413. };
  58414. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  58415. var theta = Math.atan2(vDir.z, vDir.x);
  58416. var phi = Math.acos(vDir.y);
  58417. while (theta < -Math.PI)
  58418. theta += 2 * Math.PI;
  58419. while (theta > Math.PI)
  58420. theta -= 2 * Math.PI;
  58421. var dx = theta / Math.PI;
  58422. var dy = phi / Math.PI;
  58423. // recenter.
  58424. dx = dx * 0.5 + 0.5;
  58425. var px = Math.round(dx * inputWidth);
  58426. if (px < 0)
  58427. px = 0;
  58428. else if (px >= inputWidth)
  58429. px = inputWidth - 1;
  58430. var py = Math.round(dy * inputHeight);
  58431. if (py < 0)
  58432. py = 0;
  58433. else if (py >= inputHeight)
  58434. py = inputHeight - 1;
  58435. var inputY = (inputHeight - py - 1);
  58436. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  58437. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  58438. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  58439. return {
  58440. r: r,
  58441. g: g,
  58442. b: b
  58443. };
  58444. };
  58445. PanoramaToCubeMapTools.FACE_FRONT = [
  58446. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58447. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58448. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58449. new BABYLON.Vector3(1.0, 1.0, -1.0)
  58450. ];
  58451. PanoramaToCubeMapTools.FACE_BACK = [
  58452. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58453. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58454. new BABYLON.Vector3(1.0, 1.0, 1.0),
  58455. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  58456. ];
  58457. PanoramaToCubeMapTools.FACE_RIGHT = [
  58458. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58459. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58460. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58461. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58462. ];
  58463. PanoramaToCubeMapTools.FACE_LEFT = [
  58464. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58465. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58466. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58467. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  58468. ];
  58469. PanoramaToCubeMapTools.FACE_DOWN = [
  58470. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58471. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58472. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58473. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58474. ];
  58475. PanoramaToCubeMapTools.FACE_UP = [
  58476. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58477. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58478. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58479. new BABYLON.Vector3(1.0, -1.0, -1.0)
  58480. ];
  58481. return PanoramaToCubeMapTools;
  58482. })();
  58483. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  58484. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58485. })(BABYLON || (BABYLON = {}));
  58486. var BABYLON;
  58487. (function (BABYLON) {
  58488. var Internals;
  58489. (function (Internals) {
  58490. ;
  58491. /**
  58492. * This groups tools to convert HDR texture to native colors array.
  58493. */
  58494. var HDRTools = (function () {
  58495. function HDRTools() {
  58496. }
  58497. HDRTools.Ldexp = function (mantissa, exponent) {
  58498. if (exponent > 1023) {
  58499. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  58500. }
  58501. if (exponent < -1074) {
  58502. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  58503. }
  58504. return mantissa * Math.pow(2, exponent);
  58505. };
  58506. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  58507. if (exponent > 0) {
  58508. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  58509. float32array[index + 0] = red * exponent;
  58510. float32array[index + 1] = green * exponent;
  58511. float32array[index + 2] = blue * exponent;
  58512. }
  58513. else {
  58514. float32array[index + 0] = 0;
  58515. float32array[index + 1] = 0;
  58516. float32array[index + 2] = 0;
  58517. }
  58518. };
  58519. HDRTools.readStringLine = function (uint8array, startIndex) {
  58520. var line = "";
  58521. var character = "";
  58522. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  58523. character = String.fromCharCode(uint8array[i]);
  58524. if (character == "\n") {
  58525. break;
  58526. }
  58527. line += character;
  58528. }
  58529. return line;
  58530. };
  58531. /**
  58532. * Reads header information from an RGBE texture stored in a native array.
  58533. * More information on this format are available here:
  58534. * https://en.wikipedia.org/wiki/RGBE_image_format
  58535. *
  58536. * @param uint8array The binary file stored in native array.
  58537. * @return The header information.
  58538. */
  58539. HDRTools.RGBE_ReadHeader = function (uint8array) {
  58540. var height = 0;
  58541. var width = 0;
  58542. var line = this.readStringLine(uint8array, 0);
  58543. if (line[0] != '#' || line[1] != '?') {
  58544. throw "Bad HDR Format.";
  58545. }
  58546. var endOfHeader = false;
  58547. var findFormat = false;
  58548. var lineIndex = 0;
  58549. do {
  58550. lineIndex += (line.length + 1);
  58551. line = this.readStringLine(uint8array, lineIndex);
  58552. if (line == "FORMAT=32-bit_rle_rgbe") {
  58553. findFormat = true;
  58554. }
  58555. else if (line.length == 0) {
  58556. endOfHeader = true;
  58557. }
  58558. } while (!endOfHeader);
  58559. if (!findFormat) {
  58560. throw "HDR Bad header format, unsupported FORMAT";
  58561. }
  58562. lineIndex += (line.length + 1);
  58563. line = this.readStringLine(uint8array, lineIndex);
  58564. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  58565. var match = sizeRegexp.exec(line);
  58566. // TODO. Support +Y and -X if needed.
  58567. if (match.length < 3) {
  58568. throw "HDR Bad header format, no size";
  58569. }
  58570. width = parseInt(match[2]);
  58571. height = parseInt(match[1]);
  58572. if (width < 8 || width > 0x7fff) {
  58573. throw "HDR Bad header format, unsupported size";
  58574. }
  58575. lineIndex += (line.length + 1);
  58576. return {
  58577. height: height,
  58578. width: width,
  58579. dataPosition: lineIndex
  58580. };
  58581. };
  58582. /**
  58583. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  58584. * This RGBE texture needs to store the information as a panorama.
  58585. *
  58586. * More information on this format are available here:
  58587. * https://en.wikipedia.org/wiki/RGBE_image_format
  58588. *
  58589. * @param buffer The binary file stored in an array buffer.
  58590. * @param size The expected size of the extracted cubemap.
  58591. * @return The Cube Map information.
  58592. */
  58593. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  58594. var uint8array = new Uint8Array(buffer);
  58595. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  58596. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58597. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  58598. return cubeMapData;
  58599. };
  58600. /**
  58601. * Returns the pixels data extracted from an RGBE texture.
  58602. * This pixels will be stored left to right up to down in the R G B order in one array.
  58603. *
  58604. * More information on this format are available here:
  58605. * https://en.wikipedia.org/wiki/RGBE_image_format
  58606. *
  58607. * @param uint8array The binary file stored in an array buffer.
  58608. * @param hdrInfo The header information of the file.
  58609. * @return The pixels data in RGB right to left up to down order.
  58610. */
  58611. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  58612. // Keep for multi format supports.
  58613. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58614. };
  58615. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  58616. var num_scanlines = hdrInfo.height;
  58617. var scanline_width = hdrInfo.width;
  58618. var a, b, c, d, count;
  58619. var dataIndex = hdrInfo.dataPosition;
  58620. var index = 0, endIndex = 0, i = 0;
  58621. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  58622. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  58623. // 3 channels of 4 bytes per pixel in float.
  58624. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  58625. var resultArray = new Float32Array(resultBuffer);
  58626. // read in each successive scanline
  58627. while (num_scanlines > 0) {
  58628. a = uint8array[dataIndex++];
  58629. b = uint8array[dataIndex++];
  58630. c = uint8array[dataIndex++];
  58631. d = uint8array[dataIndex++];
  58632. if (a != 2 || b != 2 || (c & 0x80)) {
  58633. // this file is not run length encoded
  58634. throw "HDR Bad header format, not RLE";
  58635. }
  58636. if (((c << 8) | d) != scanline_width) {
  58637. throw "HDR Bad header format, wrong scan line width";
  58638. }
  58639. index = 0;
  58640. // read each of the four channels for the scanline into the buffer
  58641. for (i = 0; i < 4; i++) {
  58642. endIndex = (i + 1) * scanline_width;
  58643. while (index < endIndex) {
  58644. a = uint8array[dataIndex++];
  58645. b = uint8array[dataIndex++];
  58646. if (a > 128) {
  58647. // a run of the same value
  58648. count = a - 128;
  58649. if ((count == 0) || (count > endIndex - index)) {
  58650. throw "HDR Bad Format, bad scanline data (run)";
  58651. }
  58652. while (count-- > 0) {
  58653. scanLineArray[index++] = b;
  58654. }
  58655. }
  58656. else {
  58657. // a non-run
  58658. count = a;
  58659. if ((count == 0) || (count > endIndex - index)) {
  58660. throw "HDR Bad Format, bad scanline data (non-run)";
  58661. }
  58662. scanLineArray[index++] = b;
  58663. if (--count > 0) {
  58664. for (var j = 0; j < count; j++) {
  58665. scanLineArray[index++] = uint8array[dataIndex++];
  58666. }
  58667. }
  58668. }
  58669. }
  58670. }
  58671. // now convert data from buffer into floats
  58672. for (i = 0; i < scanline_width; i++) {
  58673. a = scanLineArray[i];
  58674. b = scanLineArray[i + scanline_width];
  58675. c = scanLineArray[i + 2 * scanline_width];
  58676. d = scanLineArray[i + 3 * scanline_width];
  58677. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  58678. }
  58679. num_scanlines--;
  58680. }
  58681. return resultArray;
  58682. };
  58683. return HDRTools;
  58684. })();
  58685. Internals.HDRTools = HDRTools;
  58686. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58687. })(BABYLON || (BABYLON = {}));
  58688. //_______________________________________________________________
  58689. // Extracted from CubeMapGen:
  58690. // https://code.google.com/archive/p/cubemapgen/
  58691. //
  58692. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  58693. //_______________________________________________________________
  58694. var BABYLON;
  58695. (function (BABYLON) {
  58696. var Internals;
  58697. (function (Internals) {
  58698. /**
  58699. * The bounding box information used during the conversion process.
  58700. */
  58701. var CMGBoundinBox = (function () {
  58702. function CMGBoundinBox() {
  58703. this.min = new BABYLON.Vector3(0, 0, 0);
  58704. this.max = new BABYLON.Vector3(0, 0, 0);
  58705. this.clear();
  58706. }
  58707. CMGBoundinBox.prototype.clear = function () {
  58708. this.min.x = CMGBoundinBox.MAX;
  58709. this.min.y = CMGBoundinBox.MAX;
  58710. this.min.z = CMGBoundinBox.MAX;
  58711. this.max.x = CMGBoundinBox.MIN;
  58712. this.max.y = CMGBoundinBox.MIN;
  58713. this.max.z = CMGBoundinBox.MIN;
  58714. };
  58715. CMGBoundinBox.prototype.augment = function (x, y, z) {
  58716. this.min.x = Math.min(this.min.x, x);
  58717. this.min.y = Math.min(this.min.y, y);
  58718. this.min.z = Math.min(this.min.z, z);
  58719. this.max.x = Math.max(this.max.x, x);
  58720. this.max.y = Math.max(this.max.y, y);
  58721. this.max.z = Math.max(this.max.z, z);
  58722. };
  58723. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  58724. this.min.x = Math.max(this.min.x, x);
  58725. this.min.y = Math.max(this.min.y, y);
  58726. this.min.z = Math.max(this.min.z, z);
  58727. };
  58728. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  58729. this.max.x = Math.min(this.max.x, x);
  58730. this.max.y = Math.min(this.max.y, y);
  58731. this.max.z = Math.min(this.max.z, z);
  58732. };
  58733. CMGBoundinBox.prototype.empty = function () {
  58734. if ((this.min.x > this.max.y) ||
  58735. (this.min.y > this.max.y) ||
  58736. (this.min.z > this.max.y)) {
  58737. return true;
  58738. }
  58739. else {
  58740. return false;
  58741. }
  58742. };
  58743. CMGBoundinBox.MAX = Number.MAX_VALUE;
  58744. CMGBoundinBox.MIN = Number.MIN_VALUE;
  58745. return CMGBoundinBox;
  58746. })();
  58747. /**
  58748. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  58749. * required by the glossinees of a material.
  58750. *
  58751. * This only supports the cosine drop power as well as Warp fixup generation method.
  58752. *
  58753. * This is using the process from CubeMapGen described here:
  58754. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  58755. */
  58756. var PMREMGenerator = (function () {
  58757. /**
  58758. * Constructor of the generator.
  58759. *
  58760. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  58761. * @param inputSize The size of the cubemap faces
  58762. * @param outputSize The size of the output cubemap faces
  58763. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  58764. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  58765. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  58766. * @param specularPower The max specular level of the desired cubemap
  58767. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  58768. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  58769. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  58770. */
  58771. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  58772. this.input = input;
  58773. this.inputSize = inputSize;
  58774. this.outputSize = outputSize;
  58775. this.maxNumMipLevels = maxNumMipLevels;
  58776. this.numChannels = numChannels;
  58777. this.isFloat = isFloat;
  58778. this.specularPower = specularPower;
  58779. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  58780. this.excludeBase = excludeBase;
  58781. this.fixup = fixup;
  58782. this._outputSurface = [];
  58783. this._numMipLevels = 0;
  58784. }
  58785. /**
  58786. * Launches the filter process and return the result.
  58787. *
  58788. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  58789. */
  58790. PMREMGenerator.prototype.filterCubeMap = function () {
  58791. // Init cubemap processor
  58792. this.init();
  58793. // Filters the cubemap
  58794. this.filterCubeMapMipChain();
  58795. // Returns the filtered mips.
  58796. return this._outputSurface;
  58797. };
  58798. PMREMGenerator.prototype.init = function () {
  58799. var i;
  58800. var j;
  58801. var mipLevelSize;
  58802. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  58803. if (this.maxNumMipLevels == 0) {
  58804. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  58805. }
  58806. //first miplevel size
  58807. mipLevelSize = this.outputSize;
  58808. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  58809. for (j = 0; j < this.maxNumMipLevels; j++) {
  58810. this._outputSurface.length++;
  58811. this._outputSurface[j] = [];
  58812. //Iterate over faces for output images
  58813. for (i = 0; i < 6; i++) {
  58814. this._outputSurface[j].length++;
  58815. // Initializes a new array for the output.
  58816. if (this.isFloat) {
  58817. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  58818. }
  58819. else {
  58820. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  58821. }
  58822. }
  58823. //next mip level is half size
  58824. mipLevelSize >>= 1;
  58825. this._numMipLevels++;
  58826. //terminate if mip chain becomes too small
  58827. if (mipLevelSize == 0) {
  58828. this.maxNumMipLevels = j;
  58829. return;
  58830. }
  58831. }
  58832. };
  58833. //--------------------------------------------------------------------------------------
  58834. //Cube map filtering and mip chain generation.
  58835. // the cube map filtereing is specified using a number of parameters:
  58836. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  58837. // indicates the region of the hemisphere to filter over for each tap.
  58838. //
  58839. // Note that the top mip level is also a filtered version of the original input images
  58840. // as well in order to create mip chains for diffuse environment illumination.
  58841. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  58842. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  58843. //
  58844. // Then the mip angle used to genreate the next level of the mip chain from the first level
  58845. // is a_InitialMipAngle
  58846. //
  58847. // The angle for the subsequent levels of the mip chain are specified by their parents
  58848. // filtering angle and a per-level scale and bias
  58849. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  58850. //
  58851. //--------------------------------------------------------------------------------------
  58852. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  58853. // First, take count of the lighting model to modify SpecularPower
  58854. // 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;
  58855. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  58856. //Cone angle start (for generating subsequent mip levels)
  58857. var currentSpecularPower = this.specularPower;
  58858. //Build filter lookup tables based on the source miplevel size
  58859. this.precomputeFilterLookupTables(this.inputSize);
  58860. // Note that we need to filter the first level before generating mipmap
  58861. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  58862. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  58863. // TODO : Write a function to copy and scale the base mipmap in output
  58864. // I am just lazy here and just put a high specular power value, and do some if.
  58865. if (this.excludeBase && (levelIndex == 0)) {
  58866. // 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).
  58867. currentSpecularPower = 100000.0;
  58868. }
  58869. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  58870. var srcCubeImage = this.input;
  58871. var dstCubeImage = this._outputSurface[levelIndex];
  58872. var dstSize = this.outputSize >> levelIndex;
  58873. // Compute required angle.
  58874. var angle = this.getBaseFilterAngle(currentSpecularPower);
  58875. // filter cube surfaces
  58876. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  58877. // fix seams
  58878. if (this.fixup) {
  58879. this.fixupCubeEdges(dstCubeImage, dstSize);
  58880. }
  58881. // Decrease the specular power to generate the mipmap chain
  58882. // TODO : Use another method for Exclude (see first comment at start of the function
  58883. if (this.excludeBase && (levelIndex == 0)) {
  58884. currentSpecularPower = this.specularPower;
  58885. }
  58886. currentSpecularPower *= this.cosinePowerDropPerMip;
  58887. }
  58888. };
  58889. //--------------------------------------------------------------------------------------
  58890. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  58891. // It allow to optimize the texel to access base on the specular power.
  58892. //--------------------------------------------------------------------------------------
  58893. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  58894. // We want to find the alpha such that:
  58895. // cos(alpha)^cosinePower = epsilon
  58896. // That's: acos(epsilon^(1/cosinePower))
  58897. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  58898. var angle = 180.0;
  58899. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  58900. angle *= 180.0 / Math.PI; // Convert to degree
  58901. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  58902. return angle;
  58903. };
  58904. //--------------------------------------------------------------------------------------
  58905. //Builds the following lookup tables prior to filtering:
  58906. // -normalizer cube map
  58907. // -tap weight lookup table
  58908. //
  58909. //--------------------------------------------------------------------------------------
  58910. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  58911. var srcTexelAngle;
  58912. var iCubeFace;
  58913. //clear pre-existing normalizer cube map
  58914. this._normCubeMap = [];
  58915. //Normalized vectors per cubeface and per-texel solid angle
  58916. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  58917. };
  58918. //--------------------------------------------------------------------------------------
  58919. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  58920. //
  58921. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  58922. //
  58923. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  58924. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  58925. // below
  58926. //--------------------------------------------------------------------------------------
  58927. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  58928. var iCubeFace;
  58929. var u;
  58930. var v;
  58931. //iterate over cube faces
  58932. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58933. //First three channels for norm cube, and last channel for solid angle
  58934. this._normCubeMap.push(new Float32Array(size * size * 4));
  58935. //fast texture walk, build normalizer cube map
  58936. var facesData = this.input[iCubeFace];
  58937. for (v = 0; v < size; v++) {
  58938. for (u = 0; u < size; u++) {
  58939. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  58940. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  58941. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  58942. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  58943. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  58944. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  58945. }
  58946. }
  58947. }
  58948. };
  58949. //--------------------------------------------------------------------------------------
  58950. // Convert cubemap face texel coordinates and face idx to 3D vector
  58951. // note the U and V coords are integer coords and range from 0 to size-1
  58952. // this routine can be used to generate a normalizer cube map
  58953. //--------------------------------------------------------------------------------------
  58954. // SL BEGIN
  58955. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  58956. var nvcU;
  58957. var nvcV;
  58958. var tempVec;
  58959. // Change from original AMD code
  58960. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  58961. // + 0.5f is for texel center addressing
  58962. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  58963. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  58964. // warp fixup
  58965. if (fixup && size > 1) {
  58966. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  58967. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  58968. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  58969. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  58970. }
  58971. // Get current vector
  58972. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  58973. // U contribution
  58974. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  58975. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  58976. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  58977. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  58978. // V contribution and Sum
  58979. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  58980. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  58981. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  58982. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  58983. //add face axis
  58984. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  58985. PMREMGenerator._vectorTemp.x += faceAxis[0];
  58986. PMREMGenerator._vectorTemp.y += faceAxis[1];
  58987. PMREMGenerator._vectorTemp.z += faceAxis[2];
  58988. //normalize vector
  58989. PMREMGenerator._vectorTemp.normalize();
  58990. return PMREMGenerator._vectorTemp;
  58991. };
  58992. //--------------------------------------------------------------------------------------
  58993. // Convert 3D vector to cubemap face texel coordinates and face idx
  58994. // note the U and V coords are integer coords and range from 0 to size-1
  58995. // this routine can be used to generate a normalizer cube map
  58996. //
  58997. // returns face IDX and texel coords
  58998. //--------------------------------------------------------------------------------------
  58999. // SL BEGIN
  59000. /*
  59001. Mapping Texture Coordinates to Cube Map Faces
  59002. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  59003. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  59004. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  59005. map arrangement in Pixar's RenderMan package.
  59006. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  59007. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  59008. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  59009. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  59010. the major axis direction). The target column in the table below explains how the major axis direction
  59011. maps to the 2D image of a particular cube map target.
  59012. major axis
  59013. direction target sc tc ma
  59014. ---------- --------------------------------- --- --- ---
  59015. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  59016. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  59017. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  59018. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  59019. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  59020. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  59021. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  59022. an updated (s,t) is calculated as follows
  59023. s = ( sc/|ma| + 1 ) / 2
  59024. t = ( tc/|ma| + 1 ) / 2
  59025. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  59026. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  59027. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  59028. */
  59029. // Note this method return U and V in range from 0 to size-1
  59030. // SL END
  59031. // Store the information in vector3 for convenience (faceindex, u, v)
  59032. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  59033. var maxCoord;
  59034. var faceIdx;
  59035. //absolute value 3
  59036. var absX = Math.abs(x);
  59037. var absY = Math.abs(y);
  59038. var absZ = Math.abs(z);
  59039. if (absX >= absY && absX >= absZ) {
  59040. maxCoord = absX;
  59041. if (x >= 0) {
  59042. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  59043. }
  59044. else {
  59045. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  59046. }
  59047. }
  59048. else if (absY >= absX && absY >= absZ) {
  59049. maxCoord = absY;
  59050. if (y >= 0) {
  59051. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  59052. }
  59053. else {
  59054. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  59055. }
  59056. }
  59057. else {
  59058. maxCoord = absZ;
  59059. if (z >= 0) {
  59060. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  59061. }
  59062. else {
  59063. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  59064. }
  59065. }
  59066. //divide through by max coord so face vector lies on cube face
  59067. var scale = 1 / maxCoord;
  59068. x *= scale;
  59069. y *= scale;
  59070. z *= scale;
  59071. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  59072. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  59073. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  59074. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  59075. // Modify original AMD code to return value from 0 to Size - 1
  59076. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  59077. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  59078. PMREMGenerator._vectorTemp.x = faceIdx;
  59079. PMREMGenerator._vectorTemp.y = u;
  59080. PMREMGenerator._vectorTemp.z = v;
  59081. return PMREMGenerator._vectorTemp;
  59082. };
  59083. //--------------------------------------------------------------------------------------
  59084. //Original code from Ignacio CastaÒo
  59085. // This formula is from Manne ÷hrstrˆm's thesis.
  59086. // Take two coordiantes in the range [-1, 1] that define a portion of a
  59087. // cube face and return the area of the projection of that portion on the
  59088. // surface of the sphere.
  59089. //--------------------------------------------------------------------------------------
  59090. PMREMGenerator.prototype.areaElement = function (x, y) {
  59091. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  59092. };
  59093. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  59094. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  59095. // (+ 0.5f is for texel center addressing)
  59096. u = (2.0 * (u + 0.5) / size) - 1.0;
  59097. v = (2.0 * (v + 0.5) / size) - 1.0;
  59098. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  59099. var invResolution = 1.0 / size;
  59100. // U and V are the -1..1 texture coordinate on the current face.
  59101. // Get projected area for this texel
  59102. var x0 = u - invResolution;
  59103. var y0 = v - invResolution;
  59104. var x1 = u + invResolution;
  59105. var y1 = v + invResolution;
  59106. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  59107. return solidAngle;
  59108. };
  59109. //--------------------------------------------------------------------------------------
  59110. //The key to the speed of these filtering routines is to quickly define a per-face
  59111. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  59112. // Later these pixels are selectively processed based on their dot products to see if
  59113. // they reside within the filtering cone.
  59114. //
  59115. //This is done by computing the smallest per-texel angle to get a conservative estimate
  59116. // of the number of texels needed to be covered in width and height order to filter the
  59117. // region. the bounding box for the center taps face is defined first, and if the
  59118. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  59119. // defined next
  59120. //--------------------------------------------------------------------------------------
  59121. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  59122. // note that pixels within these regions may be rejected
  59123. // based on the anlge
  59124. var iCubeFace;
  59125. var u;
  59126. var v;
  59127. // bounding box per face to specify region to process
  59128. var filterExtents = [];
  59129. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  59130. filterExtents.push(new CMGBoundinBox());
  59131. }
  59132. // min angle a src texel can cover (in degrees)
  59133. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  59134. // angle about center tap to define filter cone
  59135. // filter angle is 1/2 the cone angle
  59136. var filterAngle = filterConeAngle / 2.0;
  59137. //ensure filter angle is larger than a texel
  59138. if (filterAngle < srcTexelAngle) {
  59139. filterAngle = srcTexelAngle;
  59140. }
  59141. //ensure filter cone is always smaller than the hemisphere
  59142. if (filterAngle > 90.0) {
  59143. filterAngle = 90.0;
  59144. }
  59145. // the maximum number of texels in 1D the filter cone angle will cover
  59146. // used to determine bounding box size for filter extents
  59147. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  59148. // ensure conservative region always covers at least one texel
  59149. if (filterSize < 1) {
  59150. filterSize = 1;
  59151. }
  59152. // dotProdThresh threshold based on cone angle to determine whether or not taps
  59153. // reside within the cone angle
  59154. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  59155. // process required faces
  59156. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  59157. //iterate over dst cube map face texel
  59158. for (v = 0; v < dstSize; v++) {
  59159. for (u = 0; u < dstSize; u++) {
  59160. //get center tap direction
  59161. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  59162. //clear old per-face filter extents
  59163. this.clearFilterExtents(filterExtents);
  59164. //define per-face filter extents
  59165. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  59166. //perform filtering of src faces using filter extents
  59167. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  59168. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  59169. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  59170. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  59171. }
  59172. }
  59173. }
  59174. };
  59175. //--------------------------------------------------------------------------------------
  59176. //Clear filter extents for the 6 cube map faces
  59177. //--------------------------------------------------------------------------------------
  59178. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  59179. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  59180. filterExtents[iCubeFaces].clear();
  59181. }
  59182. };
  59183. //--------------------------------------------------------------------------------------
  59184. //Define per-face bounding box filter extents
  59185. //
  59186. // These define conservative texel regions in each of the faces the filter can possibly
  59187. // process. When the pixels in the regions are actually processed, the dot product
  59188. // between the tap vector and the center tap vector is used to determine the weight of
  59189. // the tap and whether or not the tap is within the cone.
  59190. //
  59191. //--------------------------------------------------------------------------------------
  59192. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  59193. //neighboring face and bleed over amount, and width of BBOX for
  59194. // left, right, top, and bottom edges of this face
  59195. var bleedOverAmount = [0, 0, 0, 0];
  59196. var bleedOverBBoxMin = [0, 0, 0, 0];
  59197. var bleedOverBBoxMax = [0, 0, 0, 0];
  59198. var neighborFace;
  59199. var neighborEdge;
  59200. var oppositeFaceIdx;
  59201. //get face idx, and u, v info from center tap dir
  59202. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  59203. var faceIdx = result.x;
  59204. var u = result.y;
  59205. var v = result.z;
  59206. //define bbox size within face
  59207. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  59208. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  59209. filterExtents[faceIdx].clampMin(0, 0, 0);
  59210. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  59211. //u and v extent in face corresponding to center tap
  59212. var minU = filterExtents[faceIdx].min.x;
  59213. var minV = filterExtents[faceIdx].min.y;
  59214. var maxU = filterExtents[faceIdx].max.x;
  59215. var maxV = filterExtents[faceIdx].max.y;
  59216. //bleed over amounts for face across u=0 edge (left)
  59217. bleedOverAmount[0] = (bboxSize - u);
  59218. bleedOverBBoxMin[0] = minV;
  59219. bleedOverBBoxMax[0] = maxV;
  59220. //bleed over amounts for face across u=1 edge (right)
  59221. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  59222. bleedOverBBoxMin[1] = minV;
  59223. bleedOverBBoxMax[1] = maxV;
  59224. //bleed over to face across v=0 edge (up)
  59225. bleedOverAmount[2] = (bboxSize - v);
  59226. bleedOverBBoxMin[2] = minU;
  59227. bleedOverBBoxMax[2] = maxU;
  59228. //bleed over to face across v=1 edge (down)
  59229. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  59230. bleedOverBBoxMin[3] = minU;
  59231. bleedOverBBoxMax[3] = maxU;
  59232. //compute bleed over regions in neighboring faces
  59233. for (var i = 0; i < 4; i++) {
  59234. if (bleedOverAmount[i] > 0) {
  59235. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  59236. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  59237. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  59238. // be flipped: the cases are
  59239. // if a left edge mates with a left or bottom edge on the neighbor
  59240. // if a top edge mates with a top or right edge on the neighbor
  59241. // if a right edge mates with a right or top edge on the neighbor
  59242. // if a bottom edge mates with a bottom or left edge on the neighbor
  59243. //Seeing as the edges are enumerated as follows
  59244. // left =0
  59245. // right =1
  59246. // top =2
  59247. // bottom =3
  59248. //
  59249. // so if the edge enums are the same, or the sum of the enums == 3,
  59250. // the bbox needs to be flipped
  59251. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  59252. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  59253. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  59254. }
  59255. //The way the bounding box is extended onto the neighboring face
  59256. // depends on which edge of neighboring face abuts with this one
  59257. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  59258. case PMREMGenerator.CP_EDGE_LEFT:
  59259. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  59260. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  59261. break;
  59262. case PMREMGenerator.CP_EDGE_RIGHT:
  59263. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  59264. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  59265. break;
  59266. case PMREMGenerator.CP_EDGE_TOP:
  59267. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  59268. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  59269. break;
  59270. case PMREMGenerator.CP_EDGE_BOTTOM:
  59271. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  59272. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  59273. break;
  59274. }
  59275. //clamp filter extents in non-center tap faces to remain within surface
  59276. filterExtents[neighborFace].clampMin(0, 0, 0);
  59277. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  59278. }
  59279. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  59280. // from the center tap face, then process the opposite face entirely for now.
  59281. //Note that the cases in which this happens, what usually happens is that
  59282. // more than one edge bleeds onto the opposite face, and the bounding box
  59283. // encompasses the entire cube map face.
  59284. if (bleedOverAmount[i] > srcSize) {
  59285. //determine opposite face
  59286. switch (faceIdx) {
  59287. case PMREMGenerator.CP_FACE_X_POS:
  59288. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  59289. break;
  59290. case PMREMGenerator.CP_FACE_X_NEG:
  59291. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  59292. break;
  59293. case PMREMGenerator.CP_FACE_Y_POS:
  59294. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  59295. break;
  59296. case PMREMGenerator.CP_FACE_Y_NEG:
  59297. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  59298. break;
  59299. case PMREMGenerator.CP_FACE_Z_POS:
  59300. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  59301. break;
  59302. case PMREMGenerator.CP_FACE_Z_NEG:
  59303. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  59304. break;
  59305. default:
  59306. break;
  59307. }
  59308. //just encompass entire face for now
  59309. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  59310. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  59311. }
  59312. }
  59313. };
  59314. //--------------------------------------------------------------------------------------
  59315. //ProcessFilterExtents
  59316. // Process bounding box in each cube face
  59317. //
  59318. //--------------------------------------------------------------------------------------
  59319. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  59320. //accumulators are 64-bit floats in order to have the precision needed
  59321. // over a summation of a large number of pixels
  59322. var dstAccum = [0, 0, 0, 0];
  59323. var weightAccum = 0;
  59324. var k = 0;
  59325. var nSrcChannels = this.numChannels;
  59326. // norm cube map and srcCubeMap have same face width
  59327. var faceWidth = srcSize;
  59328. //amount to add to pointer to move to next scanline in images
  59329. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  59330. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  59331. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  59332. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  59333. // iterate over cubefaces
  59334. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  59335. //if bbox is non empty
  59336. if (!filterExtents[iFaceIdx].empty()) {
  59337. var uStart = filterExtents[iFaceIdx].min.x;
  59338. var vStart = filterExtents[iFaceIdx].min.y;
  59339. var uEnd = filterExtents[iFaceIdx].max.x;
  59340. var vEnd = filterExtents[iFaceIdx].max.y;
  59341. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  59342. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  59343. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  59344. for (var v = vStart; v <= vEnd; v++) {
  59345. var normCubeRowWalk = 0;
  59346. var srcCubeRowWalk = 0;
  59347. for (var u = uStart; u <= uEnd; u++) {
  59348. //pointer to direction in cube map associated with texel
  59349. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  59350. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  59351. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  59352. //check dot product to see if texel is within cone
  59353. var tapDotProd = texelVectX * centerTapDir.x +
  59354. texelVectY * centerTapDir.y +
  59355. texelVectZ * centerTapDir.z;
  59356. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  59357. //solid angle stored in 4th channel of normalizer/solid angle cube map
  59358. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  59359. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  59360. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  59361. // so just adding one to specularpower do the trick.
  59362. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  59363. //iterate over channels
  59364. for (k = 0; k < nSrcChannels; k++) {
  59365. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  59366. srcCubeRowWalk++;
  59367. }
  59368. weightAccum += weight; //accumulate weight
  59369. }
  59370. else {
  59371. //step across source pixel
  59372. srcCubeRowWalk += nSrcChannels;
  59373. }
  59374. normCubeRowWalk += 4; // 4 channels per norm cube map.
  59375. }
  59376. startIndexNormCubeMap += normCubePitch;
  59377. startIndexSrcCubeMap += srcCubePitch;
  59378. }
  59379. }
  59380. }
  59381. //divide through by weights if weight is non zero
  59382. if (weightAccum != 0.0) {
  59383. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  59384. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  59385. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  59386. if (this.numChannels > 3) {
  59387. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  59388. }
  59389. }
  59390. else {
  59391. // otherwise sample nearest
  59392. // get face idx and u, v texel coordinate in face
  59393. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  59394. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  59395. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  59396. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  59397. if (this.numChannels > 3) {
  59398. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  59399. }
  59400. }
  59401. return PMREMGenerator._vectorTemp;
  59402. };
  59403. //--------------------------------------------------------------------------------------
  59404. // Fixup cube edges
  59405. //
  59406. // average texels on cube map faces across the edges
  59407. // WARP/BENT Method Only.
  59408. //--------------------------------------------------------------------------------------
  59409. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  59410. var k;
  59411. var j;
  59412. var i;
  59413. var iFace;
  59414. var iCorner = 0;
  59415. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  59416. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  59417. // note that if functionality to filter across the three texels for each corner, then
  59418. //indexed by corner and face idx. the array contains the face the start points belongs to.
  59419. var cornerPtr = [
  59420. [[], [], []],
  59421. [[], [], []],
  59422. [[], [], []],
  59423. [[], [], []],
  59424. [[], [], []],
  59425. [[], [], []],
  59426. [[], [], []],
  59427. [[], [], []]
  59428. ];
  59429. //if there is no fixup, or fixup width = 0, do nothing
  59430. if (cubeMapSize < 1) {
  59431. return;
  59432. }
  59433. //special case 1x1 cubemap, average face colors
  59434. if (cubeMapSize == 1) {
  59435. //iterate over channels
  59436. for (k = 0; k < this.numChannels; k++) {
  59437. var accum = 0.0;
  59438. //iterate over faces to accumulate face colors
  59439. for (iFace = 0; iFace < 6; iFace++) {
  59440. accum += cubeMap[iFace][k];
  59441. }
  59442. //compute average over 6 face colors
  59443. accum /= 6.0;
  59444. //iterate over faces to distribute face colors
  59445. for (iFace = 0; iFace < 6; iFace++) {
  59446. cubeMap[iFace][k] = accum;
  59447. }
  59448. }
  59449. return;
  59450. }
  59451. //iterate over faces to collect list of corner texel pointers
  59452. for (iFace = 0; iFace < 6; iFace++) {
  59453. //the 4 corner pointers for this face
  59454. faceCornerStartIndicies[0] = [iFace, 0];
  59455. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  59456. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  59457. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  59458. //iterate over face corners to collect cube corner pointers
  59459. for (iCorner = 0; iCorner < 4; iCorner++) {
  59460. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  59461. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  59462. cornerNumPtrs[corner]++;
  59463. }
  59464. }
  59465. //iterate over corners to average across corner tap values
  59466. for (iCorner = 0; iCorner < 8; iCorner++) {
  59467. for (k = 0; k < this.numChannels; k++) {
  59468. var cornerTapAccum = 0.0;
  59469. //iterate over corner texels and average results
  59470. for (i = 0; i < 3; i++) {
  59471. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  59472. }
  59473. //divide by 3 to compute average of corner tap values
  59474. cornerTapAccum *= (1.0 / 3.0);
  59475. //iterate over corner texels and average results
  59476. for (i = 0; i < 3; i++) {
  59477. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  59478. }
  59479. }
  59480. }
  59481. //iterate over the twelve edges of the cube to average across edges
  59482. for (i = 0; i < 12; i++) {
  59483. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  59484. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  59485. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  59486. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  59487. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  59488. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  59489. var edgeWalk = 0;
  59490. var neighborEdgeWalk = 0;
  59491. //Determine walking pointers based on edge type
  59492. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  59493. switch (edge) {
  59494. case PMREMGenerator.CP_EDGE_LEFT:
  59495. // no change to faceEdgeStartPtr
  59496. edgeWalk = this.numChannels * cubeMapSize;
  59497. break;
  59498. case PMREMGenerator.CP_EDGE_RIGHT:
  59499. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59500. edgeWalk = this.numChannels * cubeMapSize;
  59501. break;
  59502. case PMREMGenerator.CP_EDGE_TOP:
  59503. // no change to faceEdgeStartPtr
  59504. edgeWalk = this.numChannels;
  59505. break;
  59506. case PMREMGenerator.CP_EDGE_BOTTOM:
  59507. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  59508. edgeWalk = this.numChannels;
  59509. break;
  59510. }
  59511. //For certain types of edge abutments, the neighbor edge walk needs to
  59512. // be flipped: the cases are
  59513. // if a left edge mates with a left or bottom edge on the neighbor
  59514. // if a top edge mates with a top or right edge on the neighbor
  59515. // if a right edge mates with a right or top edge on the neighbor
  59516. // if a bottom edge mates with a bottom or left edge on the neighbor
  59517. //Seeing as the edges are enumerated as follows
  59518. // left =0
  59519. // right =1
  59520. // top =2
  59521. // bottom =3
  59522. //
  59523. //If the edge enums are the same, or the sum of the enums == 3,
  59524. // the neighbor edge walk needs to be flipped
  59525. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  59526. switch (neighborEdge) {
  59527. case PMREMGenerator.CP_EDGE_LEFT:
  59528. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  59529. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  59530. break;
  59531. case PMREMGenerator.CP_EDGE_RIGHT:
  59532. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  59533. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  59534. break;
  59535. case PMREMGenerator.CP_EDGE_TOP:
  59536. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59537. neighborEdgeWalk = -this.numChannels;
  59538. break;
  59539. case PMREMGenerator.CP_EDGE_BOTTOM:
  59540. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  59541. neighborEdgeWalk = -this.numChannels;
  59542. break;
  59543. }
  59544. }
  59545. else {
  59546. //swapped direction neighbor edge walk
  59547. switch (neighborEdge) {
  59548. case PMREMGenerator.CP_EDGE_LEFT:
  59549. //no change to neighborEdgeStartPtr for this case since it points
  59550. // to the upper left corner already
  59551. neighborEdgeWalk = this.numChannels * cubeMapSize;
  59552. break;
  59553. case PMREMGenerator.CP_EDGE_RIGHT:
  59554. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59555. neighborEdgeWalk = this.numChannels * cubeMapSize;
  59556. break;
  59557. case PMREMGenerator.CP_EDGE_TOP:
  59558. //no change to neighborEdgeStartPtr for this case since it points
  59559. // to the upper left corner already
  59560. neighborEdgeWalk = this.numChannels;
  59561. break;
  59562. case PMREMGenerator.CP_EDGE_BOTTOM:
  59563. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  59564. neighborEdgeWalk = this.numChannels;
  59565. break;
  59566. }
  59567. }
  59568. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  59569. //nearby neighborhood
  59570. //step ahead one texel on edge
  59571. edgeStartIndex += edgeWalk;
  59572. neighborEdgeStartIndex += neighborEdgeWalk;
  59573. // note that this loop does not process the corner texels, since they have already been
  59574. // averaged across faces across earlier
  59575. for (j = 1; j < (cubeMapSize - 1); j++) {
  59576. //for each set of taps along edge, average them
  59577. // and rewrite the results into the edges
  59578. for (k = 0; k < this.numChannels; k++) {
  59579. var edgeTap = cubeMap[face][edgeStartIndex + k];
  59580. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  59581. //compute average of tap intensity values
  59582. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  59583. //propagate average of taps to edge taps
  59584. cubeMap[face][edgeStartIndex + k] = avgTap;
  59585. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  59586. }
  59587. edgeStartIndex += edgeWalk;
  59588. neighborEdgeStartIndex += neighborEdgeWalk;
  59589. }
  59590. }
  59591. };
  59592. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  59593. PMREMGenerator.CP_UDIR = 0;
  59594. PMREMGenerator.CP_VDIR = 1;
  59595. PMREMGenerator.CP_FACEAXIS = 2;
  59596. //used to index cube faces
  59597. PMREMGenerator.CP_FACE_X_POS = 0;
  59598. PMREMGenerator.CP_FACE_X_NEG = 1;
  59599. PMREMGenerator.CP_FACE_Y_POS = 2;
  59600. PMREMGenerator.CP_FACE_Y_NEG = 3;
  59601. PMREMGenerator.CP_FACE_Z_POS = 4;
  59602. PMREMGenerator.CP_FACE_Z_NEG = 5;
  59603. //used to index image edges
  59604. // NOTE.. the actual number corresponding to the edge is important
  59605. // do not change these, or the code will break
  59606. //
  59607. // CP_EDGE_LEFT is u = 0
  59608. // CP_EDGE_RIGHT is u = width-1
  59609. // CP_EDGE_TOP is v = 0
  59610. // CP_EDGE_BOTTOM is v = height-1
  59611. PMREMGenerator.CP_EDGE_LEFT = 0;
  59612. PMREMGenerator.CP_EDGE_RIGHT = 1;
  59613. PMREMGenerator.CP_EDGE_TOP = 2;
  59614. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  59615. //corners of CUBE map (P or N specifys if it corresponds to the
  59616. // positive or negative direction each of X, Y, and Z
  59617. PMREMGenerator.CP_CORNER_NNN = 0;
  59618. PMREMGenerator.CP_CORNER_NNP = 1;
  59619. PMREMGenerator.CP_CORNER_NPN = 2;
  59620. PMREMGenerator.CP_CORNER_NPP = 3;
  59621. PMREMGenerator.CP_CORNER_PNN = 4;
  59622. PMREMGenerator.CP_CORNER_PNP = 5;
  59623. PMREMGenerator.CP_CORNER_PPN = 6;
  59624. PMREMGenerator.CP_CORNER_PPP = 7;
  59625. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  59626. //3x2 matrices that map cube map indexing vectors in 3d
  59627. // (after face selection and divide through by the
  59628. // _ABSOLUTE VALUE_ of the max coord)
  59629. // into NVC space
  59630. //Note this currently assumes the D3D cube face ordering and orientation
  59631. PMREMGenerator._sgFace2DMapping = [
  59632. //XPOS face
  59633. [[0, 0, -1],
  59634. [0, -1, 0],
  59635. [1, 0, 0]],
  59636. //XNEG face
  59637. [[0, 0, 1],
  59638. [0, -1, 0],
  59639. [-1, 0, 0]],
  59640. //YPOS face
  59641. [[1, 0, 0],
  59642. [0, 0, 1],
  59643. [0, 1, 0]],
  59644. //YNEG face
  59645. [[1, 0, 0],
  59646. [0, 0, -1],
  59647. [0, -1, 0]],
  59648. //ZPOS face
  59649. [[1, 0, 0],
  59650. [0, -1, 0],
  59651. [0, 0, 1]],
  59652. //ZNEG face
  59653. [[-1, 0, 0],
  59654. [0, -1, 0],
  59655. [0, 0, -1]],
  59656. ];
  59657. //------------------------------------------------------------------------------
  59658. // D3D cube map face specification
  59659. // mapping from 3D x,y,z cube map lookup coordinates
  59660. // to 2D within face u,v coordinates
  59661. //
  59662. // --------------------> U direction
  59663. // | (within-face texture space)
  59664. // | _____
  59665. // | | |
  59666. // | | +Y |
  59667. // | _____|_____|_____ _____
  59668. // | | | | | |
  59669. // | | -X | +Z | +X | -Z |
  59670. // | |_____|_____|_____|_____|
  59671. // | | |
  59672. // | | -Y |
  59673. // | |_____|
  59674. // |
  59675. // v V direction
  59676. // (within-face texture space)
  59677. //------------------------------------------------------------------------------
  59678. //Information about neighbors and how texture coorrdinates change across faces
  59679. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  59680. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  59681. //Note this currently assumes the D3D cube face ordering and orientation
  59682. PMREMGenerator._sgCubeNgh = [
  59683. //XPOS face
  59684. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59685. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59686. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59687. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  59688. //XNEG face
  59689. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59690. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  59691. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  59692. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  59693. //YPOS face
  59694. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  59695. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  59696. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  59697. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  59698. //YNEG face
  59699. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  59700. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59701. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59702. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  59703. //ZPOS face
  59704. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59705. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  59706. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59707. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  59708. //ZNEG face
  59709. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59710. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59711. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  59712. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  59713. ];
  59714. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  59715. // this table is used to average over the edges.
  59716. PMREMGenerator._sgCubeEdgeList = [
  59717. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  59718. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59719. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  59720. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59721. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59722. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59723. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  59724. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  59725. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  59726. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59727. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  59728. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  59729. ];
  59730. //Information about which of the 8 cube corners are correspond to the
  59731. // the 4 corners in each cube face
  59732. // the order is upper left, upper right, lower left, lower right
  59733. PMREMGenerator._sgCubeCornerList = [
  59734. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  59735. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  59736. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  59737. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  59738. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  59739. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  59740. ];
  59741. return PMREMGenerator;
  59742. })();
  59743. Internals.PMREMGenerator = PMREMGenerator;
  59744. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59745. })(BABYLON || (BABYLON = {}));
  59746. var BABYLON;
  59747. (function (BABYLON) {
  59748. /**
  59749. * This represents a texture coming from an HDR input.
  59750. *
  59751. * The only supported format is currently panorama picture stored in RGBE format.
  59752. * Example of such files can be found on HDRLib: http://hdrlib.com/
  59753. */
  59754. var HDRCubeTexture = (function (_super) {
  59755. __extends(HDRCubeTexture, _super);
  59756. /**
  59757. * Instantiates an HDRTexture from the following parameters.
  59758. *
  59759. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  59760. * @param scene The scene the texture will be used in
  59761. * @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.
  59762. * @param noMipmap Forces to not generate the mipmap if true
  59763. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  59764. * @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)
  59765. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  59766. */
  59767. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  59768. if (noMipmap === void 0) { noMipmap = false; }
  59769. if (generateHarmonics === void 0) { generateHarmonics = true; }
  59770. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  59771. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  59772. _super.call(this, scene);
  59773. this._useInGammaSpace = false;
  59774. this._generateHarmonics = true;
  59775. this._isBABYLONPreprocessed = false;
  59776. /**
  59777. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  59778. */
  59779. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  59780. /**
  59781. * The spherical polynomial data extracted from the texture.
  59782. */
  59783. this.sphericalPolynomial = null;
  59784. /**
  59785. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  59786. * This is usefull at run time to apply the good shader.
  59787. */
  59788. this.isPMREM = false;
  59789. if (!url) {
  59790. return;
  59791. }
  59792. this.name = url;
  59793. this.url = url;
  59794. this.hasAlpha = false;
  59795. this.isCube = true;
  59796. this._textureMatrix = BABYLON.Matrix.Identity();
  59797. if (size) {
  59798. this._isBABYLONPreprocessed = false;
  59799. this._noMipmap = noMipmap;
  59800. this._size = size;
  59801. this._useInGammaSpace = useInGammaSpace;
  59802. this._usePMREMGenerator = usePMREMGenerator &&
  59803. scene.getEngine().getCaps().textureLOD &&
  59804. this.getScene().getEngine().getCaps().textureFloat &&
  59805. !this._useInGammaSpace;
  59806. }
  59807. else {
  59808. this._isBABYLONPreprocessed = true;
  59809. this._noMipmap = false;
  59810. this._useInGammaSpace = false;
  59811. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  59812. this.getScene().getEngine().getCaps().textureFloat &&
  59813. !this._useInGammaSpace;
  59814. }
  59815. this.isPMREM = this._usePMREMGenerator;
  59816. this._texture = this._getFromCache(url, this._noMipmap);
  59817. if (!this._texture) {
  59818. if (!scene.useDelayedTextureLoading) {
  59819. this.loadTexture();
  59820. }
  59821. else {
  59822. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59823. }
  59824. }
  59825. }
  59826. /**
  59827. * Occurs when the file is a preprocessed .babylon.hdr file.
  59828. */
  59829. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  59830. var _this = this;
  59831. var mipLevels = 0;
  59832. var floatArrayView = null;
  59833. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  59834. var mips = [];
  59835. var startIndex = 30;
  59836. for (var level = 0; level < mipLevels; level++) {
  59837. mips.push([]);
  59838. // Fill each pixel of the mip level.
  59839. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  59840. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59841. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  59842. mips[level].push(faceData);
  59843. startIndex += faceSize;
  59844. }
  59845. }
  59846. return mips;
  59847. } : null;
  59848. var callback = function (buffer) {
  59849. // Create Native Array Views
  59850. var intArrayView = new Int32Array(buffer);
  59851. floatArrayView = new Float32Array(buffer);
  59852. // Fill header.
  59853. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  59854. _this._size = intArrayView[1]; // CubeMap max mip face size.
  59855. // Update Texture Information.
  59856. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  59857. // Fill polynomial information.
  59858. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  59859. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  59860. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  59861. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  59862. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  59863. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  59864. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  59865. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  59866. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  59867. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  59868. // Fill pixel data.
  59869. mipLevels = intArrayView[29]; // Number of mip levels.
  59870. var startIndex = 30;
  59871. var data = [];
  59872. var faceSize = Math.pow(_this._size, 2) * 3;
  59873. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59874. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  59875. startIndex += faceSize;
  59876. }
  59877. var results = [];
  59878. var byteArray = null;
  59879. // Push each faces.
  59880. for (var k = 0; k < 6; k++) {
  59881. var dataFace = null;
  59882. // If special cases.
  59883. if (!mipmapGenerator) {
  59884. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  59885. dataFace = data[j];
  59886. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59887. // 3 channels of 1 bytes per pixel in bytes.
  59888. var byteBuffer = new ArrayBuffer(faceSize);
  59889. byteArray = new Uint8Array(byteBuffer);
  59890. }
  59891. for (var i = 0; i < _this._size * _this._size; i++) {
  59892. // Put in gamma space if requested.
  59893. if (_this._useInGammaSpace) {
  59894. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59895. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59896. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59897. }
  59898. // Convert to int texture for fallback.
  59899. if (byteArray) {
  59900. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59901. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59902. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59903. // May use luminance instead if the result is not accurate.
  59904. var max = Math.max(Math.max(r, g), b);
  59905. if (max > 255) {
  59906. var scale = 255 / max;
  59907. r *= scale;
  59908. g *= scale;
  59909. b *= scale;
  59910. }
  59911. byteArray[(i * 3) + 0] = r;
  59912. byteArray[(i * 3) + 1] = g;
  59913. byteArray[(i * 3) + 2] = b;
  59914. }
  59915. }
  59916. }
  59917. else {
  59918. dataFace = data[k];
  59919. }
  59920. // Fill the array accordingly.
  59921. if (byteArray) {
  59922. results.push(byteArray);
  59923. }
  59924. else {
  59925. results.push(dataFace);
  59926. }
  59927. }
  59928. return results;
  59929. };
  59930. 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);
  59931. };
  59932. /**
  59933. * Occurs when the file is raw .hdr file.
  59934. */
  59935. HDRCubeTexture.prototype.loadHDRTexture = function () {
  59936. var _this = this;
  59937. var callback = function (buffer) {
  59938. // Extract the raw linear data.
  59939. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  59940. // Generate harmonics if needed.
  59941. if (_this._generateHarmonics) {
  59942. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  59943. }
  59944. var results = [];
  59945. var byteArray = null;
  59946. // Push each faces.
  59947. for (var j = 0; j < 6; j++) {
  59948. // Create uintarray fallback.
  59949. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59950. // 3 channels of 1 bytes per pixel in bytes.
  59951. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  59952. byteArray = new Uint8Array(byteBuffer);
  59953. }
  59954. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  59955. // If special cases.
  59956. if (_this._useInGammaSpace || byteArray) {
  59957. for (var i = 0; i < _this._size * _this._size; i++) {
  59958. // Put in gamma space if requested.
  59959. if (_this._useInGammaSpace) {
  59960. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59961. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59962. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59963. }
  59964. // Convert to int texture for fallback.
  59965. if (byteArray) {
  59966. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59967. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59968. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59969. // May use luminance instead if the result is not accurate.
  59970. var max = Math.max(Math.max(r, g), b);
  59971. if (max > 255) {
  59972. var scale = 255 / max;
  59973. r *= scale;
  59974. g *= scale;
  59975. b *= scale;
  59976. }
  59977. byteArray[(i * 3) + 0] = r;
  59978. byteArray[(i * 3) + 1] = g;
  59979. byteArray[(i * 3) + 2] = b;
  59980. }
  59981. }
  59982. }
  59983. if (byteArray) {
  59984. results.push(byteArray);
  59985. }
  59986. else {
  59987. results.push(dataFace);
  59988. }
  59989. }
  59990. return results;
  59991. };
  59992. var mipmapGenerator = null;
  59993. if (!this._noMipmap &&
  59994. this._usePMREMGenerator) {
  59995. mipmapGenerator = function (data) {
  59996. // Custom setup of the generator matching with the PBR shader values.
  59997. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  59998. return generator.filterCubeMap();
  59999. };
  60000. }
  60001. 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);
  60002. };
  60003. /**
  60004. * Starts the loading process of the texture.
  60005. */
  60006. HDRCubeTexture.prototype.loadTexture = function () {
  60007. if (this._isBABYLONPreprocessed) {
  60008. this.loadBabylonTexture();
  60009. }
  60010. else {
  60011. this.loadHDRTexture();
  60012. }
  60013. };
  60014. HDRCubeTexture.prototype.clone = function () {
  60015. var size = this._isBABYLONPreprocessed ? null : this._size;
  60016. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  60017. // Base texture
  60018. newTexture.level = this.level;
  60019. newTexture.wrapU = this.wrapU;
  60020. newTexture.wrapV = this.wrapV;
  60021. newTexture.coordinatesIndex = this.coordinatesIndex;
  60022. newTexture.coordinatesMode = this.coordinatesMode;
  60023. return newTexture;
  60024. };
  60025. // Methods
  60026. HDRCubeTexture.prototype.delayLoad = function () {
  60027. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60028. return;
  60029. }
  60030. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  60031. this._texture = this._getFromCache(this.url, this._noMipmap);
  60032. if (!this._texture) {
  60033. this.loadTexture();
  60034. }
  60035. };
  60036. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  60037. return this._textureMatrix;
  60038. };
  60039. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60040. var texture = null;
  60041. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  60042. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  60043. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  60044. texture.name = parsedTexture.name;
  60045. texture.hasAlpha = parsedTexture.hasAlpha;
  60046. texture.level = parsedTexture.level;
  60047. texture.coordinatesMode = parsedTexture.coordinatesMode;
  60048. }
  60049. return texture;
  60050. };
  60051. HDRCubeTexture.prototype.serialize = function () {
  60052. if (!this.name) {
  60053. return null;
  60054. }
  60055. var serializationObject = {};
  60056. serializationObject.name = this.name;
  60057. serializationObject.hasAlpha = this.hasAlpha;
  60058. serializationObject.isCube = true;
  60059. serializationObject.level = this.level;
  60060. serializationObject.size = this._size;
  60061. serializationObject.coordinatesMode = this.coordinatesMode;
  60062. serializationObject.useInGammaSpace = this._useInGammaSpace;
  60063. serializationObject.generateHarmonics = this._generateHarmonics;
  60064. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  60065. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  60066. serializationObject.customType = "BABYLON.HDRCubeTexture";
  60067. return serializationObject;
  60068. };
  60069. /**
  60070. * Saves as a file the data contained in the texture in a binary format.
  60071. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  60072. * as the spherical used in the lighting.
  60073. * @param url The HDR file url.
  60074. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  60075. * @param onError Method called if any error happens during download.
  60076. * @return The packed binary data.
  60077. */
  60078. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  60079. if (onError === void 0) { onError = null; }
  60080. var callback = function (buffer) {
  60081. var data = new Blob([buffer], { type: 'application/octet-stream' });
  60082. // Returns a URL you can use as a href.
  60083. var objUrl = window.URL.createObjectURL(data);
  60084. // Simulates a link to it and click to dowload.
  60085. var a = document.createElement("a");
  60086. document.body.appendChild(a);
  60087. a.style.display = "none";
  60088. a.href = objUrl;
  60089. a.download = "envmap.babylon.hdr";
  60090. a.click();
  60091. };
  60092. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  60093. };
  60094. /**
  60095. * Serializes the data contained in the texture in a binary format.
  60096. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  60097. * as the spherical used in the lighting.
  60098. * @param url The HDR file url.
  60099. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  60100. * @param onError Method called if any error happens during download.
  60101. * @return The packed binary data.
  60102. */
  60103. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  60104. if (onError === void 0) { onError = null; }
  60105. // Needs the url tho create the texture.
  60106. if (!url) {
  60107. return null;
  60108. }
  60109. // Check Power of two size.
  60110. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  60111. return null;
  60112. }
  60113. var getDataCallback = function (dataBuffer) {
  60114. // Extract the raw linear data.
  60115. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  60116. // Generate harmonics if needed.
  60117. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  60118. // Generate seamless faces
  60119. var mipGeneratorArray = [];
  60120. // Data are known to be in +X +Y +Z -X -Y -Z
  60121. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  60122. mipGeneratorArray.push(cubeData.right); // +X
  60123. mipGeneratorArray.push(cubeData.left); // -X
  60124. mipGeneratorArray.push(cubeData.up); // +Y
  60125. mipGeneratorArray.push(cubeData.down); // -Y
  60126. mipGeneratorArray.push(cubeData.front); // +Z
  60127. mipGeneratorArray.push(cubeData.back); // -Z
  60128. // Custom setup of the generator matching with the PBR shader values.
  60129. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  60130. var mippedData = generator.filterCubeMap();
  60131. // Compute required byte length.
  60132. var byteLength = 1 * 4; // Raw Data Version int32.
  60133. byteLength += 4; // CubeMap max mip face size int32.
  60134. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  60135. // Add data size.
  60136. byteLength += 4; // Number of mip levels int32.
  60137. for (var level = 0; level < mippedData.length; level++) {
  60138. var mipSize = size >> level;
  60139. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  60140. }
  60141. // Prepare binary structure.
  60142. var buffer = new ArrayBuffer(byteLength);
  60143. var intArrayView = new Int32Array(buffer);
  60144. var floatArrayView = new Float32Array(buffer);
  60145. // Fill header.
  60146. intArrayView[0] = 1; // Version 1.
  60147. intArrayView[1] = size; // CubeMap max mip face size.
  60148. // Fill polynomial information.
  60149. sphericalPolynomial.x.toArray(floatArrayView, 2);
  60150. sphericalPolynomial.y.toArray(floatArrayView, 5);
  60151. sphericalPolynomial.z.toArray(floatArrayView, 8);
  60152. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  60153. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  60154. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  60155. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  60156. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  60157. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  60158. // Fill pixel data.
  60159. intArrayView[29] = mippedData.length; // Number of mip levels.
  60160. var startIndex = 30;
  60161. for (var level = 0; level < mippedData.length; level++) {
  60162. // Fill each pixel of the mip level.
  60163. var faceSize = Math.pow(size >> level, 2) * 3;
  60164. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  60165. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  60166. startIndex += faceSize;
  60167. }
  60168. }
  60169. // Callback.
  60170. callback(buffer);
  60171. };
  60172. // Download and process.
  60173. BABYLON.Tools.LoadFile(url, function (data) {
  60174. getDataCallback(data);
  60175. }, null, null, true, onError);
  60176. };
  60177. HDRCubeTexture._facesMapping = [
  60178. "right",
  60179. "up",
  60180. "front",
  60181. "left",
  60182. "down",
  60183. "back"
  60184. ];
  60185. return HDRCubeTexture;
  60186. })(BABYLON.BaseTexture);
  60187. BABYLON.HDRCubeTexture = HDRCubeTexture;
  60188. })(BABYLON || (BABYLON = {}));
  60189. var BABYLON;
  60190. (function (BABYLON) {
  60191. var Debug;
  60192. (function (Debug) {
  60193. /**
  60194. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  60195. */
  60196. var SkeletonViewer = (function () {
  60197. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  60198. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60199. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60200. this.skeleton = skeleton;
  60201. this.mesh = mesh;
  60202. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60203. this.renderingGroupId = renderingGroupId;
  60204. this.color = BABYLON.Color3.White();
  60205. this._debugLines = [];
  60206. this._isEnabled = false;
  60207. this._scene = scene;
  60208. this.update();
  60209. this._renderFunction = this.update.bind(this);
  60210. }
  60211. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60212. get: function () {
  60213. return this._isEnabled;
  60214. },
  60215. set: function (value) {
  60216. if (this._isEnabled === value) {
  60217. return;
  60218. }
  60219. this._isEnabled = value;
  60220. if (value) {
  60221. this._scene.registerBeforeRender(this._renderFunction);
  60222. }
  60223. else {
  60224. this._scene.unregisterBeforeRender(this._renderFunction);
  60225. }
  60226. },
  60227. enumerable: true,
  60228. configurable: true
  60229. });
  60230. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60231. if (x === void 0) { x = 0; }
  60232. if (y === void 0) { y = 0; }
  60233. if (z === void 0) { z = 0; }
  60234. var tmat = BABYLON.Tmp.Matrix[0];
  60235. var parentBone = bone.getParent();
  60236. tmat.copyFrom(bone.getLocalMatrix());
  60237. if (x !== 0 || y !== 0 || z !== 0) {
  60238. var tmat2 = BABYLON.Tmp.Matrix[1];
  60239. BABYLON.Matrix.IdentityToRef(tmat2);
  60240. tmat2.m[12] = x;
  60241. tmat2.m[13] = y;
  60242. tmat2.m[14] = z;
  60243. tmat2.multiplyToRef(tmat, tmat);
  60244. }
  60245. if (parentBone) {
  60246. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60247. }
  60248. tmat.multiplyToRef(meshMat, tmat);
  60249. position.x = tmat.m[12];
  60250. position.y = tmat.m[13];
  60251. position.z = tmat.m[14];
  60252. };
  60253. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60254. var len = bones.length;
  60255. for (var i = 0; i < len; i++) {
  60256. var bone = bones[i];
  60257. var points = this._debugLines[i];
  60258. if (!points) {
  60259. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60260. this._debugLines[i] = points;
  60261. }
  60262. this._getBonePosition(points[0], bone, meshMat);
  60263. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60264. }
  60265. };
  60266. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60267. var len = bones.length;
  60268. var boneNum = 0;
  60269. for (var i = len - 1; i >= 0; i--) {
  60270. var childBone = bones[i];
  60271. var parentBone = childBone.getParent();
  60272. if (!parentBone) {
  60273. continue;
  60274. }
  60275. var points = this._debugLines[boneNum];
  60276. if (!points) {
  60277. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60278. this._debugLines[boneNum] = points;
  60279. }
  60280. this._getBonePosition(points[0], childBone, meshMat);
  60281. this._getBonePosition(points[1], parentBone, meshMat);
  60282. boneNum++;
  60283. }
  60284. };
  60285. SkeletonViewer.prototype.update = function () {
  60286. if (this.autoUpdateBonesMatrices) {
  60287. this._updateBoneMatrix(this.skeleton.bones[0]);
  60288. }
  60289. if (this.skeleton.bones[0].length === undefined) {
  60290. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60291. }
  60292. else {
  60293. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60294. }
  60295. if (!this._debugMesh) {
  60296. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  60297. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60298. }
  60299. else {
  60300. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60301. }
  60302. this._debugMesh.color = this.color;
  60303. };
  60304. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  60305. if (bone.getParent()) {
  60306. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  60307. }
  60308. var children = bone.children;
  60309. var len = children.length;
  60310. for (var i = 0; i < len; i++) {
  60311. this._updateBoneMatrix(children[i]);
  60312. }
  60313. };
  60314. SkeletonViewer.prototype.dispose = function () {
  60315. if (this._debugMesh) {
  60316. this.isEnabled = false;
  60317. this._debugMesh.dispose();
  60318. this._debugMesh = null;
  60319. }
  60320. };
  60321. return SkeletonViewer;
  60322. })();
  60323. Debug.SkeletonViewer = SkeletonViewer;
  60324. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60325. })(BABYLON || (BABYLON = {}));
  60326. var BABYLON;
  60327. (function (BABYLON) {
  60328. /**
  60329. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  60330. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  60331. * 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;
  60332. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  60333. */
  60334. var ColorCurves = (function () {
  60335. function ColorCurves() {
  60336. this._dirty = true;
  60337. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  60338. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  60339. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  60340. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  60341. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  60342. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  60343. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  60344. this._globalHue = 30;
  60345. this._globalDensity = 0;
  60346. this._globalSaturation = 0;
  60347. this._globalExposure = 0;
  60348. this._highlightsHue = 30;
  60349. this._highlightsDensity = 0;
  60350. this._highlightsSaturation = 0;
  60351. this._highlightsExposure = 0;
  60352. this._midtonesHue = 30;
  60353. this._midtonesDensity = 0;
  60354. this._midtonesSaturation = 0;
  60355. this._midtonesExposure = 0;
  60356. this._shadowsHue = 30;
  60357. this._shadowsDensity = 0;
  60358. this._shadowsSaturation = 0;
  60359. this._shadowsExposure = 0;
  60360. }
  60361. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  60362. /**
  60363. * Gets the global Hue value.
  60364. * 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).
  60365. */
  60366. get: function () {
  60367. return this._globalHue;
  60368. },
  60369. /**
  60370. * Sets the global Hue value.
  60371. * 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).
  60372. */
  60373. set: function (value) {
  60374. this._globalHue = value;
  60375. this._dirty = true;
  60376. },
  60377. enumerable: true,
  60378. configurable: true
  60379. });
  60380. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  60381. /**
  60382. * Gets the global Density value.
  60383. * 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.
  60384. * Values less than zero provide a filter of opposite hue.
  60385. */
  60386. get: function () {
  60387. return this._globalDensity;
  60388. },
  60389. /**
  60390. * Sets the global Density value.
  60391. * 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.
  60392. * Values less than zero provide a filter of opposite hue.
  60393. */
  60394. set: function (value) {
  60395. this._globalDensity = value;
  60396. this._dirty = true;
  60397. },
  60398. enumerable: true,
  60399. configurable: true
  60400. });
  60401. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  60402. /**
  60403. * Gets the global Saturation value.
  60404. * 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.
  60405. */
  60406. get: function () {
  60407. return this._globalSaturation;
  60408. },
  60409. /**
  60410. * Sets the global Saturation value.
  60411. * 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.
  60412. */
  60413. set: function (value) {
  60414. this._globalSaturation = value;
  60415. this._dirty = true;
  60416. },
  60417. enumerable: true,
  60418. configurable: true
  60419. });
  60420. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  60421. /**
  60422. * Gets the highlights Hue value.
  60423. * 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).
  60424. */
  60425. get: function () {
  60426. return this._highlightsHue;
  60427. },
  60428. /**
  60429. * Sets the highlights Hue value.
  60430. * 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).
  60431. */
  60432. set: function (value) {
  60433. this._highlightsHue = value;
  60434. this._dirty = true;
  60435. },
  60436. enumerable: true,
  60437. configurable: true
  60438. });
  60439. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  60440. /**
  60441. * Gets the highlights Density value.
  60442. * 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.
  60443. * Values less than zero provide a filter of opposite hue.
  60444. */
  60445. get: function () {
  60446. return this._highlightsDensity;
  60447. },
  60448. /**
  60449. * Sets the highlights Density value.
  60450. * 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.
  60451. * Values less than zero provide a filter of opposite hue.
  60452. */
  60453. set: function (value) {
  60454. this._highlightsDensity = value;
  60455. this._dirty = true;
  60456. },
  60457. enumerable: true,
  60458. configurable: true
  60459. });
  60460. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  60461. /**
  60462. * Gets the highlights Saturation value.
  60463. * 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.
  60464. */
  60465. get: function () {
  60466. return this._highlightsSaturation;
  60467. },
  60468. /**
  60469. * Sets the highlights Saturation value.
  60470. * 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.
  60471. */
  60472. set: function (value) {
  60473. this._highlightsSaturation = value;
  60474. this._dirty = true;
  60475. },
  60476. enumerable: true,
  60477. configurable: true
  60478. });
  60479. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  60480. /**
  60481. * Gets the highlights Exposure value.
  60482. * 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.
  60483. */
  60484. get: function () {
  60485. return this._highlightsExposure;
  60486. },
  60487. /**
  60488. * Sets the highlights Exposure value.
  60489. * 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.
  60490. */
  60491. set: function (value) {
  60492. this._highlightsExposure = value;
  60493. this._dirty = true;
  60494. },
  60495. enumerable: true,
  60496. configurable: true
  60497. });
  60498. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  60499. /**
  60500. * Gets the midtones Hue value.
  60501. * 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).
  60502. */
  60503. get: function () {
  60504. return this._midtonesHue;
  60505. },
  60506. /**
  60507. * Sets the midtones Hue value.
  60508. * 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).
  60509. */
  60510. set: function (value) {
  60511. this._midtonesHue = value;
  60512. this._dirty = true;
  60513. },
  60514. enumerable: true,
  60515. configurable: true
  60516. });
  60517. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  60518. /**
  60519. * Gets the midtones Density value.
  60520. * 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.
  60521. * Values less than zero provide a filter of opposite hue.
  60522. */
  60523. get: function () {
  60524. return this._midtonesDensity;
  60525. },
  60526. /**
  60527. * Sets the midtones Density value.
  60528. * 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.
  60529. * Values less than zero provide a filter of opposite hue.
  60530. */
  60531. set: function (value) {
  60532. this._midtonesDensity = value;
  60533. this._dirty = true;
  60534. },
  60535. enumerable: true,
  60536. configurable: true
  60537. });
  60538. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  60539. /**
  60540. * Gets the midtones Saturation value.
  60541. * 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.
  60542. */
  60543. get: function () {
  60544. return this._midtonesSaturation;
  60545. },
  60546. /**
  60547. * Sets the midtones Saturation value.
  60548. * 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.
  60549. */
  60550. set: function (value) {
  60551. this._midtonesSaturation = value;
  60552. this._dirty = true;
  60553. },
  60554. enumerable: true,
  60555. configurable: true
  60556. });
  60557. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  60558. /**
  60559. * Gets the midtones Exposure value.
  60560. * 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.
  60561. */
  60562. get: function () {
  60563. return this._midtonesExposure;
  60564. },
  60565. /**
  60566. * Sets the midtones Exposure value.
  60567. * 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.
  60568. */
  60569. set: function (value) {
  60570. this._midtonesExposure = value;
  60571. this._dirty = true;
  60572. },
  60573. enumerable: true,
  60574. configurable: true
  60575. });
  60576. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  60577. /**
  60578. * Gets the shadows Hue value.
  60579. * 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).
  60580. */
  60581. get: function () {
  60582. return this._shadowsHue;
  60583. },
  60584. /**
  60585. * Sets the shadows Hue value.
  60586. * 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).
  60587. */
  60588. set: function (value) {
  60589. this._shadowsHue = value;
  60590. this._dirty = true;
  60591. },
  60592. enumerable: true,
  60593. configurable: true
  60594. });
  60595. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  60596. /**
  60597. * Gets the shadows Density value.
  60598. * 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.
  60599. * Values less than zero provide a filter of opposite hue.
  60600. */
  60601. get: function () {
  60602. return this._shadowsDensity;
  60603. },
  60604. /**
  60605. * Sets the shadows Density value.
  60606. * 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.
  60607. * Values less than zero provide a filter of opposite hue.
  60608. */
  60609. set: function (value) {
  60610. this._shadowsDensity = value;
  60611. this._dirty = true;
  60612. },
  60613. enumerable: true,
  60614. configurable: true
  60615. });
  60616. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  60617. /**
  60618. * Gets the shadows Saturation value.
  60619. * 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.
  60620. */
  60621. get: function () {
  60622. return this._shadowsSaturation;
  60623. },
  60624. /**
  60625. * Sets the shadows Saturation value.
  60626. * 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.
  60627. */
  60628. set: function (value) {
  60629. this._shadowsSaturation = value;
  60630. this._dirty = true;
  60631. },
  60632. enumerable: true,
  60633. configurable: true
  60634. });
  60635. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  60636. /**
  60637. * Gets the shadows Exposure value.
  60638. * 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.
  60639. */
  60640. get: function () {
  60641. return this._shadowsExposure;
  60642. },
  60643. /**
  60644. * Sets the shadows Exposure value.
  60645. * 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.
  60646. */
  60647. set: function (value) {
  60648. this._shadowsExposure = value;
  60649. this._dirty = true;
  60650. },
  60651. enumerable: true,
  60652. configurable: true
  60653. });
  60654. /**
  60655. * Binds the color curves to the shader.
  60656. * @param colorCurves The color curve to bind
  60657. * @param effect The effect to bind to
  60658. */
  60659. ColorCurves.Bind = function (colorCurves, effect) {
  60660. if (colorCurves._dirty) {
  60661. colorCurves._dirty = false;
  60662. // Fill in global info.
  60663. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  60664. // Compute highlights info.
  60665. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  60666. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  60667. // Compute midtones info.
  60668. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  60669. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  60670. // Compute shadows info.
  60671. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  60672. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  60673. // Compute deltas (neutral is midtones).
  60674. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  60675. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  60676. }
  60677. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  60678. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  60679. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  60680. };
  60681. /**
  60682. * Prepare the list of uniforms associated with the ColorCurves effects.
  60683. * @param uniformsList The list of uniforms used in the effect
  60684. */
  60685. ColorCurves.PrepareUniforms = function (uniformsList) {
  60686. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  60687. };
  60688. /**
  60689. * Returns color grading data based on a hue, density, saturation and exposure value.
  60690. * @param filterHue The hue of the color filter.
  60691. * @param filterDensity The density of the color filter.
  60692. * @param saturation The saturation.
  60693. * @param exposure The exposure.
  60694. * @param result The result data container.
  60695. */
  60696. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  60697. if (hue == null) {
  60698. return;
  60699. }
  60700. hue = ColorCurves.clamp(hue, 0, 360);
  60701. density = ColorCurves.clamp(density, -100, 100);
  60702. saturation = ColorCurves.clamp(saturation, -100, 100);
  60703. exposure = ColorCurves.clamp(exposure, -100, 100);
  60704. // Remap the slider/config filter density with non-linear mapping and also scale by half
  60705. // so that the maximum filter density is only 50% control. This provides fine control
  60706. // for small values and reasonable range.
  60707. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  60708. density *= 0.5;
  60709. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  60710. if (density < 0) {
  60711. density *= -1;
  60712. hue = (hue + 180) % 360;
  60713. }
  60714. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  60715. result.scaleToRef(2, result);
  60716. result.a = 1 + 0.01 * saturation;
  60717. };
  60718. /**
  60719. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  60720. * @param value The input slider value in range [-100,100].
  60721. * @returns Adjusted value.
  60722. */
  60723. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  60724. value /= 100;
  60725. var x = Math.abs(value);
  60726. x = Math.pow(x, 2);
  60727. if (value < 0) {
  60728. x *= -1;
  60729. }
  60730. x *= 100;
  60731. return x;
  60732. };
  60733. /**
  60734. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  60735. * @param hue The hue (H) input.
  60736. * @param saturation The saturation (S) input.
  60737. * @param brightness The brightness (B) input.
  60738. * @result An RGBA color represented as Vector4.
  60739. */
  60740. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  60741. var h = ColorCurves.clamp(hue, 0, 360);
  60742. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  60743. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  60744. if (s === 0) {
  60745. result.r = v;
  60746. result.g = v;
  60747. result.b = v;
  60748. }
  60749. else {
  60750. // sector 0 to 5
  60751. h /= 60;
  60752. var i = Math.floor(h);
  60753. // fractional part of h
  60754. var f = h - i;
  60755. var p = v * (1 - s);
  60756. var q = v * (1 - s * f);
  60757. var t = v * (1 - s * (1 - f));
  60758. switch (i) {
  60759. case 0:
  60760. result.r = v;
  60761. result.g = t;
  60762. result.b = p;
  60763. break;
  60764. case 1:
  60765. result.r = q;
  60766. result.g = v;
  60767. result.b = p;
  60768. break;
  60769. case 2:
  60770. result.r = p;
  60771. result.g = v;
  60772. result.b = t;
  60773. break;
  60774. case 3:
  60775. result.r = p;
  60776. result.g = q;
  60777. result.b = v;
  60778. break;
  60779. case 4:
  60780. result.r = t;
  60781. result.g = p;
  60782. result.b = v;
  60783. break;
  60784. default:
  60785. result.r = v;
  60786. result.g = p;
  60787. result.b = q;
  60788. break;
  60789. }
  60790. }
  60791. result.a = 1;
  60792. };
  60793. /**
  60794. * Returns a value clamped between min and max
  60795. * @param value The value to clamp
  60796. * @param min The minimum of value
  60797. * @param max The maximum of value
  60798. * @returns The clamped value.
  60799. */
  60800. ColorCurves.clamp = function (value, min, max) {
  60801. return Math.min(Math.max(value, min), max);
  60802. };
  60803. /**
  60804. * Clones the current color curve instance.
  60805. * @return The cloned curves
  60806. */
  60807. ColorCurves.prototype.clone = function () {
  60808. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  60809. };
  60810. /**
  60811. * Serializes the current color curve instance to a json representation.
  60812. * @return a JSON representation
  60813. */
  60814. ColorCurves.prototype.serialize = function () {
  60815. return BABYLON.SerializationHelper.Serialize(this);
  60816. };
  60817. /**
  60818. * Parses the color curve from a json representation.
  60819. * @param source the JSON source to parse
  60820. * @return The parsed curves
  60821. */
  60822. ColorCurves.Parse = function (source) {
  60823. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  60824. };
  60825. __decorate([
  60826. BABYLON.serialize()
  60827. ], ColorCurves.prototype, "_globalHue", void 0);
  60828. __decorate([
  60829. BABYLON.serialize()
  60830. ], ColorCurves.prototype, "_globalDensity", void 0);
  60831. __decorate([
  60832. BABYLON.serialize()
  60833. ], ColorCurves.prototype, "_globalSaturation", void 0);
  60834. __decorate([
  60835. BABYLON.serialize()
  60836. ], ColorCurves.prototype, "_globalExposure", void 0);
  60837. __decorate([
  60838. BABYLON.serialize()
  60839. ], ColorCurves.prototype, "_highlightsHue", void 0);
  60840. __decorate([
  60841. BABYLON.serialize()
  60842. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  60843. __decorate([
  60844. BABYLON.serialize()
  60845. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  60846. __decorate([
  60847. BABYLON.serialize()
  60848. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  60849. __decorate([
  60850. BABYLON.serialize()
  60851. ], ColorCurves.prototype, "_midtonesHue", void 0);
  60852. __decorate([
  60853. BABYLON.serialize()
  60854. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  60855. __decorate([
  60856. BABYLON.serialize()
  60857. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  60858. __decorate([
  60859. BABYLON.serialize()
  60860. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  60861. return ColorCurves;
  60862. })();
  60863. BABYLON.ColorCurves = ColorCurves;
  60864. })(BABYLON || (BABYLON = {}));
  60865. var BABYLON;
  60866. (function (BABYLON) {
  60867. /**
  60868. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  60869. * It can help converting any input color in a desired output one. This can then be used to create effects
  60870. * from sepia, black and white to sixties or futuristic rendering...
  60871. *
  60872. * The only supported format is currently 3dl.
  60873. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  60874. */
  60875. var ColorGradingTexture = (function (_super) {
  60876. __extends(ColorGradingTexture, _super);
  60877. /**
  60878. * Instantiates a ColorGradingTexture from the following parameters.
  60879. *
  60880. * @param url The location of the color gradind data (currently only supporting 3dl)
  60881. * @param scene The scene the texture will be used in
  60882. */
  60883. function ColorGradingTexture(url, scene) {
  60884. _super.call(this, scene);
  60885. if (!url) {
  60886. return;
  60887. }
  60888. this._textureMatrix = BABYLON.Matrix.Identity();
  60889. this.name = url;
  60890. this.url = url;
  60891. this.hasAlpha = false;
  60892. this.isCube = false;
  60893. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60894. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60895. this.anisotropicFilteringLevel = 1;
  60896. this._texture = this._getFromCache(url, true);
  60897. if (!this._texture) {
  60898. if (!scene.useDelayedTextureLoading) {
  60899. this.loadTexture();
  60900. }
  60901. else {
  60902. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  60903. }
  60904. }
  60905. }
  60906. /**
  60907. * Returns the texture matrix used in most of the material.
  60908. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  60909. */
  60910. ColorGradingTexture.prototype.getTextureMatrix = function () {
  60911. return this._textureMatrix;
  60912. };
  60913. /**
  60914. * Occurs when the file being loaded is a .3dl LUT file.
  60915. */
  60916. ColorGradingTexture.prototype.load3dlTexture = function () {
  60917. var _this = this;
  60918. var mipLevels = 0;
  60919. var floatArrayView = null;
  60920. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60921. this._texture = texture;
  60922. var callback = function (text) {
  60923. var data;
  60924. var tempData;
  60925. var line;
  60926. var lines = text.split('\n');
  60927. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  60928. var maxColor = 0;
  60929. for (var i = 0; i < lines.length; i++) {
  60930. line = lines[i];
  60931. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  60932. continue;
  60933. if (line.indexOf('#') === 0)
  60934. continue;
  60935. var words = line.split(" ");
  60936. if (size === 0) {
  60937. // Number of space + one
  60938. size = words.length;
  60939. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  60940. tempData = new Float32Array(size * size * size * 4);
  60941. continue;
  60942. }
  60943. if (size != 0) {
  60944. var r = Math.max(parseInt(words[0]), 0);
  60945. var g = Math.max(parseInt(words[1]), 0);
  60946. var b = Math.max(parseInt(words[2]), 0);
  60947. maxColor = Math.max(r, maxColor);
  60948. maxColor = Math.max(g, maxColor);
  60949. maxColor = Math.max(b, maxColor);
  60950. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  60951. tempData[pixelStorageIndex + 0] = r;
  60952. tempData[pixelStorageIndex + 1] = g;
  60953. tempData[pixelStorageIndex + 2] = b;
  60954. tempData[pixelStorageIndex + 3] = 0;
  60955. pixelIndexSlice++;
  60956. if (pixelIndexSlice % size == 0) {
  60957. pixelIndexH++;
  60958. pixelIndexSlice = 0;
  60959. if (pixelIndexH % size == 0) {
  60960. pixelIndexW++;
  60961. pixelIndexH = 0;
  60962. }
  60963. }
  60964. }
  60965. }
  60966. for (var i = 0; i < tempData.length; i++) {
  60967. var value = tempData[i];
  60968. data[i] = (value / maxColor * 255);
  60969. }
  60970. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  60971. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  60972. };
  60973. BABYLON.Tools.LoadFile(this.url, callback);
  60974. return this._texture;
  60975. };
  60976. /**
  60977. * Starts the loading process of the texture.
  60978. */
  60979. ColorGradingTexture.prototype.loadTexture = function () {
  60980. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  60981. this.load3dlTexture();
  60982. }
  60983. };
  60984. /**
  60985. * Clones the color gradind texture.
  60986. */
  60987. ColorGradingTexture.prototype.clone = function () {
  60988. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  60989. // Base texture
  60990. newTexture.level = this.level;
  60991. return newTexture;
  60992. };
  60993. /**
  60994. * Called during delayed load for textures.
  60995. */
  60996. ColorGradingTexture.prototype.delayLoad = function () {
  60997. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60998. return;
  60999. }
  61000. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  61001. this._texture = this._getFromCache(this.url, true);
  61002. if (!this._texture) {
  61003. this.loadTexture();
  61004. }
  61005. };
  61006. /**
  61007. * Binds the color grading to the shader.
  61008. * @param colorGrading The texture to bind
  61009. * @param effect The effect to bind to
  61010. */
  61011. ColorGradingTexture.Bind = function (colorGrading, effect) {
  61012. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  61013. var x = colorGrading.level; // Texture Level
  61014. var y = colorGrading.getSize().height; // Texture Size example with 8
  61015. var z = y - 1.0; // SizeMinusOne 8 - 1
  61016. var w = 1 / y; // Space of 1 slice 1 / 8
  61017. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  61018. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  61019. 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
  61020. 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
  61021. 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
  61022. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  61023. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  61024. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  61025. };
  61026. /**
  61027. * Prepare the list of uniforms associated with the ColorGrading effects.
  61028. * @param uniformsList The list of uniforms used in the effect
  61029. * @param samplersList The list of samplers used in the effect
  61030. */
  61031. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  61032. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  61033. samplersList.push("cameraColorGrading2DSampler");
  61034. };
  61035. /**
  61036. * Parses a color grading texture serialized by Babylon.
  61037. * @param parsedTexture The texture information being parsedTexture
  61038. * @param scene The scene to load the texture in
  61039. * @param rootUrl The root url of the data assets to load
  61040. * @return A color gradind texture
  61041. */
  61042. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  61043. var texture = null;
  61044. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  61045. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  61046. texture.name = parsedTexture.name;
  61047. texture.level = parsedTexture.level;
  61048. }
  61049. return texture;
  61050. };
  61051. /**
  61052. * Serializes the LUT texture to json format.
  61053. */
  61054. ColorGradingTexture.prototype.serialize = function () {
  61055. if (!this.name) {
  61056. return null;
  61057. }
  61058. var serializationObject = {};
  61059. serializationObject.name = this.name;
  61060. serializationObject.level = this.level;
  61061. serializationObject.customType = "BABYLON.ColorGradingTexture";
  61062. return serializationObject;
  61063. };
  61064. /**
  61065. * Empty line regex stored for GC.
  61066. */
  61067. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  61068. return ColorGradingTexture;
  61069. })(BABYLON.BaseTexture);
  61070. BABYLON.ColorGradingTexture = ColorGradingTexture;
  61071. })(BABYLON || (BABYLON = {}));
  61072. var BABYLON;
  61073. (function (BABYLON) {
  61074. var PBRMaterialDefines = (function (_super) {
  61075. __extends(PBRMaterialDefines, _super);
  61076. function PBRMaterialDefines() {
  61077. _super.call(this);
  61078. this.ALBEDO = false;
  61079. this.AMBIENT = false;
  61080. this.OPACITY = false;
  61081. this.OPACITYRGB = false;
  61082. this.REFLECTION = false;
  61083. this.EMISSIVE = false;
  61084. this.REFLECTIVITY = false;
  61085. this.BUMP = false;
  61086. this.PARALLAX = false;
  61087. this.PARALLAXOCCLUSION = false;
  61088. this.SPECULAROVERALPHA = false;
  61089. this.CLIPPLANE = false;
  61090. this.ALPHATEST = false;
  61091. this.ALPHAFROMALBEDO = false;
  61092. this.POINTSIZE = false;
  61093. this.FOG = false;
  61094. this.SPECULARTERM = false;
  61095. this.OPACITYFRESNEL = false;
  61096. this.EMISSIVEFRESNEL = false;
  61097. this.FRESNEL = false;
  61098. this.NORMAL = false;
  61099. this.UV1 = false;
  61100. this.UV2 = false;
  61101. this.VERTEXCOLOR = false;
  61102. this.VERTEXALPHA = false;
  61103. this.NUM_BONE_INFLUENCERS = 0;
  61104. this.BonesPerMesh = 0;
  61105. this.INSTANCES = false;
  61106. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  61107. this.MICROSURFACEAUTOMATIC = false;
  61108. this.EMISSIVEASILLUMINATION = false;
  61109. this.LINKEMISSIVEWITHALBEDO = false;
  61110. this.LIGHTMAP = false;
  61111. this.USELIGHTMAPASSHADOWMAP = false;
  61112. this.REFLECTIONMAP_3D = false;
  61113. this.REFLECTIONMAP_SPHERICAL = false;
  61114. this.REFLECTIONMAP_PLANAR = false;
  61115. this.REFLECTIONMAP_CUBIC = false;
  61116. this.REFLECTIONMAP_PROJECTION = false;
  61117. this.REFLECTIONMAP_SKYBOX = false;
  61118. this.REFLECTIONMAP_EXPLICIT = false;
  61119. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  61120. this.INVERTCUBICMAP = false;
  61121. this.LOGARITHMICDEPTH = false;
  61122. this.CAMERATONEMAP = false;
  61123. this.CAMERACONTRAST = false;
  61124. this.CAMERACOLORGRADING = false;
  61125. this.CAMERACOLORCURVES = false;
  61126. this.OVERLOADEDVALUES = false;
  61127. this.OVERLOADEDSHADOWVALUES = false;
  61128. this.USESPHERICALFROMREFLECTIONMAP = false;
  61129. this.REFRACTION = false;
  61130. this.REFRACTIONMAP_3D = false;
  61131. this.LINKREFRACTIONTOTRANSPARENCY = false;
  61132. this.REFRACTIONMAPINLINEARSPACE = false;
  61133. this.LODBASEDMICROSFURACE = false;
  61134. this.USEPHYSICALLIGHTFALLOFF = false;
  61135. this.RADIANCEOVERALPHA = false;
  61136. this.USEPMREMREFLECTION = false;
  61137. this.USEPMREMREFRACTION = false;
  61138. this.OPENGLNORMALMAP = false;
  61139. this.INVERTNORMALMAPX = false;
  61140. this.INVERTNORMALMAPY = false;
  61141. this.SHADOWFULLFLOAT = false;
  61142. this.rebuild();
  61143. }
  61144. return PBRMaterialDefines;
  61145. })(BABYLON.MaterialDefines);
  61146. /**
  61147. * The Physically based material of BJS.
  61148. *
  61149. * This offers the main features of a standard PBR material.
  61150. * For more information, please refer to the documentation :
  61151. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  61152. */
  61153. var PBRMaterial = (function (_super) {
  61154. __extends(PBRMaterial, _super);
  61155. /**
  61156. * Instantiates a new PBRMaterial instance.
  61157. *
  61158. * @param name The material name
  61159. * @param scene The scene the material will be use in.
  61160. */
  61161. function PBRMaterial(name, scene) {
  61162. var _this = this;
  61163. _super.call(this, name, scene);
  61164. /**
  61165. * Intensity of the direct lights e.g. the four lights available in your scene.
  61166. * This impacts both the direct diffuse and specular highlights.
  61167. */
  61168. this.directIntensity = 1.0;
  61169. /**
  61170. * Intensity of the emissive part of the material.
  61171. * This helps controlling the emissive effect without modifying the emissive color.
  61172. */
  61173. this.emissiveIntensity = 1.0;
  61174. /**
  61175. * Intensity of the environment e.g. how much the environment will light the object
  61176. * either through harmonics for rough material or through the refelction for shiny ones.
  61177. */
  61178. this.environmentIntensity = 1.0;
  61179. /**
  61180. * This is a special control allowing the reduction of the specular highlights coming from the
  61181. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  61182. */
  61183. this.specularIntensity = 1.0;
  61184. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  61185. /**
  61186. * Debug Control allowing disabling the bump map on this material.
  61187. */
  61188. this.disableBumpMap = false;
  61189. /**
  61190. * Debug Control helping enforcing or dropping the darkness of shadows.
  61191. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  61192. */
  61193. this.overloadedShadowIntensity = 1.0;
  61194. /**
  61195. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  61196. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  61197. */
  61198. this.overloadedShadeIntensity = 1.0;
  61199. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  61200. /**
  61201. * The camera exposure used on this material.
  61202. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  61203. * This corresponds to a photographic exposure.
  61204. */
  61205. this.cameraExposure = 1.0;
  61206. /**
  61207. * The camera contrast used on this material.
  61208. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  61209. */
  61210. this.cameraContrast = 1.0;
  61211. /**
  61212. * Color Grading 2D Lookup Texture.
  61213. * This allows special effects like sepia, black and white to sixties rendering style.
  61214. */
  61215. this.cameraColorGradingTexture = null;
  61216. /**
  61217. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  61218. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  61219. * 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;
  61220. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  61221. */
  61222. this.cameraColorCurves = null;
  61223. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  61224. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  61225. /**
  61226. * Debug Control allowing to overload the ambient color.
  61227. * This as to be use with the overloadedAmbientIntensity parameter.
  61228. */
  61229. this.overloadedAmbient = BABYLON.Color3.White();
  61230. /**
  61231. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  61232. */
  61233. this.overloadedAmbientIntensity = 0.0;
  61234. /**
  61235. * Debug Control allowing to overload the albedo color.
  61236. * This as to be use with the overloadedAlbedoIntensity parameter.
  61237. */
  61238. this.overloadedAlbedo = BABYLON.Color3.White();
  61239. /**
  61240. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  61241. */
  61242. this.overloadedAlbedoIntensity = 0.0;
  61243. /**
  61244. * Debug Control allowing to overload the reflectivity color.
  61245. * This as to be use with the overloadedReflectivityIntensity parameter.
  61246. */
  61247. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  61248. /**
  61249. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  61250. */
  61251. this.overloadedReflectivityIntensity = 0.0;
  61252. /**
  61253. * Debug Control allowing to overload the emissive color.
  61254. * This as to be use with the overloadedEmissiveIntensity parameter.
  61255. */
  61256. this.overloadedEmissive = BABYLON.Color3.White();
  61257. /**
  61258. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  61259. */
  61260. this.overloadedEmissiveIntensity = 0.0;
  61261. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  61262. /**
  61263. * Debug Control allowing to overload the reflection color.
  61264. * This as to be use with the overloadedReflectionIntensity parameter.
  61265. */
  61266. this.overloadedReflection = BABYLON.Color3.White();
  61267. /**
  61268. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  61269. */
  61270. this.overloadedReflectionIntensity = 0.0;
  61271. /**
  61272. * Debug Control allowing to overload the microsurface.
  61273. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  61274. */
  61275. this.overloadedMicroSurface = 0.0;
  61276. /**
  61277. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  61278. */
  61279. this.overloadedMicroSurfaceIntensity = 0.0;
  61280. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  61281. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  61282. /**
  61283. * AKA Diffuse Color in other nomenclature.
  61284. */
  61285. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  61286. /**
  61287. * AKA Specular Color in other nomenclature.
  61288. */
  61289. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  61290. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  61291. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  61292. /**
  61293. * AKA Glossiness in other nomenclature.
  61294. */
  61295. this.microSurface = 0.9;
  61296. /**
  61297. * source material index of refraction (IOR)' / 'destination material IOR.
  61298. */
  61299. this.indexOfRefraction = 0.66;
  61300. /**
  61301. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  61302. */
  61303. this.invertRefractionY = false;
  61304. /**
  61305. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  61306. * Materials half opaque for instance using refraction could benefit from this control.
  61307. */
  61308. this.linkRefractionWithTransparency = false;
  61309. /**
  61310. * The emissive and albedo are linked to never be more than one (Energy conservation).
  61311. */
  61312. this.linkEmissiveWithAlbedo = false;
  61313. this.useLightmapAsShadowmap = false;
  61314. /**
  61315. * In this mode, the emissive informtaion will always be added to the lighting once.
  61316. * A light for instance can be thought as emissive.
  61317. */
  61318. this.useEmissiveAsIllumination = false;
  61319. /**
  61320. * Secifies that the alpha is coming form the albedo channel alpha channel.
  61321. */
  61322. this.useAlphaFromAlbedoTexture = false;
  61323. /**
  61324. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  61325. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  61326. */
  61327. this.useSpecularOverAlpha = true;
  61328. /**
  61329. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  61330. */
  61331. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  61332. /**
  61333. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  61334. * The material will try to infer what glossiness each pixel should be.
  61335. */
  61336. this.useAutoMicroSurfaceFromReflectivityMap = false;
  61337. /**
  61338. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  61339. * the creation of the material.
  61340. */
  61341. this.useScalarInLinearSpace = false;
  61342. /**
  61343. * BJS is using an harcoded light falloff based on a manually sets up range.
  61344. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  61345. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  61346. */
  61347. this.usePhysicalLightFalloff = true;
  61348. /**
  61349. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  61350. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  61351. */
  61352. this.useRadianceOverAlpha = true;
  61353. /**
  61354. * Allows using the bump map in parallax mode.
  61355. */
  61356. this.useParallax = false;
  61357. /**
  61358. * Allows using the bump map in parallax occlusion mode.
  61359. */
  61360. this.useParallaxOcclusion = false;
  61361. /**
  61362. * Controls the scale bias of the parallax mode.
  61363. */
  61364. this.parallaxScaleBias = 0.05;
  61365. /**
  61366. * If sets to true, disables all the lights affecting the material.
  61367. */
  61368. this.disableLighting = false;
  61369. /**
  61370. * Number of Simultaneous lights allowed on the material.
  61371. */
  61372. this.maxSimultaneousLights = 4;
  61373. /**
  61374. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  61375. */
  61376. this.invertNormalMapX = false;
  61377. /**
  61378. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  61379. */
  61380. this.invertNormalMapY = false;
  61381. this._renderTargets = new BABYLON.SmartArray(16);
  61382. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  61383. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  61384. this._tempColor = new BABYLON.Color3();
  61385. this._defines = new PBRMaterialDefines();
  61386. this._cachedDefines = new PBRMaterialDefines();
  61387. this._myScene = null;
  61388. this._myShadowGenerator = null;
  61389. this._cachedDefines.BonesPerMesh = -1;
  61390. this.getRenderTargetTextures = function () {
  61391. _this._renderTargets.reset();
  61392. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  61393. _this._renderTargets.push(_this.reflectionTexture);
  61394. }
  61395. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  61396. _this._renderTargets.push(_this.refractionTexture);
  61397. }
  61398. return _this._renderTargets;
  61399. };
  61400. }
  61401. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  61402. get: function () {
  61403. return this._useLogarithmicDepth;
  61404. },
  61405. set: function (value) {
  61406. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  61407. },
  61408. enumerable: true,
  61409. configurable: true
  61410. });
  61411. PBRMaterial.prototype.needAlphaBlending = function () {
  61412. if (this.linkRefractionWithTransparency) {
  61413. return false;
  61414. }
  61415. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  61416. };
  61417. PBRMaterial.prototype.needAlphaTesting = function () {
  61418. if (this.linkRefractionWithTransparency) {
  61419. return false;
  61420. }
  61421. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  61422. };
  61423. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  61424. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  61425. };
  61426. PBRMaterial.prototype.getAlphaTestTexture = function () {
  61427. return this.albedoTexture;
  61428. };
  61429. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  61430. if (!mesh) {
  61431. return true;
  61432. }
  61433. if (this._defines.INSTANCES !== useInstances) {
  61434. return false;
  61435. }
  61436. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  61437. return true;
  61438. }
  61439. return false;
  61440. };
  61441. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  61442. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  61443. };
  61444. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  61445. if (!useScalarInLinear) {
  61446. color.toLinearSpaceToRef(ref);
  61447. }
  61448. else {
  61449. ref.r = color.r;
  61450. ref.g = color.g;
  61451. ref.b = color.b;
  61452. }
  61453. };
  61454. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  61455. var lightIndex = 0;
  61456. var depthValuesAlreadySet = false;
  61457. for (var index = 0; index < scene.lights.length; index++) {
  61458. var light = scene.lights[index];
  61459. if (!light.isEnabled()) {
  61460. continue;
  61461. }
  61462. if (!light.canAffectMesh(mesh)) {
  61463. continue;
  61464. }
  61465. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  61466. // GAMMA CORRECTION.
  61467. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  61468. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  61469. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  61470. if (defines["SPECULARTERM"]) {
  61471. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  61472. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  61473. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  61474. }
  61475. // Shadows
  61476. if (scene.shadowsEnabled) {
  61477. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  61478. }
  61479. lightIndex++;
  61480. if (lightIndex === maxSimultaneousLights)
  61481. break;
  61482. }
  61483. };
  61484. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  61485. if (this.checkReadyOnlyOnce) {
  61486. if (this._wasPreviouslyReady) {
  61487. return true;
  61488. }
  61489. }
  61490. var scene = this.getScene();
  61491. if (!this.checkReadyOnEveryCall) {
  61492. if (this._renderId === scene.getRenderId()) {
  61493. if (this._checkCache(scene, mesh, useInstances)) {
  61494. return true;
  61495. }
  61496. }
  61497. }
  61498. var engine = scene.getEngine();
  61499. var needNormals = false;
  61500. var needUVs = false;
  61501. this._defines.reset();
  61502. if (scene.texturesEnabled) {
  61503. // Textures
  61504. if (scene.texturesEnabled) {
  61505. if (scene.getEngine().getCaps().textureLOD) {
  61506. this._defines.LODBASEDMICROSFURACE = true;
  61507. }
  61508. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  61509. if (!this.albedoTexture.isReady()) {
  61510. return false;
  61511. }
  61512. else {
  61513. needUVs = true;
  61514. this._defines.ALBEDO = true;
  61515. }
  61516. }
  61517. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  61518. if (!this.ambientTexture.isReady()) {
  61519. return false;
  61520. }
  61521. else {
  61522. needUVs = true;
  61523. this._defines.AMBIENT = true;
  61524. }
  61525. }
  61526. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  61527. if (!this.opacityTexture.isReady()) {
  61528. return false;
  61529. }
  61530. else {
  61531. needUVs = true;
  61532. this._defines.OPACITY = true;
  61533. if (this.opacityTexture.getAlphaFromRGB) {
  61534. this._defines.OPACITYRGB = true;
  61535. }
  61536. }
  61537. }
  61538. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  61539. if (!this.reflectionTexture.isReady()) {
  61540. return false;
  61541. }
  61542. else {
  61543. needNormals = true;
  61544. this._defines.REFLECTION = true;
  61545. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  61546. this._defines.INVERTCUBICMAP = true;
  61547. }
  61548. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  61549. switch (this.reflectionTexture.coordinatesMode) {
  61550. case BABYLON.Texture.CUBIC_MODE:
  61551. case BABYLON.Texture.INVCUBIC_MODE:
  61552. this._defines.REFLECTIONMAP_CUBIC = true;
  61553. break;
  61554. case BABYLON.Texture.EXPLICIT_MODE:
  61555. this._defines.REFLECTIONMAP_EXPLICIT = true;
  61556. break;
  61557. case BABYLON.Texture.PLANAR_MODE:
  61558. this._defines.REFLECTIONMAP_PLANAR = true;
  61559. break;
  61560. case BABYLON.Texture.PROJECTION_MODE:
  61561. this._defines.REFLECTIONMAP_PROJECTION = true;
  61562. break;
  61563. case BABYLON.Texture.SKYBOX_MODE:
  61564. this._defines.REFLECTIONMAP_SKYBOX = true;
  61565. break;
  61566. case BABYLON.Texture.SPHERICAL_MODE:
  61567. this._defines.REFLECTIONMAP_SPHERICAL = true;
  61568. break;
  61569. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  61570. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  61571. break;
  61572. }
  61573. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  61574. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  61575. needNormals = true;
  61576. if (this.reflectionTexture.isPMREM) {
  61577. this._defines.USEPMREMREFLECTION = true;
  61578. }
  61579. }
  61580. }
  61581. }
  61582. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  61583. if (!this.lightmapTexture.isReady()) {
  61584. return false;
  61585. }
  61586. else {
  61587. needUVs = true;
  61588. this._defines.LIGHTMAP = true;
  61589. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  61590. }
  61591. }
  61592. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  61593. if (!this.emissiveTexture.isReady()) {
  61594. return false;
  61595. }
  61596. else {
  61597. needUVs = true;
  61598. this._defines.EMISSIVE = true;
  61599. }
  61600. }
  61601. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  61602. if (!this.reflectivityTexture.isReady()) {
  61603. return false;
  61604. }
  61605. else {
  61606. needUVs = true;
  61607. this._defines.REFLECTIVITY = true;
  61608. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  61609. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  61610. }
  61611. }
  61612. }
  61613. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  61614. if (!this.bumpTexture.isReady()) {
  61615. return false;
  61616. }
  61617. else {
  61618. needUVs = true;
  61619. this._defines.BUMP = true;
  61620. if (this.useParallax) {
  61621. this._defines.PARALLAX = true;
  61622. if (this.useParallaxOcclusion) {
  61623. this._defines.PARALLAXOCCLUSION = true;
  61624. }
  61625. }
  61626. if (this.invertNormalMapX) {
  61627. this._defines.INVERTNORMALMAPX = true;
  61628. }
  61629. if (this.invertNormalMapY) {
  61630. this._defines.INVERTNORMALMAPY = true;
  61631. }
  61632. }
  61633. }
  61634. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  61635. if (!this.refractionTexture.isReady()) {
  61636. return false;
  61637. }
  61638. else {
  61639. needUVs = true;
  61640. this._defines.REFRACTION = true;
  61641. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  61642. if (this.linkRefractionWithTransparency) {
  61643. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  61644. }
  61645. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  61646. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  61647. if (this.refractionTexture.isPMREM) {
  61648. this._defines.USEPMREMREFRACTION = true;
  61649. }
  61650. }
  61651. }
  61652. }
  61653. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  61654. if (!this.cameraColorGradingTexture.isReady()) {
  61655. return false;
  61656. }
  61657. else {
  61658. this._defines.CAMERACOLORGRADING = true;
  61659. }
  61660. }
  61661. }
  61662. // Effect
  61663. if (scene.clipPlane) {
  61664. this._defines.CLIPPLANE = true;
  61665. }
  61666. if (engine.getAlphaTesting()) {
  61667. this._defines.ALPHATEST = true;
  61668. }
  61669. if (this._shouldUseAlphaFromAlbedoTexture()) {
  61670. this._defines.ALPHAFROMALBEDO = true;
  61671. }
  61672. if (this.useEmissiveAsIllumination) {
  61673. this._defines.EMISSIVEASILLUMINATION = true;
  61674. }
  61675. if (this.linkEmissiveWithAlbedo) {
  61676. this._defines.LINKEMISSIVEWITHALBEDO = true;
  61677. }
  61678. if (this.useLogarithmicDepth) {
  61679. this._defines.LOGARITHMICDEPTH = true;
  61680. }
  61681. if (this.cameraContrast != 1) {
  61682. this._defines.CAMERACONTRAST = true;
  61683. }
  61684. if (this.cameraExposure != 1) {
  61685. this._defines.CAMERATONEMAP = true;
  61686. }
  61687. if (this.cameraColorCurves) {
  61688. this._defines.CAMERACOLORCURVES = true;
  61689. }
  61690. if (this.overloadedShadeIntensity != 1 ||
  61691. this.overloadedShadowIntensity != 1) {
  61692. this._defines.OVERLOADEDSHADOWVALUES = true;
  61693. }
  61694. if (this.overloadedMicroSurfaceIntensity > 0 ||
  61695. this.overloadedEmissiveIntensity > 0 ||
  61696. this.overloadedReflectivityIntensity > 0 ||
  61697. this.overloadedAlbedoIntensity > 0 ||
  61698. this.overloadedAmbientIntensity > 0 ||
  61699. this.overloadedReflectionIntensity > 0) {
  61700. this._defines.OVERLOADEDVALUES = true;
  61701. }
  61702. // Point size
  61703. if (this.pointsCloud || scene.forcePointsCloud) {
  61704. this._defines.POINTSIZE = true;
  61705. }
  61706. // Fog
  61707. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  61708. this._defines.FOG = true;
  61709. }
  61710. if (scene.lightsEnabled && !this.disableLighting) {
  61711. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  61712. }
  61713. if (BABYLON.StandardMaterial.FresnelEnabled) {
  61714. // Fresnel
  61715. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  61716. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61717. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  61718. this._defines.OPACITYFRESNEL = true;
  61719. }
  61720. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61721. this._defines.EMISSIVEFRESNEL = true;
  61722. }
  61723. needNormals = true;
  61724. this._defines.FRESNEL = true;
  61725. }
  61726. }
  61727. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  61728. this._defines.SPECULAROVERALPHA = true;
  61729. }
  61730. if (this.usePhysicalLightFalloff) {
  61731. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  61732. }
  61733. if (this.useRadianceOverAlpha) {
  61734. this._defines.RADIANCEOVERALPHA = true;
  61735. }
  61736. // Attribs
  61737. if (mesh) {
  61738. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61739. this._defines.NORMAL = true;
  61740. }
  61741. if (needUVs) {
  61742. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61743. this._defines.UV1 = true;
  61744. }
  61745. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61746. this._defines.UV2 = true;
  61747. }
  61748. }
  61749. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  61750. this._defines.VERTEXCOLOR = true;
  61751. if (mesh.hasVertexAlpha) {
  61752. this._defines.VERTEXALPHA = true;
  61753. }
  61754. }
  61755. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61756. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  61757. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  61758. }
  61759. // Instances
  61760. if (useInstances) {
  61761. this._defines.INSTANCES = true;
  61762. }
  61763. }
  61764. // Get correct effect
  61765. if (!this._defines.isEqual(this._cachedDefines)) {
  61766. this._defines.cloneTo(this._cachedDefines);
  61767. scene.resetCachedMaterial();
  61768. // Fallbacks
  61769. var fallbacks = new BABYLON.EffectFallbacks();
  61770. if (this._defines.REFLECTION) {
  61771. fallbacks.addFallback(0, "REFLECTION");
  61772. }
  61773. if (this._defines.REFRACTION) {
  61774. fallbacks.addFallback(0, "REFRACTION");
  61775. }
  61776. if (this._defines.REFLECTIVITY) {
  61777. fallbacks.addFallback(0, "REFLECTIVITY");
  61778. }
  61779. if (this._defines.BUMP) {
  61780. fallbacks.addFallback(0, "BUMP");
  61781. }
  61782. if (this._defines.PARALLAX) {
  61783. fallbacks.addFallback(1, "PARALLAX");
  61784. }
  61785. if (this._defines.PARALLAXOCCLUSION) {
  61786. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  61787. }
  61788. if (this._defines.SPECULAROVERALPHA) {
  61789. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  61790. }
  61791. if (this._defines.FOG) {
  61792. fallbacks.addFallback(1, "FOG");
  61793. }
  61794. if (this._defines.POINTSIZE) {
  61795. fallbacks.addFallback(0, "POINTSIZE");
  61796. }
  61797. if (this._defines.LOGARITHMICDEPTH) {
  61798. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  61799. }
  61800. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  61801. if (this._defines.SPECULARTERM) {
  61802. fallbacks.addFallback(0, "SPECULARTERM");
  61803. }
  61804. if (this._defines.OPACITYFRESNEL) {
  61805. fallbacks.addFallback(1, "OPACITYFRESNEL");
  61806. }
  61807. if (this._defines.EMISSIVEFRESNEL) {
  61808. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  61809. }
  61810. if (this._defines.FRESNEL) {
  61811. fallbacks.addFallback(3, "FRESNEL");
  61812. }
  61813. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  61814. fallbacks.addCPUSkinningFallback(0, mesh);
  61815. }
  61816. //Attributes
  61817. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61818. if (this._defines.NORMAL) {
  61819. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61820. }
  61821. if (this._defines.UV1) {
  61822. attribs.push(BABYLON.VertexBuffer.UVKind);
  61823. }
  61824. if (this._defines.UV2) {
  61825. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61826. }
  61827. if (this._defines.VERTEXCOLOR) {
  61828. attribs.push(BABYLON.VertexBuffer.ColorKind);
  61829. }
  61830. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  61831. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  61832. // Legacy browser patch
  61833. var shaderName = "pbr";
  61834. if (!scene.getEngine().getCaps().standardDerivatives) {
  61835. shaderName = "legacypbr";
  61836. }
  61837. var join = this._defines.toString();
  61838. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  61839. "vFogInfos", "vFogColor", "pointSize",
  61840. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  61841. "mBones",
  61842. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  61843. "depthValues",
  61844. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  61845. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  61846. "logarithmicDepthConstant",
  61847. "vSphericalX", "vSphericalY", "vSphericalZ",
  61848. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  61849. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  61850. "vMicrosurfaceTextureLods",
  61851. "vCameraInfos"
  61852. ];
  61853. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  61854. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  61855. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  61856. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  61857. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  61858. }
  61859. if (!this._effect.isReady()) {
  61860. return false;
  61861. }
  61862. this._renderId = scene.getRenderId();
  61863. this._wasPreviouslyReady = true;
  61864. if (mesh) {
  61865. if (!mesh._materialDefines) {
  61866. mesh._materialDefines = new PBRMaterialDefines();
  61867. }
  61868. this._defines.cloneTo(mesh._materialDefines);
  61869. }
  61870. return true;
  61871. };
  61872. PBRMaterial.prototype.unbind = function () {
  61873. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  61874. this._effect.setTexture("reflection2DSampler", null);
  61875. }
  61876. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  61877. this._effect.setTexture("refraction2DSampler", null);
  61878. }
  61879. _super.prototype.unbind.call(this);
  61880. };
  61881. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  61882. this._effect.setMatrix("world", world);
  61883. };
  61884. PBRMaterial.prototype.bind = function (world, mesh) {
  61885. this._myScene = this.getScene();
  61886. // Matrices
  61887. this.bindOnlyWorldMatrix(world);
  61888. // Bones
  61889. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  61890. if (this._myScene.getCachedMaterial() !== this) {
  61891. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  61892. if (BABYLON.StandardMaterial.FresnelEnabled) {
  61893. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  61894. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  61895. }
  61896. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61897. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  61898. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  61899. }
  61900. }
  61901. // Textures
  61902. if (this._myScene.texturesEnabled) {
  61903. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  61904. this._effect.setTexture("albedoSampler", this.albedoTexture);
  61905. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  61906. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  61907. }
  61908. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  61909. this._effect.setTexture("ambientSampler", this.ambientTexture);
  61910. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  61911. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  61912. }
  61913. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  61914. this._effect.setTexture("opacitySampler", this.opacityTexture);
  61915. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  61916. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  61917. }
  61918. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  61919. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  61920. if (this.reflectionTexture.isCube) {
  61921. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  61922. }
  61923. else {
  61924. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  61925. }
  61926. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  61927. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  61928. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  61929. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  61930. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  61931. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  61932. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  61933. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  61934. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  61935. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  61936. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  61937. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  61938. }
  61939. }
  61940. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  61941. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  61942. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  61943. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  61944. }
  61945. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  61946. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  61947. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  61948. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  61949. }
  61950. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  61951. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  61952. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  61953. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  61954. }
  61955. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  61956. this._effect.setTexture("bumpSampler", this.bumpTexture);
  61957. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  61958. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  61959. }
  61960. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  61961. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  61962. var depth = 1.0;
  61963. if (this.refractionTexture.isCube) {
  61964. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  61965. }
  61966. else {
  61967. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  61968. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  61969. if (this.refractionTexture.depth) {
  61970. depth = this.refractionTexture.depth;
  61971. }
  61972. }
  61973. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  61974. }
  61975. if ((this.reflectionTexture || this.refractionTexture)) {
  61976. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  61977. }
  61978. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  61979. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  61980. }
  61981. }
  61982. // Clip plane
  61983. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  61984. // Point size
  61985. if (this.pointsCloud) {
  61986. this._effect.setFloat("pointSize", this.pointSize);
  61987. }
  61988. // Colors
  61989. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  61990. // GAMMA CORRECTION.
  61991. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  61992. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  61993. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  61994. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  61995. // GAMMA CORRECTION.
  61996. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  61997. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  61998. // GAMMA CORRECTION.
  61999. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  62000. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  62001. }
  62002. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  62003. // GAMMA CORRECTION.
  62004. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  62005. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  62006. // Lights
  62007. if (this._myScene.lightsEnabled && !this.disableLighting) {
  62008. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  62009. }
  62010. // View
  62011. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  62012. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  62013. }
  62014. // Fog
  62015. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  62016. this._lightingInfos.x = this.directIntensity;
  62017. this._lightingInfos.y = this.emissiveIntensity;
  62018. this._lightingInfos.z = this.environmentIntensity;
  62019. this._lightingInfos.w = this.specularIntensity;
  62020. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  62021. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  62022. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  62023. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  62024. this._cameraInfos.x = this.cameraExposure;
  62025. this._cameraInfos.y = this.cameraContrast;
  62026. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  62027. if (this.cameraColorCurves) {
  62028. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  62029. }
  62030. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  62031. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  62032. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  62033. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  62034. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  62035. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  62036. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  62037. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  62038. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  62039. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  62040. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  62041. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  62042. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  62043. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  62044. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  62045. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  62046. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  62047. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  62048. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  62049. // Log. depth
  62050. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  62051. }
  62052. _super.prototype.bind.call(this, world, mesh);
  62053. this._myScene = null;
  62054. };
  62055. PBRMaterial.prototype.getAnimatables = function () {
  62056. var results = [];
  62057. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  62058. results.push(this.albedoTexture);
  62059. }
  62060. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  62061. results.push(this.ambientTexture);
  62062. }
  62063. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  62064. results.push(this.opacityTexture);
  62065. }
  62066. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  62067. results.push(this.reflectionTexture);
  62068. }
  62069. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  62070. results.push(this.emissiveTexture);
  62071. }
  62072. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  62073. results.push(this.reflectivityTexture);
  62074. }
  62075. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  62076. results.push(this.bumpTexture);
  62077. }
  62078. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  62079. results.push(this.lightmapTexture);
  62080. }
  62081. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  62082. results.push(this.refractionTexture);
  62083. }
  62084. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  62085. results.push(this.cameraColorGradingTexture);
  62086. }
  62087. return results;
  62088. };
  62089. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62090. if (forceDisposeTextures) {
  62091. if (this.albedoTexture) {
  62092. this.albedoTexture.dispose();
  62093. }
  62094. if (this.ambientTexture) {
  62095. this.ambientTexture.dispose();
  62096. }
  62097. if (this.opacityTexture) {
  62098. this.opacityTexture.dispose();
  62099. }
  62100. if (this.reflectionTexture) {
  62101. this.reflectionTexture.dispose();
  62102. }
  62103. if (this.emissiveTexture) {
  62104. this.emissiveTexture.dispose();
  62105. }
  62106. if (this.reflectivityTexture) {
  62107. this.reflectivityTexture.dispose();
  62108. }
  62109. if (this.bumpTexture) {
  62110. this.bumpTexture.dispose();
  62111. }
  62112. if (this.lightmapTexture) {
  62113. this.lightmapTexture.dispose();
  62114. }
  62115. if (this.refractionTexture) {
  62116. this.refractionTexture.dispose();
  62117. }
  62118. if (this.cameraColorGradingTexture) {
  62119. this.cameraColorGradingTexture.dispose();
  62120. }
  62121. }
  62122. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62123. };
  62124. PBRMaterial.prototype.clone = function (name) {
  62125. var _this = this;
  62126. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  62127. };
  62128. PBRMaterial.prototype.serialize = function () {
  62129. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  62130. serializationObject.customType = "BABYLON.PBRMaterial";
  62131. return serializationObject;
  62132. };
  62133. // Statics
  62134. PBRMaterial.Parse = function (source, scene, rootUrl) {
  62135. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  62136. };
  62137. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  62138. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  62139. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  62140. PBRMaterial._scaledReflection = new BABYLON.Color3();
  62141. __decorate([
  62142. BABYLON.serialize()
  62143. ], PBRMaterial.prototype, "directIntensity", void 0);
  62144. __decorate([
  62145. BABYLON.serialize()
  62146. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  62147. __decorate([
  62148. BABYLON.serialize()
  62149. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  62150. __decorate([
  62151. BABYLON.serialize()
  62152. ], PBRMaterial.prototype, "specularIntensity", void 0);
  62153. __decorate([
  62154. BABYLON.serialize()
  62155. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  62156. __decorate([
  62157. BABYLON.serialize()
  62158. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  62159. __decorate([
  62160. BABYLON.serialize()
  62161. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  62162. __decorate([
  62163. BABYLON.serialize()
  62164. ], PBRMaterial.prototype, "cameraExposure", void 0);
  62165. __decorate([
  62166. BABYLON.serialize()
  62167. ], PBRMaterial.prototype, "cameraContrast", void 0);
  62168. __decorate([
  62169. BABYLON.serializeAsTexture()
  62170. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  62171. __decorate([
  62172. BABYLON.serializeAsColorCurves()
  62173. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  62174. __decorate([
  62175. BABYLON.serializeAsColor3()
  62176. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  62177. __decorate([
  62178. BABYLON.serialize()
  62179. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  62180. __decorate([
  62181. BABYLON.serializeAsColor3()
  62182. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  62183. __decorate([
  62184. BABYLON.serialize()
  62185. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  62186. __decorate([
  62187. BABYLON.serializeAsColor3()
  62188. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  62189. __decorate([
  62190. BABYLON.serialize()
  62191. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  62192. __decorate([
  62193. BABYLON.serializeAsColor3()
  62194. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  62195. __decorate([
  62196. BABYLON.serialize()
  62197. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  62198. __decorate([
  62199. BABYLON.serializeAsColor3()
  62200. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  62201. __decorate([
  62202. BABYLON.serialize()
  62203. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  62204. __decorate([
  62205. BABYLON.serialize()
  62206. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  62207. __decorate([
  62208. BABYLON.serialize()
  62209. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  62210. __decorate([
  62211. BABYLON.serializeAsTexture()
  62212. ], PBRMaterial.prototype, "albedoTexture", void 0);
  62213. __decorate([
  62214. BABYLON.serializeAsTexture()
  62215. ], PBRMaterial.prototype, "ambientTexture", void 0);
  62216. __decorate([
  62217. BABYLON.serializeAsTexture()
  62218. ], PBRMaterial.prototype, "opacityTexture", void 0);
  62219. __decorate([
  62220. BABYLON.serializeAsTexture()
  62221. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  62222. __decorate([
  62223. BABYLON.serializeAsTexture()
  62224. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  62225. __decorate([
  62226. BABYLON.serializeAsTexture()
  62227. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  62228. __decorate([
  62229. BABYLON.serializeAsTexture()
  62230. ], PBRMaterial.prototype, "bumpTexture", void 0);
  62231. __decorate([
  62232. BABYLON.serializeAsTexture()
  62233. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  62234. __decorate([
  62235. BABYLON.serializeAsTexture()
  62236. ], PBRMaterial.prototype, "refractionTexture", void 0);
  62237. __decorate([
  62238. BABYLON.serializeAsColor3("ambient")
  62239. ], PBRMaterial.prototype, "ambientColor", void 0);
  62240. __decorate([
  62241. BABYLON.serializeAsColor3("albedo")
  62242. ], PBRMaterial.prototype, "albedoColor", void 0);
  62243. __decorate([
  62244. BABYLON.serializeAsColor3("reflectivity")
  62245. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  62246. __decorate([
  62247. BABYLON.serializeAsColor3("reflection")
  62248. ], PBRMaterial.prototype, "reflectionColor", void 0);
  62249. __decorate([
  62250. BABYLON.serializeAsColor3("emissive")
  62251. ], PBRMaterial.prototype, "emissiveColor", void 0);
  62252. __decorate([
  62253. BABYLON.serialize()
  62254. ], PBRMaterial.prototype, "microSurface", void 0);
  62255. __decorate([
  62256. BABYLON.serialize()
  62257. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  62258. __decorate([
  62259. BABYLON.serialize()
  62260. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  62261. __decorate([
  62262. BABYLON.serializeAsFresnelParameters()
  62263. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  62264. __decorate([
  62265. BABYLON.serializeAsFresnelParameters()
  62266. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  62267. __decorate([
  62268. BABYLON.serialize()
  62269. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  62270. __decorate([
  62271. BABYLON.serialize()
  62272. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  62273. __decorate([
  62274. BABYLON.serialize()
  62275. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  62276. __decorate([
  62277. BABYLON.serialize()
  62278. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  62279. __decorate([
  62280. BABYLON.serialize()
  62281. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  62282. __decorate([
  62283. BABYLON.serialize()
  62284. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  62285. __decorate([
  62286. BABYLON.serialize()
  62287. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  62288. __decorate([
  62289. BABYLON.serialize()
  62290. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  62291. __decorate([
  62292. BABYLON.serialize()
  62293. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  62294. __decorate([
  62295. BABYLON.serialize()
  62296. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  62297. __decorate([
  62298. BABYLON.serialize()
  62299. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  62300. __decorate([
  62301. BABYLON.serialize()
  62302. ], PBRMaterial.prototype, "useParallax", void 0);
  62303. __decorate([
  62304. BABYLON.serialize()
  62305. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  62306. __decorate([
  62307. BABYLON.serialize()
  62308. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  62309. __decorate([
  62310. BABYLON.serialize()
  62311. ], PBRMaterial.prototype, "disableLighting", void 0);
  62312. __decorate([
  62313. BABYLON.serialize()
  62314. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  62315. __decorate([
  62316. BABYLON.serialize()
  62317. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  62318. __decorate([
  62319. BABYLON.serialize()
  62320. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  62321. __decorate([
  62322. BABYLON.serialize()
  62323. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  62324. return PBRMaterial;
  62325. })(BABYLON.Material);
  62326. BABYLON.PBRMaterial = PBRMaterial;
  62327. })(BABYLON || (BABYLON = {}));
  62328. var BABYLON;
  62329. (function (BABYLON) {
  62330. var StandardRenderingPipeline = (function (_super) {
  62331. __extends(StandardRenderingPipeline, _super);
  62332. /**
  62333. * @constructor
  62334. * @param {string} name - The rendering pipeline name
  62335. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62336. * @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)
  62337. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  62338. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62339. */
  62340. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  62341. var _this = this;
  62342. if (originalPostProcess === void 0) { originalPostProcess = null; }
  62343. _super.call(this, scene.getEngine(), name);
  62344. this.downSampleX4PostProcess = null;
  62345. this.brightPassPostProcess = null;
  62346. this.gaussianBlurHPostProcesses = [];
  62347. this.gaussianBlurVPostProcesses = [];
  62348. this.textureAdderPostProcess = null;
  62349. this.depthOfFieldSourcePostProcess = null;
  62350. this.depthOfFieldPostProcess = null;
  62351. this.brightThreshold = 1.0;
  62352. this.gaussianCoefficient = 0.25;
  62353. this.gaussianMean = 1.0;
  62354. this.gaussianStandardDeviation = 1.0;
  62355. this.exposure = 1.0;
  62356. this.lensTexture = null;
  62357. this.depthOfFieldDistance = 10.0;
  62358. this._depthRenderer = null;
  62359. // Getters and setters
  62360. this._blurEnabled = true;
  62361. this._depthOfFieldEnabled = false;
  62362. // Initialize
  62363. this._scene = scene;
  62364. // Create pass post-processe
  62365. if (!originalPostProcess) {
  62366. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  62367. }
  62368. else {
  62369. this.originalPostProcess = originalPostProcess;
  62370. }
  62371. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  62372. // Create down sample X4 post-process
  62373. this._createDownSampleX4PostProcess(scene, ratio / 2);
  62374. // Create bright pass post-process
  62375. this._createBrightPassPostProcess(scene, ratio / 2);
  62376. // Create gaussian blur post-processes (down sampling blurs)
  62377. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  62378. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  62379. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  62380. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  62381. // Create texture adder post-process
  62382. this._createTextureAdderPostProcess(scene, ratio);
  62383. // Create depth-of-field source post-process
  62384. 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);
  62385. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.depthOfFieldSourcePostProcess; }, true));
  62386. // Create gaussian blur used by depth-of-field
  62387. this._createGaussianBlurPostProcesses(scene, ratio / 2, 4);
  62388. // Create depth-of-field post-process
  62389. this._createDepthOfFieldPostProcess(scene, ratio);
  62390. // Finish
  62391. scene.postProcessRenderPipelineManager.addPipeline(this);
  62392. if (cameras !== null) {
  62393. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62394. }
  62395. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfFieldSource", cameras);
  62396. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH4", cameras);
  62397. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV4", cameras);
  62398. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", cameras);
  62399. }
  62400. Object.defineProperty(StandardRenderingPipeline.prototype, "BlurEnabled", {
  62401. get: function () {
  62402. return this._blurEnabled;
  62403. },
  62404. set: function (enabled) {
  62405. if (enabled && !this._blurEnabled || !enabled && this._blurEnabled) {
  62406. for (var i = 0; i < this.gaussianBlurHPostProcesses.length - 1; i++) {
  62407. if (enabled) {
  62408. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._scene.cameras);
  62409. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._scene.cameras);
  62410. }
  62411. else {
  62412. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._scene.cameras);
  62413. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._scene.cameras);
  62414. }
  62415. }
  62416. }
  62417. this._blurEnabled = enabled;
  62418. },
  62419. enumerable: true,
  62420. configurable: true
  62421. });
  62422. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  62423. get: function () {
  62424. return this._depthOfFieldEnabled;
  62425. },
  62426. set: function (enabled) {
  62427. if (enabled && !this._depthOfFieldEnabled) {
  62428. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfFieldSource", this._scene.cameras);
  62429. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH4", this._scene.cameras);
  62430. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV4", this._scene.cameras);
  62431. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  62432. this._depthRenderer = this._scene.enableDepthRenderer();
  62433. }
  62434. else if (!enabled && this._depthOfFieldEnabled) {
  62435. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfFieldSource", this._scene.cameras);
  62436. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH4", this._scene.cameras);
  62437. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV4", this._scene.cameras);
  62438. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  62439. }
  62440. this._depthOfFieldEnabled = enabled;
  62441. },
  62442. enumerable: true,
  62443. configurable: true
  62444. });
  62445. // Down Sample X4 Post-Processs
  62446. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  62447. var _this = this;
  62448. var downSampleX4Offsets = new Array(32);
  62449. 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);
  62450. this.downSampleX4PostProcess.onApply = function (effect) {
  62451. var id = 0;
  62452. for (var i = -2; i < 2; i++) {
  62453. for (var j = -2; j < 2; j++) {
  62454. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  62455. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  62456. id += 2;
  62457. }
  62458. }
  62459. effect.setArray2("dsOffsets", downSampleX4Offsets);
  62460. };
  62461. // Add to pipeline
  62462. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  62463. };
  62464. // Brightpass Post-Process
  62465. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  62466. var _this = this;
  62467. var brightOffsets = new Array(8);
  62468. 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);
  62469. this.brightPassPostProcess.onApply = function (effect) {
  62470. var sU = (1.0 / _this.brightPassPostProcess.width);
  62471. var sV = (1.0 / _this.brightPassPostProcess.height);
  62472. brightOffsets[0] = -0.5 * sU;
  62473. brightOffsets[1] = 0.5 * sV;
  62474. brightOffsets[2] = 0.5 * sU;
  62475. brightOffsets[3] = 0.5 * sV;
  62476. brightOffsets[4] = -0.5 * sU;
  62477. brightOffsets[5] = -0.5 * sV;
  62478. brightOffsets[6] = 0.5 * sU;
  62479. brightOffsets[7] = -0.5 * sV;
  62480. effect.setArray2("dsOffsets", brightOffsets);
  62481. effect.setFloat("brightThreshold", _this.brightThreshold);
  62482. };
  62483. // Add to pipeline
  62484. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  62485. };
  62486. // Create gaussian blur H&V post-processes
  62487. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  62488. var _this = this;
  62489. var blurOffsets = new Array(9);
  62490. var blurWeights = new Array(9);
  62491. var uniforms = ["blurOffsets", "blurWeights"];
  62492. var callback = function (height) {
  62493. return function (effect) {
  62494. // Weights
  62495. var x = 0.0;
  62496. for (var i = 0; i < 9; i++) {
  62497. x = (i - 4.0) / 4.0;
  62498. blurWeights[i] =
  62499. _this.gaussianCoefficient
  62500. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  62501. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  62502. }
  62503. var lastOutputDimensions = {
  62504. width: scene.getEngine().getRenderWidth(),
  62505. height: scene.getEngine().getRenderHeight()
  62506. };
  62507. for (var i = 0; i < 9; i++) {
  62508. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  62509. blurOffsets[i] = value;
  62510. }
  62511. effect.setArray("blurOffsets", blurOffsets);
  62512. effect.setArray("blurWeights", blurWeights);
  62513. };
  62514. };
  62515. // Create horizontal gaussian blur post-processes
  62516. 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);
  62517. gaussianBlurHPostProcess.onApply = callback(false);
  62518. // Create vertical gaussian blur post-process
  62519. 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);
  62520. gaussianBlurVPostProcess.onApply = callback(true);
  62521. // Add to pipeline
  62522. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  62523. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  62524. // Finish
  62525. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  62526. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  62527. };
  62528. // Create texture adder post-process
  62529. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  62530. var _this = this;
  62531. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  62532. 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);
  62533. this.textureAdderPostProcess.onApply = function (effect) {
  62534. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  62535. effect.setTexture("lensSampler", _this.lensTexture);
  62536. effect.setFloat("exposure", _this.exposure);
  62537. };
  62538. // Add to pipeline
  62539. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  62540. };
  62541. // Create depth-of-field post-process
  62542. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  62543. var _this = this;
  62544. 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);
  62545. this.depthOfFieldPostProcess.onApply = function (effect) {
  62546. effect.setTextureFromPostProcess("otherSampler", _this.depthOfFieldSourcePostProcess);
  62547. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  62548. effect.setFloat("distance", _this.depthOfFieldDistance);
  62549. };
  62550. // Add to pipeline
  62551. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  62552. };
  62553. return StandardRenderingPipeline;
  62554. })(BABYLON.PostProcessRenderPipeline);
  62555. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  62556. })(BABYLON || (BABYLON = {}));
  62557. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","ellipse2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","ellipse2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","lines2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","lines2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","rect2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","rect2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","sprite2dPixelShader":"varying vec2 vUV;\nvarying float vOpacity;\nuniform bool alphaTest;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest)\n{\nif (color.a<0.95) {\ndiscard;\n}\n}\ncolor.a*=vOpacity;\ngl_FragColor=color;\n}","sprite2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 scaleFactor;\natt vec2 textureSize;\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\nvoid main(void) {\nvec2 pos2;\n\nvec2 off=vec2(0.0,0.0);\nvec2 sfSizeUV=sizeUV*scaleFactor;\nfloat frame=properties.x;\nfloat invertY=properties.y;\nfloat alignToPixel=properties.z;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sfSizeUV.x)+off.x,topLeftUV.y-off.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sfSizeUV.x)+off.x,(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),topLeftUV.y-off.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\nif (alignToPixel == 1.0)\n{\npos.xy=floor(pos2.xy*sizeUV*textureSize);\n} else {\npos.xy=pos2.xy*sizeUV*textureSize;\n}\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n} ","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\ngl_FragColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\ngl_FragColor=color*vColor;\n}","text2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=floor(pos2.xy*superSampleFactor*sizeUV*textureSize); \npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  62558. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  62559. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:!(o.z-i>e.z)},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(0>r)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&s>c?(t.root=c,t.found=!0,t):h>0&&s>h?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,r){void 0===r&&(r=1.401298e-45);var n=t-i;return n>=-r&&r>=n},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r(-this.x,-this.y)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=0>o?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&2*o*e>s+h},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r(-this.x,-this.y,-this.z)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){r.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],r.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],r.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n,s=t.z+(i.z-t.z)*n;return new r(o,e,s)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(M.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,-(t.y/o*2-1),t.z),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(n,o,e,s){var h=n.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],R=0,T=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),r.CrossToRef(h,T,g),g.normalize(),r.Dot(a,g)<0&&(v=1),R=r.Dot(h,T),R=Math.min(1,Math.max(-1,R)),f=Math.acos(R)*v,r.Dot(T,u)<0&&(f=Math.PI+f,T=T.scaleInPlace(-1),d++);var _=M.Vector3[2],A=M.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),r.CrossToRef(_,T,A),A.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(T,g)<0&&(v=1),R=r.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,r.Dot(A,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,T,g),g.normalize(),r.Dot(g,m)<0&&(v=1),R=r.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,0>R&&2>d&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r(-this.x,-this.y,-this.z,-this.w)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return t?this.width===t.width&&this.height===t.height:!1},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.substract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r,n,o,e=this.x,s=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=e*s+h*a;if(u>.499&&(r=2*Math.atan2(e,a),n=Math.PI/2,o=0),-.499>u&&(r=-2*Math.atan2(e,a),n=-Math.PI/2,o=0),isNaN(r)){var m=e*e,y=s*s,c=h*h;r=Math.atan2(2*s*a-2*e*h,1-2*y-2*c),n=Math.asin(2*u),o=Math.atan2(2*e*a-2*s*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=r,t.z=n,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var r=new t;return t.FromRotationMatrixToRef(i,r),r},t.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,r){return t.RotationAxisToRef(i,r,new t)},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,r,n){var o,e,s=n,h=i.x*r.x+i.y*r.y+i.z*r.z+i.w*r.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}return new t(e*i.x+o*r.x,e*i.y+o*r.y,e*i.z+o*r.z,e*i.w+o*r.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14]},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var r=new t;return this.addToRef(i,r),r},t.prototype.addToRef=function(t,i){for(var r=0;16>r;r++)i.m[r]=this.m[r]+t.m[r];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),b=1/(i*T+r*_+n*M+o*A),F=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,D=s*y-h*m,q=e*c-a*u,V=e*y-h*u,N=e*m-s*u;return t.m[0]=T*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=A*b,t.m[1]=-(r*z-n*w+o*v)*b,t.m[5]=(i*z-n*d+o*g)*b,t.m[9]=-(i*w-r*d+o*R)*b,t.m[13]=(i*v-r*g+n*R)*b,t.m[2]=(r*F-n*L+o*C)*b,t.m[6]=-(i*F-n*P+o*Z)*b,t.m[10]=(i*L-r*P+o*S)*b,t.m[14]=-(i*C-r*Z+n*S)*b,t.m[3]=-(r*I-n*H+o*D)*b,t.m[7]=(i*I-n*q+o*V)*b,t.m[11]=-(i*H-r*q+o*N)*b,t.m[15]=(i*D-r*V+n*N)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var r=new t;return this.multiplyToRef(i,r),r},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;16>r;r++)t[i+r]=this.m[r];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),\nthis},t.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],b=t.m[8],F=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*b+s*P,i[r+1]=n*d+o*_+e*F+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*b+m*P,i[r+5]=h*d+a*_+u*F+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*b+f*P,i[r+9]=y*d+c*_+p*F+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*b+w*P,i[r+13]=x*d+l*_+z*F+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+z*C+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;16>i;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(r,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(r.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),r.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),r.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===r.x||0===r.y||0===r.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=t.FromValues(this.m[0]/r.x,this.m[1]/r.x,this.m[2]/r.x,0,this.m[4]/r.y,this.m[5]/r.y,this.m[6]/r.y,0,this.m[8]/r.z,this.m[9]/r.z,this.m[10]/r.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,n),!0},t.FromArray=function(i,r){var n=new t;return r||(r=0),t.FromArrayToRef(i,r,n),n},t.FromArrayToRef=function(t,i,r){for(var n=0;16>n;n++)r.m[n]=t[n+i]},t.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;16>o;o++)n.m[o]=t[o+i]*r},t.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},t.prototype.getRow=function(t){if(0>t||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(0>t||t>3)return this;var r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},t.FromValues=function(i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new t;return z.m[0]=i,z.m[1]=r,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},t.Compose=function(i,r,n){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return r.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var r=new t;return t.RotationXToRef(i,r),r},t.Invert=function(i){var r=new t;return i.invertToRef(r),r},t.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var r=new t;return t.RotationYToRef(i,r),r},t.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var r=new t;return t.RotationZToRef(i,r),r},t.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,r){var n=t.Zero();return t.RotationAxisToRef(i,r,n),n},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},t.Scaling=function(i,r,n){var o=t.Zero();return t.ScalingToRef(i,r,n,o),o},t.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},t.Translation=function(i,r,n){var o=t.Identity();return t.TranslationToRef(i,r,n,o),o},t.TranslationToRef=function(i,r,n,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,r,n,1,o)},t.Lerp=function(i,r,n){for(var o=t.Zero(),e=0;16>e;e++)o.m[e]=i.m[e]*(1-n)+r.m[e]*n;return o},t.DecomposeLerp=function(i,r,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);r.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return t.Compose(c,p,f)},t.LookAtLH=function(i,r,n){var o=t.Zero();return t.LookAtLHToRef(i,r,n,o),o},t.LookAtLHToRef=function(i,r,n,o){r.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.LookAtRH=function(i,r,n){var o=t.Zero();return t.LookAtRHToRef(i,r,n,o),o},t.LookAtRHToRef=function(i,r,n,o){i.subtractToRef(r,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.OrthoLH=function(i,r,n,o){var e=t.Zero();return t.OrthoLHToRef(i,r,n,o,e),e},t.OrthoLHToRef=function(i,r,n,o,e){var s=2/i,h=2/r,a=1/(o-n),u=n/(n-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,r,n,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(n-r),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=1/(e-o),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(n+r)/(r-n),s.m[14]=-o/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,r,n,o,e,s,h){t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h.m[10]*=-1},t.PerspectiveLH=function(i,r,n,o){var e=t.Zero();return e.m[0]=2*n/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*n/r,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(n-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=n*o/(n-o),e},t.PerspectiveFovLH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,r,n,o,e),e},t.PerspectiveFovLHToRef=function(t,i,r,n,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=n/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(r*n)/(n-r)},t.PerspectiveFovRH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,r,n,o,e),e},t.PerspectiveFovRHToRef=function(t,i,r,n,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=n/(r-n),o.m[11]=-1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=r*n/(r-n)},t.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-r/(i-r),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=i*r/(i-r)},t.GetFinalMatrix=function(i,r,n,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return r.multiply(n).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var r=new t;return r.m[0]=i.m[0],r.m[1]=i.m[4],r.m[2]=i.m[8],r.m[3]=i.m[12],r.m[4]=i.m[1],r.m[5]=i.m[5],r.m[6]=i.m[9],r.m[7]=i.m[13],r.m[8]=i.m[2],r.m[9]=i.m[6],r.m[10]=i.m[10],r.m[11]=i.m[14],r.m[12]=i.m[3],r.m[13]=i.m[7],r.m[14]=i.m[11],r.m[15]=i.m[15],r},t.Reflection=function(i){var r=new t;return t.ReflectionToRef(i,r),r},t.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var r=e.Dot(this.normal,t);return i>=r},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;6>n;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var z=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===x.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;e>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&u>=i){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=w;var v=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,-1,0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var R=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=R;var T=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var _=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[r.Black(),r.Black(),r.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  62560. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  62561. module.exports = BABYLON;
  62562. };